feat: recover interrupted installation preparation safely
This commit is contained in:
@@ -4,6 +4,7 @@ import { mkdirSync, mkdtempSync, realpathSync, existsSync, readFileSync, rmSync,
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { parse } from 'yaml';
|
||||
import { prepareBundle } from './release-bundle.mjs';
|
||||
import { commandRunner } from './publish-installation.mjs';
|
||||
@@ -24,14 +25,17 @@ export async function buildSourceImages({ run, source, output, revision, version
|
||||
const images = {};
|
||||
for (const role of ['core', 'frontend']) {
|
||||
const iid = join(output, `${role}.iid`);
|
||||
await run('docker', ['buildx', 'build', '--load', '--platform', platform, '--file', `docker/${role}.Dockerfile`,
|
||||
const localTag = `thothii-source-${role}:${randomBytes(16).toString('hex')}`;
|
||||
await run('docker', ['buildx', 'build', '--load', '--tag', localTag, '--platform', platform, '--file', `docker/${role}.Dockerfile`,
|
||||
'--iidfile', iid, '--build-arg', `IMAGE_VERSION=${version}`, '--label', `org.opencontainers.image.revision=${revision}`,
|
||||
'--label', `org.opencontainers.image.version=${version}`, '--provenance=false', '--sbom=false', '.'], { cwd: source, timeout: 45 * 60_000 });
|
||||
const id = readFileSync(iid, 'utf8').trim();
|
||||
if (!/^sha256:[a-f0-9]{64}$/.test(id)) throw new Error('Source build did not produce an immutable local image identity.');
|
||||
const image = JSON.parse(await run('docker', ['image', 'inspect', '--format', '{{json .}}', id], { quiet: true }));
|
||||
if (image.Id !== id || `${image.Os}/${image.Architecture}` !== platform || image.Config?.Labels?.['org.opencontainers.image.revision'] !== revision || image.Config?.Labels?.['org.opencontainers.image.version'] !== version) throw new Error('Built image identity differs from the selected source.');
|
||||
images[role] = id;
|
||||
// Containerd and classic Docker stores expose different IDs; resolve the local
|
||||
// daemon identity through our unique build tag, then pin that immutable ID.
|
||||
const image = JSON.parse(await run('docker', ['image', 'inspect', '--format', '{{json .}}', localTag], { quiet: true }));
|
||||
if (!/^sha256:[a-f0-9]{64}$/.test(image.Id ?? '') || `${image.Os}/${image.Architecture}` !== platform || image.Config?.Labels?.['org.opencontainers.image.revision'] !== revision || image.Config?.Labels?.['org.opencontainers.image.version'] !== version) throw new Error('Built image identity differs from the selected source.');
|
||||
images[role] = image.Id;
|
||||
}
|
||||
return images;
|
||||
}
|
||||
|
||||
@@ -18,7 +18,8 @@ test('source builds load local images from the isolated checkout without publica
|
||||
assert.ok(!args.includes('--push'));
|
||||
assert.ok(!args.includes('--secret'));
|
||||
assert.deepEqual(args.filter((_, index) => args[index - 1] === '--build-arg'), [`IMAGE_VERSION=${version}`]);
|
||||
writeFileSync(args[args.indexOf('--iidfile') + 1], `sha256:${'a'.repeat(64)}`);
|
||||
// Containerd may expose the manifest as local Id while Buildx writes its config digest.
|
||||
writeFileSync(args[args.indexOf('--iidfile') + 1], `sha256:${'b'.repeat(64)}`);
|
||||
return '';
|
||||
}
|
||||
return JSON.stringify({ Id: `sha256:${'a'.repeat(64)}`, Os: 'linux', Architecture: 'amd64', Config: { Labels: { 'org.opencontainers.image.revision': revision, 'org.opencontainers.image.version': version } } });
|
||||
|
||||
@@ -78,6 +78,7 @@ export class MemoryCatalogRepository implements CatalogRepository {
|
||||
async beginPreprocessing(
|
||||
workspaceId: string,
|
||||
inputFingerprint: string,
|
||||
runId?: string,
|
||||
): Promise<CatalogPreprocessingStartResult> {
|
||||
const database = [...this.records.values()].find((record) => record.workspaceId === workspaceId);
|
||||
if (!database) return { kind: "not_found" };
|
||||
@@ -96,6 +97,7 @@ export class MemoryCatalogRepository implements CatalogRepository {
|
||||
...database,
|
||||
preprocessingStatus: "running",
|
||||
preprocessingInputFingerprint: inputFingerprint,
|
||||
preprocessingRunId: runId,
|
||||
preprocessedMetadataRevision: undefined,
|
||||
preprocessingStartedAt: now,
|
||||
preprocessingFinishedAt: undefined,
|
||||
@@ -110,12 +112,14 @@ export class MemoryCatalogRepository implements CatalogRepository {
|
||||
metadataContentRevision: number,
|
||||
inputFingerprint: string,
|
||||
outcome: { status: "succeeded" } | { status: "failed"; errorCode: string },
|
||||
runId?: string,
|
||||
): Promise<WorkspaceDatabase | undefined> {
|
||||
const database = [...this.records.values()].find((record) => record.workspaceId === workspaceId);
|
||||
if (!database
|
||||
|| database.preprocessingStatus !== "running"
|
||||
|| database.metadataContentRevision !== metadataContentRevision
|
||||
|| database.preprocessingInputFingerprint !== inputFingerprint) return undefined;
|
||||
|| database.preprocessingInputFingerprint !== inputFingerprint
|
||||
|| database.preprocessingRunId !== runId) return undefined;
|
||||
const updated: WorkspaceDatabase = {
|
||||
...database,
|
||||
preprocessingStatus: outcome.status,
|
||||
|
||||
@@ -17,6 +17,7 @@ import * as localSensitivityAnalysisMigration from "./migrations/011_local_sensi
|
||||
import * as sensitivityReasonMigration from "./migrations/012_sensitivity_reason.js";
|
||||
import * as catalogPreprocessingStateMigration from "./migrations/013_catalog_preprocessing_state.js";
|
||||
import * as installationBindingImportsMigration from "./migrations/014_installation_binding_imports.js";
|
||||
import * as preprocessingRunIdentityMigration from "./migrations/015_preprocessing_run_identity.js";
|
||||
|
||||
const connectionString = process.env.THT_CATALOG_MIGRATOR_DATABASE_URL;
|
||||
const host = process.env.THT_CATALOG_DB_HOST;
|
||||
@@ -56,6 +57,7 @@ const provider: MigrationProvider = {
|
||||
"012_sensitivity_reason": sensitivityReasonMigration,
|
||||
"013_catalog_preprocessing_state": catalogPreprocessingStateMigration,
|
||||
"014_installation_binding_imports": installationBindingImportsMigration,
|
||||
"015_preprocessing_run_identity": preprocessingRunIdentityMigration,
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { Kysely } from "kysely";
|
||||
import type { CatalogDatabase } from "../repository.js";
|
||||
|
||||
/** Fences late completions when recovery repeats exactly the same input revision. */
|
||||
export async function up(db: Kysely<CatalogDatabase>): Promise<void> {
|
||||
await db.schema.alterTable("workspace_databases")
|
||||
.addColumn("preprocessing_run_id", "text").execute();
|
||||
}
|
||||
|
||||
export async function down(db: Kysely<CatalogDatabase>): Promise<void> {
|
||||
await db.schema.alterTable("workspace_databases")
|
||||
.dropColumn("preprocessing_run_id").execute();
|
||||
}
|
||||
@@ -76,6 +76,7 @@ interface WorkspaceDatabaseTable {
|
||||
metadataContentRevision: Generated<number>;
|
||||
preprocessingStatus: Generated<WorkspaceDatabase["preprocessingStatus"]>;
|
||||
preprocessingInputFingerprint: Generated<string | null>;
|
||||
preprocessingRunId: Generated<string | null>;
|
||||
preprocessedMetadataRevision: Generated<number | null>;
|
||||
preprocessingStartedAt: NullableTimestamp;
|
||||
preprocessingFinishedAt: NullableTimestamp;
|
||||
@@ -343,6 +344,7 @@ function serialize(row: JoinedRow): WorkspaceDatabase {
|
||||
metadataContentRevision: Number(row.metadataContentRevision),
|
||||
preprocessingStatus: row.preprocessingStatus,
|
||||
preprocessingInputFingerprint: present(row.preprocessingInputFingerprint),
|
||||
preprocessingRunId: present(row.preprocessingRunId),
|
||||
preprocessedMetadataRevision: row.preprocessedMetadataRevision == null
|
||||
? undefined
|
||||
: Number(row.preprocessedMetadataRevision),
|
||||
@@ -508,6 +510,7 @@ export class KyselyCatalogRepository implements CatalogRepository {
|
||||
async beginPreprocessing(
|
||||
workspaceId: string,
|
||||
inputFingerprint: string,
|
||||
runId?: string,
|
||||
): Promise<CatalogPreprocessingStartResult> {
|
||||
return await this.db.transaction().execute(async (trx) => {
|
||||
const database = await trx.selectFrom("workspaceDatabases")
|
||||
@@ -540,6 +543,7 @@ export class KyselyCatalogRepository implements CatalogRepository {
|
||||
.set({
|
||||
preprocessingStatus: "running",
|
||||
preprocessingInputFingerprint: inputFingerprint,
|
||||
preprocessingRunId: runId ?? null,
|
||||
preprocessedMetadataRevision: null,
|
||||
preprocessingStartedAt: sql`now()`,
|
||||
preprocessingFinishedAt: null,
|
||||
@@ -557,6 +561,7 @@ export class KyselyCatalogRepository implements CatalogRepository {
|
||||
metadataContentRevision: number,
|
||||
inputFingerprint: string,
|
||||
outcome: { status: "succeeded" } | { status: "failed"; errorCode: string },
|
||||
runId?: string,
|
||||
): Promise<WorkspaceDatabase | undefined> {
|
||||
const result = await this.db.updateTable("workspaceDatabases")
|
||||
.set({
|
||||
@@ -570,6 +575,7 @@ export class KyselyCatalogRepository implements CatalogRepository {
|
||||
.where("preprocessingStatus", "=", "running")
|
||||
.where("metadataContentRevision", "=", metadataContentRevision)
|
||||
.where("preprocessingInputFingerprint", "=", inputFingerprint)
|
||||
.where("preprocessingRunId", runId === undefined ? "is" : "=", runId ?? null)
|
||||
.returning("id")
|
||||
.executeTakeFirst();
|
||||
return result ? await this.get(result.id) : undefined;
|
||||
|
||||
@@ -40,6 +40,7 @@ export interface WorkspaceDatabase {
|
||||
metadataContentRevision: number;
|
||||
preprocessingStatus: CatalogPreprocessingStatus;
|
||||
preprocessingInputFingerprint?: string;
|
||||
preprocessingRunId?: string;
|
||||
preprocessedMetadataRevision?: number;
|
||||
preprocessingStartedAt?: string;
|
||||
preprocessingFinishedAt?: string;
|
||||
@@ -453,12 +454,14 @@ export interface CatalogRepository {
|
||||
beginPreprocessing(
|
||||
workspaceId: string,
|
||||
inputFingerprint: string,
|
||||
runId?: string,
|
||||
): Promise<CatalogPreprocessingStartResult>;
|
||||
finishPreprocessing(
|
||||
workspaceId: string,
|
||||
metadataContentRevision: number,
|
||||
inputFingerprint: string,
|
||||
outcome: { status: "succeeded" } | { status: "failed"; errorCode: string },
|
||||
runId?: string,
|
||||
): Promise<WorkspaceDatabase | undefined>;
|
||||
clearPreprocessing(workspaceId: string): Promise<CatalogPreprocessingClearResult>;
|
||||
getCatalogMetrics(databaseId?: string): Promise<CatalogMetrics | undefined>;
|
||||
|
||||
@@ -155,7 +155,7 @@ export function createPiManagement(config: AppConfig, deps: PiManagementDeps): P
|
||||
|
||||
const installationConfig = (): PiInstallationConfig => {
|
||||
const settings = readSettings();
|
||||
const reasoning = config.defaults.thinking ?? settings.thinking;
|
||||
const reasoning = config.defaults.thinking ?? settings.thinking ?? "low";
|
||||
const selected = deps.modelCatalog.defaultInteraction
|
||||
? splitCanonicalModelId(deps.modelCatalog.defaultInteraction)
|
||||
: undefined;
|
||||
|
||||
@@ -28,7 +28,8 @@ export function installationRoutes(app: FastifyInstance, bindings: InstallationB
|
||||
return reply.code(result.connectionStatus === "reachable" ? 200 : 422).send(result);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) return reply.code(400).send({ code: "installation_input_invalid" });
|
||||
if (error instanceof InstallationReconciliationRequired || error instanceof CatalogConflictError || error instanceof CatalogOperationInProgressError) {
|
||||
if (error instanceof CatalogOperationInProgressError) return reply.code(409).send({ code: "installation_operation_pending" });
|
||||
if (error instanceof InstallationReconciliationRequired || error instanceof CatalogConflictError) {
|
||||
return reply.code(409).send({ code: "installation_reconciliation_required" });
|
||||
}
|
||||
return reply.code(503).send({ code: "installation_binding_unavailable" });
|
||||
|
||||
@@ -10,6 +10,7 @@ import type { ThtRunner } from "../tht/tht-runner.js";
|
||||
import type { WorkspacePreprocessingService } from "../workspaces/preprocessing-service.js";
|
||||
import type { PreprocessingJobState } from "../workspaces/preprocessing-state.js";
|
||||
import type { WorkspaceRegistry } from "../workspaces/registry.js";
|
||||
import { PreprocessingStateError } from "../workspaces/preprocessing-state.js";
|
||||
|
||||
const workspaceIdSchema = z.string().regex(/^[a-z][a-z0-9-]{2,62}$/);
|
||||
const ACTIVE_SYNC_STATES = new Set(["queued", "running", "awaiting_confirmation", "applying"]);
|
||||
@@ -317,6 +318,9 @@ export async function readWorkspacePreprocessingStatus(
|
||||
}
|
||||
|
||||
function safeError(reply: FastifyReply, error: unknown) {
|
||||
if (error instanceof PreprocessingStateError) {
|
||||
return reply.code(409).send({ code: "preprocessing_conflict", state: "running", message: "Preprocessing is still owned by another process." });
|
||||
}
|
||||
if (error instanceof CatalogUnavailableError) {
|
||||
return reply.code(503).send({
|
||||
code: "catalog_unavailable",
|
||||
@@ -357,7 +361,8 @@ export function workspacePreprocessingRoutes(
|
||||
try {
|
||||
const workspaceId = workspaceIdFrom(request);
|
||||
const before = await readWorkspacePreprocessingStatus(workspaceId, deps);
|
||||
if (!before.actionable) {
|
||||
const options = z.object({ recoverInterrupted: z.boolean().optional() }).strict().parse(request.body ?? {});
|
||||
if (!before.actionable && !(before.state === "running" && options.recoverInterrupted)) {
|
||||
return reply.code(409).send({ ...before, code: "preprocessing_blocked" });
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import { WorkspaceSecretStore } from "./workspaces/secret-store.js";
|
||||
import { WorkspacePreprocessingService, type WorkspaceOperationResult } from "./workspaces/preprocessing-service.js";
|
||||
import { createCatalogRepository } from "./catalog/repository.js";
|
||||
import type { CatalogRepository } from "./catalog/types.js";
|
||||
import { guardedPreprocessingCommand } from "./workspaces/preprocessing-owner.js";
|
||||
|
||||
export interface WorkspaceMaintenanceIo {
|
||||
stdin: string;
|
||||
@@ -238,7 +239,7 @@ export function createProductionWorkspacePreprocessingService(
|
||||
active.releaseSecrets();
|
||||
}
|
||||
},
|
||||
runChild: async ({ argv, configPath }) => {
|
||||
runChild: async ({ argv, configPath, guard }) => {
|
||||
const configFd = openSync(configPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
|
||||
try {
|
||||
return await new Promise((resolve) => {
|
||||
@@ -254,7 +255,8 @@ export function createProductionWorkspacePreprocessingService(
|
||||
"THT_CATALOG_MIGRATOR_USER",
|
||||
"THT_CATALOG_MIGRATOR_PASSWORD_FILE",
|
||||
]) delete childEnvironment[name];
|
||||
const child = spawn(config.thtBin, argv, {
|
||||
const command = guard ? guardedPreprocessingCommand(guard, config.thtBin, argv) : { executable: config.thtBin, args: argv };
|
||||
const child = spawn(command.executable, command.args, {
|
||||
cwd: config.harnessDir,
|
||||
env: { ...childEnvironment, ...(config.dataRoot ? { THT_DATA_ROOT: config.dataRoot } : {}) },
|
||||
stdio: ["ignore", "pipe", "pipe", configFd],
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { PreprocessingStateError, PreprocessingStateStore } from "./preprocessing-state.js";
|
||||
|
||||
export interface PreprocessingChildGuard {
|
||||
lockPath: string;
|
||||
tokenPath: string;
|
||||
token: string;
|
||||
}
|
||||
|
||||
// The parent lock excludes live orchestrators. Worker locks survive parent death;
|
||||
// rotating the generation under their exclusive lock fences children not yet started.
|
||||
export async function acquirePreprocessingOwner(dataRoot: string, workspaceId: string) {
|
||||
const state = new PreprocessingStateStore({ dataRoot, workspaceId });
|
||||
const owner = await state.acquireWriterLock();
|
||||
try {
|
||||
const workers = await state.acquireWriterLock("workers");
|
||||
try {
|
||||
const token = state.rotateOwnerToken();
|
||||
return { guard: { lockPath: state.workerLockPath(), tokenPath: state.ownerTokenPath(), token }, release: owner.release,
|
||||
assertOwned: () => {
|
||||
if (!owner.isHeld() || readFileSync(state.ownerTokenPath(), "utf8") !== token) throw new PreprocessingStateError("preprocessing_conflict", "Preprocessing ownership was lost");
|
||||
} };
|
||||
} finally { await workers.release(); }
|
||||
} catch (error) { await owner.release(); throw error; }
|
||||
}
|
||||
|
||||
const guardedExec = [
|
||||
"import fcntl, os, sys",
|
||||
"fd = os.open(sys.argv[1], os.O_RDWR | getattr(os, 'O_NOFOLLOW', 0))",
|
||||
"try:",
|
||||
" fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)",
|
||||
"except BlockingIOError:",
|
||||
" sys.exit(73)",
|
||||
"token_fd = os.open(sys.argv[2], os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0))",
|
||||
"with os.fdopen(token_fd) as token_file:",
|
||||
" if token_file.read(65) != sys.argv[3]: sys.exit(73)",
|
||||
"os.set_inheritable(fd, True)",
|
||||
"os.execvp(sys.argv[4], sys.argv[4:])",
|
||||
].join("\n");
|
||||
|
||||
export function guardedPreprocessingCommand(guard: PreprocessingChildGuard, executable: string, args: string[]) {
|
||||
return { executable: "python3", args: ["-c", guardedExec, guard.lockPath, guard.tokenPath, guard.token, executable, ...args] };
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
import type { DeterministicRuntimeConfigLease } from "./runtime-config-lease.js";
|
||||
import { buildCatalogMetadataSnapshot } from "../catalog/metadata-snapshot.js";
|
||||
import type { CatalogRepository } from "../catalog/types.js";
|
||||
import { acquirePreprocessingOwner, type PreprocessingChildGuard } from "./preprocessing-owner.js";
|
||||
|
||||
export interface WorkspaceOperationResult {
|
||||
schemaVersion: 1;
|
||||
@@ -47,6 +48,7 @@ export interface WorkspaceOperationResult {
|
||||
export interface ChildProcessRequest {
|
||||
argv: string[];
|
||||
configPath: string;
|
||||
guard?: PreprocessingChildGuard;
|
||||
}
|
||||
|
||||
interface ActiveRuntime {
|
||||
@@ -79,6 +81,7 @@ export interface WorkspacePreprocessingServiceDeps {
|
||||
}
|
||||
|
||||
interface RunScope {
|
||||
owner: Awaited<ReturnType<typeof acquirePreprocessingOwner>>;
|
||||
runtime: ActiveRuntime;
|
||||
state: PreprocessingStateStore;
|
||||
job: PreprocessingJobState;
|
||||
@@ -205,13 +208,39 @@ export class WorkspacePreprocessingService {
|
||||
const runtime = await this.deps.acquireActiveRuntime(options.workspaceId);
|
||||
return baseResult(runtime, "preprocess run", "failed", "catalog_not_ready");
|
||||
}
|
||||
return await this.runFromCatalog(options);
|
||||
const owner = await acquirePreprocessingOwner(this.deps.dataRoot, options.workspaceId);
|
||||
try {
|
||||
const previous = await this.deps.catalogRepository.getByWorkspace(options.workspaceId);
|
||||
// Only runs created under this guard protocol can be reclaimed automatically.
|
||||
const lastJob = this.state(options.workspaceId).readLatestJob();
|
||||
if (previous?.preprocessingStatus === "running" && previous.preprocessingInputFingerprint
|
||||
&& (lastJob?.ownerProtocol !== 1 || !previous.preprocessingRunId || lastJob.runId !== previous.preprocessingRunId)) {
|
||||
const runtime = await this.deps.acquireActiveRuntime(options.workspaceId);
|
||||
return baseResult(runtime, "preprocess run", "failed", "preprocessing_conflict",
|
||||
{ warnings: ["An older preprocessing owner cannot be recovered automatically."] });
|
||||
}
|
||||
if (previous?.preprocessingStatus === "running" && previous.preprocessingInputFingerprint && lastJob?.ownerProtocol === 1) {
|
||||
owner.assertOwned();
|
||||
await this.deps.catalogRepository.finishPreprocessing(options.workspaceId,
|
||||
previous.metadataContentRevision, previous.preprocessingInputFingerprint,
|
||||
{ status: "failed", errorCode: "preprocessing_interrupted" }, previous.preprocessingRunId);
|
||||
}
|
||||
owner.assertOwned();
|
||||
return await this.runFromCatalog(options, owner);
|
||||
} finally { await owner.release(); }
|
||||
}
|
||||
|
||||
async clear(options: { workspaceId: string }): Promise<WorkspaceOperationResult> {
|
||||
const owner = await acquirePreprocessingOwner(this.deps.dataRoot, options.workspaceId);
|
||||
try { return await this.clearOwned(options, owner); }
|
||||
finally { await owner.release(); }
|
||||
}
|
||||
|
||||
private async clearOwned(options: { workspaceId: string }, owner: RunScope["owner"]): Promise<WorkspaceOperationResult> {
|
||||
const runtime = await this.deps.acquireActiveRuntime(options.workspaceId);
|
||||
const repository = this.deps.catalogRepository;
|
||||
if (!repository) return baseResult(runtime, "preprocess clear", "failed", "catalog_not_ready");
|
||||
owner.assertOwned();
|
||||
const cleared = await repository.clearPreprocessing(runtime.workspaceId);
|
||||
if (cleared.kind !== "cleared") {
|
||||
return baseResult(
|
||||
@@ -224,7 +253,9 @@ export class WorkspacePreprocessingService {
|
||||
const result = await this.deps.runChild({
|
||||
argv: ["preprocess", "clear", "--json", "-c", "/dev/fd/3"],
|
||||
configPath: runtime.configLease.path,
|
||||
guard: owner.guard,
|
||||
});
|
||||
owner.assertOwned();
|
||||
if (result.exitCode !== 0) {
|
||||
return baseResult(runtime, "preprocess clear", "failed", "preprocessing_clear_failed");
|
||||
}
|
||||
@@ -234,11 +265,13 @@ export class WorkspacePreprocessingService {
|
||||
});
|
||||
}
|
||||
|
||||
private async runFromCatalog(options: { workspaceId: string }): Promise<WorkspaceOperationResult> {
|
||||
const scope = await this.startRun(options.workspaceId);
|
||||
private async runFromCatalog(options: { workspaceId: string }, owner: RunScope["owner"]): Promise<WorkspaceOperationResult> {
|
||||
const scope = await this.startRun(options.workspaceId, owner);
|
||||
const repository = this.deps.catalogRepository!;
|
||||
const fingerprint = scope.runtime.configLease.inputFingerprint;
|
||||
const started = await repository.beginPreprocessing(scope.runtime.workspaceId, fingerprint);
|
||||
owner.assertOwned();
|
||||
const started = await repository.beginPreprocessing(scope.runtime.workspaceId, fingerprint, scope.job.runId);
|
||||
owner.assertOwned();
|
||||
if (started.kind !== "started") {
|
||||
scope.job.status = "failed";
|
||||
scope.state.writeJob(scope.job);
|
||||
@@ -260,19 +293,23 @@ export class WorkspacePreprocessingService {
|
||||
scope.runtime.workspaceId,
|
||||
revision,
|
||||
);
|
||||
owner.assertOwned();
|
||||
const snapshotPath = this.publishCatalogSnapshot(
|
||||
scope.runtime.workspaceId,
|
||||
JSON.stringify(snapshot),
|
||||
);
|
||||
this.completeStages(scope, "catalog_snapshot");
|
||||
const semantic = await this.deps.semanticPreflight(scope.runtime.workspace);
|
||||
owner.assertOwned();
|
||||
if (!semantic.ok) {
|
||||
await repository.finishPreprocessing(
|
||||
scope.runtime.workspaceId,
|
||||
revision,
|
||||
fingerprint,
|
||||
{ status: "failed", errorCode: semantic.code },
|
||||
scope.job.runId,
|
||||
);
|
||||
owner.assertOwned();
|
||||
scope.job.status = "failed";
|
||||
scope.state.writeJob(scope.job);
|
||||
finished = true;
|
||||
@@ -280,7 +317,7 @@ export class WorkspacePreprocessingService {
|
||||
}
|
||||
|
||||
failureCode = "schema_index_failed";
|
||||
const payload = await this.runJsonStage(scope.runtime, [
|
||||
const payload = await this.runJsonStage(scope, [
|
||||
"preprocess",
|
||||
"catalog",
|
||||
"--catalog-metadata",
|
||||
@@ -301,12 +338,15 @@ export class WorkspacePreprocessingService {
|
||||
this.evidenceDependencies(scope),
|
||||
);
|
||||
if (!["succeeded", "unchanged"].includes(outcome.status)) {
|
||||
owner.assertOwned();
|
||||
await repository.finishPreprocessing(
|
||||
scope.runtime.workspaceId,
|
||||
revision,
|
||||
fingerprint,
|
||||
{ status: "failed", errorCode: outcome.code },
|
||||
scope.job.runId,
|
||||
);
|
||||
owner.assertOwned();
|
||||
scope.job.status = "failed";
|
||||
scope.state.writeJob(scope.job);
|
||||
finished = true;
|
||||
@@ -319,29 +359,35 @@ export class WorkspacePreprocessingService {
|
||||
revision,
|
||||
fingerprint,
|
||||
{ status: "succeeded" },
|
||||
scope.job.runId,
|
||||
);
|
||||
owner.assertOwned();
|
||||
if (!completed) throw new Error("catalog preprocessing completion lost its lease");
|
||||
scope.job.status = "succeeded";
|
||||
scope.state.writeJob(scope.job);
|
||||
finished = true;
|
||||
return this.evidenceResult(scope, outcome);
|
||||
} catch (error) {
|
||||
owner.assertOwned();
|
||||
if (!finished) {
|
||||
await repository.finishPreprocessing(
|
||||
scope.runtime.workspaceId,
|
||||
revision,
|
||||
fingerprint,
|
||||
{ status: "failed", errorCode: failureCode },
|
||||
scope.job.runId,
|
||||
);
|
||||
}
|
||||
owner.assertOwned();
|
||||
scope.job.status = "failed";
|
||||
scope.state.writeJob(scope.job);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async startRun(workspaceId: string): Promise<RunScope> {
|
||||
private async startRun(workspaceId: string, owner: RunScope["owner"]): Promise<RunScope> {
|
||||
const runtime = await this.deps.acquireActiveRuntime(workspaceId);
|
||||
owner.assertOwned();
|
||||
const state = this.state(runtime.workspaceId);
|
||||
const job = await state.beginJob({
|
||||
operation: "preprocess run",
|
||||
@@ -353,7 +399,10 @@ export class WorkspacePreprocessingService {
|
||||
embeddingId: runtime.configLease.effectiveConfig.embedding.id,
|
||||
embeddingDimensions: runtime.configLease.effectiveConfig.embedding.dimensions,
|
||||
});
|
||||
return { runtime, state, job };
|
||||
owner.assertOwned();
|
||||
job.ownerProtocol = 1;
|
||||
state.writeJob(job);
|
||||
return { runtime, state, job, owner };
|
||||
}
|
||||
|
||||
private state(workspaceId: string): PreprocessingStateStore {
|
||||
@@ -361,6 +410,7 @@ export class WorkspacePreprocessingService {
|
||||
}
|
||||
|
||||
private completeStages(scope: RunScope, ...stages: string[]): void {
|
||||
scope.owner.assertOwned();
|
||||
for (const stage of stages) {
|
||||
if (!scope.job.completedStages.includes(stage)) scope.job.completedStages.push(stage);
|
||||
}
|
||||
@@ -384,8 +434,8 @@ export class WorkspacePreprocessingService {
|
||||
|
||||
private evidenceDependencies(scope: RunScope): EvidencePreprocessingDependencies {
|
||||
return {
|
||||
runStage: async (argv) => await this.runJsonStage(scope.runtime, argv),
|
||||
persistJob: () => this.state(scope.runtime.workspaceId).writeJob(scope.job),
|
||||
runStage: async (argv) => await this.runJsonStage(scope, argv),
|
||||
persistJob: () => { scope.owner.assertOwned(); this.state(scope.runtime.workspaceId).writeJob(scope.job); },
|
||||
evidencePreflight: async () => await this.deps.evidencePreflight(scope.runtime.workspace),
|
||||
requireRunId: (value) => this.requireRunId(value),
|
||||
numberRecord: (value) => this.numberRecord(value),
|
||||
@@ -400,8 +450,10 @@ export class WorkspacePreprocessingService {
|
||||
return baseResult(scope.runtime, "preprocess run", status, code, extra);
|
||||
}
|
||||
|
||||
private async runJsonStage(runtime: ActiveRuntime, argv: string[]): Promise<Record<string, unknown>> {
|
||||
const result = await this.deps.runChild({ argv, configPath: runtime.configLease.path });
|
||||
private async runJsonStage(scope: RunScope, argv: string[]): Promise<Record<string, unknown>> {
|
||||
scope.owner.assertOwned();
|
||||
const result = await this.deps.runChild({ argv, configPath: scope.runtime.configLease.path, guard: scope.owner.guard });
|
||||
scope.owner.assertOwned();
|
||||
if (result.exitCode !== 0) throw new Error("workspace child failed");
|
||||
return JSON.parse(result.stdout) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@ export interface SessionInventoryRow {
|
||||
|
||||
export interface WriterLockLease {
|
||||
holderPid: number;
|
||||
isHeld(): boolean;
|
||||
release(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -66,6 +67,7 @@ export interface PreprocessingJobState {
|
||||
status: "active" | "succeeded" | "blocked" | "failed";
|
||||
candidateDigest?: string;
|
||||
reviewDigest?: string;
|
||||
ownerProtocol?: 1;
|
||||
}
|
||||
|
||||
export interface FkReviewRecord {
|
||||
@@ -195,6 +197,14 @@ export class PreprocessingStateStore {
|
||||
}
|
||||
|
||||
writerLockPath(): string { return join(this.root, "writer.lock"); }
|
||||
workerLockPath(): string { return join(this.root, "workers.lock"); }
|
||||
ownerTokenPath(): string { return join(this.root, "owner-token"); }
|
||||
rotateOwnerToken(): string {
|
||||
this.ensureLayout();
|
||||
const token = randomBytes(32).toString("hex");
|
||||
writeAtomicFile(this.ownerTokenPath(), token, 0o600);
|
||||
return token;
|
||||
}
|
||||
runtimeConfigDirectory(): string { return join(this.root, "runtime-config"); }
|
||||
runtimeConfigManifestDirectory(): string { return join(this.root, "runtime-config-manifests"); }
|
||||
jobsDirectory(): string { return join(this.root, "jobs"); }
|
||||
@@ -216,9 +226,9 @@ export class PreprocessingStateStore {
|
||||
]) ensureDirectory(directory);
|
||||
}
|
||||
|
||||
async acquireWriterLock(): Promise<WriterLockLease> {
|
||||
async acquireWriterLock(kind: "writer" | "workers" = "writer"): Promise<WriterLockLease> {
|
||||
this.ensureLayout();
|
||||
const lockPath = this.writerLockPath();
|
||||
const lockPath = kind === "writer" ? this.writerLockPath() : this.workerLockPath();
|
||||
try {
|
||||
const entry = lstatSync(lockPath);
|
||||
if (!entry.isFile() || entry.isSymbolicLink()) throw new Error("invalid writer lock path");
|
||||
@@ -257,11 +267,14 @@ export class PreprocessingStateStore {
|
||||
let released = false;
|
||||
return {
|
||||
holderPid: holder.pid ?? 0,
|
||||
isHeld: () => !released && holder.exitCode === null && holder.signalCode === null,
|
||||
release: async () => {
|
||||
if (released) return;
|
||||
released = true;
|
||||
if (holder.exitCode !== null || holder.signalCode !== null) return;
|
||||
const exited = new Promise<void>((resolve) => holder.once("exit", () => resolve()));
|
||||
if (!holder.stdin.destroyed) holder.stdin.end();
|
||||
await new Promise<void>((resolve) => holder.once("exit", () => resolve()));
|
||||
await exited;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { MemoryCatalogRepository } from "../src/catalog/memory-repository.js";
|
||||
|
||||
test("the in-memory Catalog enforces the same attempt identity as PostgreSQL", async () => {
|
||||
const repository = new MemoryCatalogRepository();
|
||||
const database = await repository.create({ workspaceId: "retry", engine: "postgres",
|
||||
databaseName: "warehouse", schema: "public",
|
||||
binding: { transport: "postgres_direct", host: "db", port: 5432, username: "reader" } });
|
||||
await repository.applySchemaSync(database.id, database.version, "all", [], {
|
||||
schemaVersion: 1, capabilities: { tables: "available", columns: "available", relationships: "available" },
|
||||
tables: [], columns: [], relationships: [],
|
||||
});
|
||||
const revision = (await repository.get(database.id))!.metadataContentRevision;
|
||||
const fingerprint = "sha256:" + "1".repeat(64);
|
||||
await repository.beginPreprocessing("retry", fingerprint, "old");
|
||||
await repository.finishPreprocessing("retry", revision, fingerprint,
|
||||
{ status: "failed", errorCode: "preprocessing_interrupted" }, "old");
|
||||
await repository.beginPreprocessing("retry", fingerprint, "replacement");
|
||||
expect(await repository.finishPreprocessing("retry", revision, fingerprint, { status: "succeeded" }, "old")).toBeUndefined();
|
||||
expect(await repository.finishPreprocessing("retry", revision, fingerprint, { status: "succeeded" }, "replacement"))
|
||||
.toMatchObject({ preprocessingStatus: "succeeded" });
|
||||
});
|
||||
@@ -23,6 +23,7 @@ import { up as upLocalSensitivityAnalysis } from "../src/catalog/migrations/011_
|
||||
import { up as upSensitivityReason } from "../src/catalog/migrations/012_sensitivity_reason.js";
|
||||
import { up as upCatalogPreprocessingState } from "../src/catalog/migrations/013_catalog_preprocessing_state.js";
|
||||
import { up as upInstallationBindingImports } from "../src/catalog/migrations/014_installation_binding_imports.js";
|
||||
import { up as upPreprocessingRunIdentity } from "../src/catalog/migrations/015_preprocessing_run_identity.js";
|
||||
import { InstallationBindings } from "../src/catalog/installation-bindings.js";
|
||||
import { CatalogService } from "../src/catalog/service.js";
|
||||
import { CatalogOperationCoordinator } from "../src/catalog/operation-coordinator.js";
|
||||
@@ -70,6 +71,7 @@ test.skipIf(!dockerAvailable)("PostgreSQL migration enforces one database per wo
|
||||
await upSensitivityReason(db);
|
||||
await upCatalogPreprocessingState(db);
|
||||
await upInstallationBindingImports(db);
|
||||
await upPreprocessingRunIdentity(db);
|
||||
await expect(db.selectFrom("sensitiveDataSuggestionRuns")
|
||||
.select(["engine", "modelId", "policyVersion", "unknown"])
|
||||
.where("id", "=", historicalSuggestionRunId)
|
||||
@@ -312,6 +314,16 @@ test.skipIf(!dockerAvailable)("PostgreSQL migration enforces one database per wo
|
||||
preprocessingStatus: "succeeded",
|
||||
preprocessedMetadataRevision: beforePreprocessing.metadataContentRevision,
|
||||
});
|
||||
const fingerprint = "sha256:" + "1".repeat(64);
|
||||
await repository.beginPreprocessing("preprocessing-lock", fingerprint, "old-run");
|
||||
await repository.finishPreprocessing("preprocessing-lock", beforePreprocessing.metadataContentRevision,
|
||||
fingerprint, { status: "failed", errorCode: "preprocessing_interrupted" }, "old-run");
|
||||
await repository.beginPreprocessing("preprocessing-lock", fingerprint, "replacement-run");
|
||||
// Identical inputs must not let a late completion finish the replacement run.
|
||||
await expect(repository.finishPreprocessing("preprocessing-lock", beforePreprocessing.metadataContentRevision,
|
||||
fingerprint, { status: "failed", errorCode: "late-owner" }, "old-run")).resolves.toBeUndefined();
|
||||
await expect(repository.finishPreprocessing("preprocessing-lock", beforePreprocessing.metadataContentRevision,
|
||||
fingerprint, { status: "succeeded" }, "replacement-run")).resolves.toMatchObject({ preprocessingStatus: "succeeded" });
|
||||
await db.insertInto("catalogTables").values({
|
||||
id: randomUUID(),
|
||||
databaseId: lockedDatabase.id,
|
||||
|
||||
@@ -1,10 +1,34 @@
|
||||
import { expect, test } from "vitest";
|
||||
// The shipped operator client is plain ESM, shared by the embedded command and these API-boundary tests.
|
||||
// @ts-expect-error JavaScript operator module has no separate declaration file.
|
||||
import { prepareWorkspace } from "../../tools/tht/internal/installapply/import-bindings.mjs";
|
||||
import { prepareWorkspace, importBinding } from "../../tools/tht/internal/installapply/import-bindings.mjs";
|
||||
|
||||
const revision = "a".repeat(40);
|
||||
|
||||
test("a stranded preprocessing state requests guarded recovery, then verifies fresh readiness", async () => {
|
||||
let state = "running";
|
||||
const request = async (path: string, body?: unknown): Promise<Response> => {
|
||||
if (path === "/catalog/databases") return Response.json([{ id: "database-id", workspaceId: "chinook", version: 2, schemaSyncedVersion: 2,
|
||||
binding: { transport: "postgres_direct" }, workspaceRevision: { commit: revision } }]);
|
||||
if (path.endsWith("/sync-runs")) return Response.json([]);
|
||||
if (path.endsWith("/preprocessing")) {
|
||||
if (body) { expect(body).toEqual({ recoverInterrupted: true }); state = "ready"; }
|
||||
return Response.json({ state });
|
||||
}
|
||||
throw Error("unexpected operation");
|
||||
};
|
||||
expect(await prepareWorkspace(request, "chinook", revision, async () => {})).toEqual({ workspaceId: "chinook", state: "ready" });
|
||||
});
|
||||
|
||||
test("retry reaches a pending human schema review even when its reservation blocks binding import", async () => {
|
||||
const request = async (path: string) => {
|
||||
if (path === "/installation/bindings") return Response.json({ code: "installation_operation_pending" }, { status: 409 });
|
||||
if (path === "/catalog/databases") return Response.json([{ workspaceId: "chinook", activeSyncRun: { id: "run-id", state: "awaiting_confirmation" } }]);
|
||||
throw Error("unexpected operation");
|
||||
};
|
||||
await expect(importBinding(request, { configuration: { workspaceId: "chinook" } }, revision, async () => {})).rejects.toMatchObject({ code: "schema_review_required", runId: "run-id" });
|
||||
});
|
||||
|
||||
test.each(["blocked", "failed"])("configured Evidence/index failure (%s) remains a real stop", async state => {
|
||||
const request = async (path: string, body?: unknown): Promise<Response> => {
|
||||
if (path === "/catalog/databases") return Response.json([{ id: "database-id", workspaceId: "chinook", version: 2, schemaSyncedVersion: 2,
|
||||
|
||||
@@ -54,6 +54,17 @@ const modelCatalog: RuntimeModelCatalog = {
|
||||
hasSession: (id) => id === "zai/glm-5.2",
|
||||
};
|
||||
|
||||
test("a fresh installation can smoke-test its catalog default without saved user settings", async () => {
|
||||
const smokeProvider = vi.fn(async () => undefined);
|
||||
const service = createPiManagement(configFor(), {
|
||||
modelCatalog, execute: successfulExec([]), readSettings: () => ({}), smokeProvider,
|
||||
});
|
||||
expect(await service.test()).toMatchObject({ ready: true });
|
||||
expect(smokeProvider).toHaveBeenCalledWith(expect.objectContaining({
|
||||
provider: "zai", model: "glm-5.2", reasoning: "low",
|
||||
}));
|
||||
});
|
||||
|
||||
function successfulExec(calls: Array<{ command: string; args: string[]; timeout: number }>): PiExecFile {
|
||||
return async (command, args, options) => {
|
||||
calls.push({ command, args, timeout: options.timeout });
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { expect, test } from "vitest";
|
||||
import { acquirePreprocessingOwner, guardedPreprocessingCommand } from "../src/workspaces/preprocessing-owner.js";
|
||||
|
||||
test("orphan worker prevents recovery; delayed old worker is fenced after recovery", async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "preprocess-owner-"));
|
||||
let worker;
|
||||
try {
|
||||
const owner = await acquirePreprocessingOwner(root, "chinook");
|
||||
const command = guardedPreprocessingCommand(owner.guard, "python3", ["-c", "import time; print('ready',flush=True); time.sleep(30)"]);
|
||||
worker = spawn(command.executable, command.args, { stdio: ["ignore", "pipe", "pipe"] });
|
||||
await new Promise<void>((resolve, reject) => { worker!.stdout!.once("data", () => resolve()); worker!.once("error", reject); worker!.once("exit", () => reject(Error("worker stopped early"))); });
|
||||
await owner.release();
|
||||
await expect(acquirePreprocessingOwner(root, "chinook")).rejects.toMatchObject({ code: "preprocessing_conflict" });
|
||||
const exited = new Promise(resolve => worker!.once("exit", resolve)); worker.kill("SIGKILL"); await exited;
|
||||
const replacement = await acquirePreprocessingOwner(root, "chinook");
|
||||
try {
|
||||
const stale = guardedPreprocessingCommand(owner.guard, "python3", ["-c", "raise Exception('must never run')"]);
|
||||
expect(spawnSync(stale.executable, stale.args).status).toBe(73);
|
||||
} finally { await replacement.release(); }
|
||||
} finally { worker?.kill("SIGKILL"); rmSync(root, { recursive: true, force: true }); }
|
||||
});
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
type WorkspacePreprocessingRouteDeps,
|
||||
} from "../src/routes/workspace-preprocessing.js";
|
||||
import type { WorkspaceRegistry } from "../src/workspaces/registry.js";
|
||||
import { PreprocessingStateError } from "../src/workspaces/preprocessing-state.js";
|
||||
|
||||
const admin: PrincipalContext = {
|
||||
issuer: "test",
|
||||
@@ -17,6 +18,22 @@ const admin: PrincipalContext = {
|
||||
isAdmin: true,
|
||||
};
|
||||
|
||||
test("explicit interrupted-run recovery is guarded and never steals an active owner", async () => {
|
||||
const run = vi.fn(async () => { throw new PreprocessingStateError("preprocessing_conflict", "private owner details"); });
|
||||
const deps = routeDeps(() => database({ preprocessingStatus: "running" }), { service: { run, clear: vi.fn() } });
|
||||
const app = Fastify();
|
||||
app.addHook("preHandler", async request => { request.principal = admin; });
|
||||
workspacePreprocessingRoutes(app, deps);
|
||||
try {
|
||||
const response = await app.inject({ method: "POST", url: "/workspaces/catalog-workspace/preprocessing", payload: { recoverInterrupted: true } });
|
||||
expect(response.statusCode).toBe(409);
|
||||
expect(response.json()).toMatchObject({ code: "preprocessing_conflict", state: "running" });
|
||||
expect(response.body).not.toContain("private owner");
|
||||
expect(run).toHaveBeenCalledOnce();
|
||||
expect(deps.service.clear).not.toHaveBeenCalled();
|
||||
} finally { await app.close(); }
|
||||
});
|
||||
|
||||
function database(overrides: Partial<WorkspaceDatabase> = {}): WorkspaceDatabase {
|
||||
return {
|
||||
id: "49b6491a-78bb-4cee-b27b-0efaf4419774",
|
||||
|
||||
@@ -3,6 +3,7 @@ import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
import { validateWorkspaceDescriptor } from "../src/workspaces/schema.js";
|
||||
import { PreprocessingStateStore, type WriterLockLease } from "../src/workspaces/preprocessing-state.js";
|
||||
import {
|
||||
WorkspacePreprocessingService,
|
||||
type ChildProcessRequest,
|
||||
@@ -10,6 +11,64 @@ import {
|
||||
|
||||
const roots: string[] = [];
|
||||
|
||||
test("a legacy running lease is never silently adopted by repeated recovery attempts", async () => {
|
||||
const catalog = repository({ getByWorkspace: vi.fn(async () => ({ ...database, preprocessingInputFingerprint: "sha256:legacy" })) });
|
||||
const instance = service({ repository: catalog });
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
expect(await instance.run({ workspaceId: "catalog-workspace" })).toMatchObject({ status: "failed", code: "preprocessing_conflict" });
|
||||
}
|
||||
expect(catalog.beginPreprocessing).not.toHaveBeenCalled();
|
||||
expect(catalog.finishPreprocessing).not.toHaveBeenCalled();
|
||||
expect(catalog.clearPreprocessing).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("retry after loss of Catalog completion restarts guarded preprocessing without clearing data", async () => {
|
||||
let stranded = false;
|
||||
let runId: string | undefined;
|
||||
const catalog = repository({ getByWorkspace: vi.fn(async () => ({ ...database,
|
||||
...(stranded ? { preprocessingInputFingerprint: "sha256:" + "f".repeat(64), preprocessingRunId: runId } : {}) })),
|
||||
beginPreprocessing: vi.fn(async (_workspace, _fingerprint, id) => {
|
||||
runId = id; return { kind: "started", database };
|
||||
}),
|
||||
});
|
||||
catalog.finishPreprocessing.mockRejectedValueOnce(Error("Catalog connection lost"))
|
||||
.mockRejectedValueOnce(Error("Catalog still unavailable"));
|
||||
const instance = service({ repository: catalog, runChild: async () => {
|
||||
stranded = true;
|
||||
return { exitCode: 0, stdout: JSON.stringify({ counts: { tables: 1 } }), stderr: "" };
|
||||
} });
|
||||
await expect(instance.run({ workspaceId: "catalog-workspace" })).rejects.toThrow();
|
||||
const second = await instance.run({ workspaceId: "catalog-workspace" });
|
||||
expect(second.status).toBe("succeeded");
|
||||
expect(catalog.finishPreprocessing).toHaveBeenCalledWith("catalog-workspace", 9, "sha256:" + "f".repeat(64),
|
||||
{ status: "failed", errorCode: "preprocessing_interrupted" }, expect.any(String));
|
||||
expect(catalog.clearPreprocessing).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("loss of the real owner during semantic preflight cannot complete or rewrite the job", async () => {
|
||||
let lease: WriterLockLease | undefined;
|
||||
const original = PreprocessingStateStore.prototype.acquireWriterLock;
|
||||
const spy = vi.spyOn(PreprocessingStateStore.prototype, "acquireWriterLock")
|
||||
.mockImplementation(async function (kind) {
|
||||
const acquired = await original.call(this, kind);
|
||||
if (kind !== "workers") lease = acquired;
|
||||
return acquired;
|
||||
});
|
||||
const catalog = repository();
|
||||
const instance = service({ repository: catalog, semanticPreflight: async () => {
|
||||
process.kill(lease!.holderPid, "SIGKILL");
|
||||
for (let i = 0; i < 100 && lease!.isHeld(); i++) await new Promise(resolve => setTimeout(resolve, 10));
|
||||
expect(lease!.isHeld()).toBe(false);
|
||||
return { ok: false, code: "semantic_index_incompatible" };
|
||||
} });
|
||||
try {
|
||||
await expect(instance.run({ workspaceId: "catalog-workspace" })).rejects.toMatchObject({ code: "preprocessing_conflict" });
|
||||
expect(catalog.finishPreprocessing).not.toHaveBeenCalled();
|
||||
const latest = new PreprocessingStateStore({ dataRoot: roots.at(-1)!, workspaceId: "catalog-workspace" }).readLatestJob();
|
||||
expect(latest?.status).toBe("active");
|
||||
} finally { spy.mockRestore(); }
|
||||
});
|
||||
|
||||
test("Evidence consolidation runs only its stage and preserves blocked Catalog readiness", async () => {
|
||||
const catalog = repository();
|
||||
const runChild = vi.fn(async () => ({ exitCode: 0, stdout: JSON.stringify({ status: "succeeded", counts: { documents: 2 } }), stderr: "" }));
|
||||
@@ -219,6 +278,7 @@ test("complete preprocessing snapshots Catalog metadata and commits its PostgreS
|
||||
9,
|
||||
"sha256:" + "f".repeat(64),
|
||||
{ status: "succeeded" },
|
||||
expect.any(String),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -257,6 +317,7 @@ test("preprocessing records a failed PostgreSQL state when its hidden worker fai
|
||||
9,
|
||||
"sha256:" + "f".repeat(64),
|
||||
{ status: "failed", errorCode: "schema_index_failed" },
|
||||
expect.any(String),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -273,6 +334,7 @@ test("semantic preflight failure is persisted before returning", async () => {
|
||||
9,
|
||||
"sha256:" + "f".repeat(64),
|
||||
{ status: "failed", errorCode: "semantic_index_incompatible" },
|
||||
expect.any(String),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -310,6 +372,7 @@ test("clear invalidates Catalog readiness before clearing only derived worker da
|
||||
expect(runChild).toHaveBeenCalledWith({
|
||||
argv: ["preprocess", "clear", "--json", "-c", "/dev/fd/3"],
|
||||
configPath: expect.any(String),
|
||||
guard: { lockPath: expect.any(String), tokenPath: expect.any(String), token: expect.stringMatching(/^[a-f0-9]{64}$/) },
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
status: "succeeded",
|
||||
|
||||
Reference in New Issue
Block a user