feat: recover interrupted installation preparation safely
This commit is contained in:
+3
-1
@@ -44,7 +44,9 @@ and invariants are in [AGENTS.md](AGENTS.md); prior snapshots remain in Git.
|
||||
Ticket #50 adds an explicit `prepare-source-installation.mjs` producer from an
|
||||
isolated committed worktree. Source bundles pin local application image IDs and
|
||||
upstream Docker Hub digests; the same native plan/apply path verifies provenance,
|
||||
shares journal/locks and never falls back to a build. Extended recovery, real-host
|
||||
shares journal/locks and never falls back to a build. Ticket #51 adds guarded
|
||||
interrupted preprocessing recovery, fencing of delayed/orphan workers and preserved
|
||||
pending schema review even during binding retry. Real-host
|
||||
acceptance and curated examples remain pending. Earlier previews are superseded
|
||||
for platform apply; no complete installer/OS acceptance is claimed.
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -153,6 +153,30 @@ Core admission requires all of the following:
|
||||
Failure leaves the workspace unavailable to the core. There is no rollback: fix the cause and run
|
||||
the complete command again.
|
||||
|
||||
## Interrupted owner recovery
|
||||
|
||||
Current preprocessing runs also hold a kernel writer lock on the shared workspace
|
||||
volume. Every mutating worker inherits a separate shared kernel lock and validates
|
||||
an owner generation before starting. Recovery takes both locks exclusively before
|
||||
rotating that generation: a surviving orphan worker blocks recovery, while a delayed
|
||||
worker from the old generation cannot start. These guards establish process ownership;
|
||||
PostgreSQL remains the readiness authority.
|
||||
|
||||
A repeated `preprocess run` can mark an orphaned current-protocol Catalog lease as
|
||||
`preprocessing_interrupted` through the version/fingerprint/run-identity-checked completion
|
||||
operation, then restart the entire pipeline. It does not resume internal stages or
|
||||
clear Memory, sessions, curated descriptions or canonical Evidence. Older running jobs
|
||||
without this ownership protocol are not automatically adopted; inspect their original
|
||||
owner during upgrade instead of deleting data or resetting leases speculatively.
|
||||
Each attempt records its unique run identity in PostgreSQL (migration 015). A late
|
||||
completion from the previous attempt cannot finish its replacement, even when the
|
||||
metadata revision and input fingerprint are unchanged.
|
||||
|
||||
The installer requests this guarded recovery when status remains running. An active
|
||||
owner returns a conflict and the installer waits. A pending destructive Catalog Sync
|
||||
Run is preserved for human review, including when its reservation temporarily blocks
|
||||
binding import. Interrupted synchronization is retried through the existing domain API.
|
||||
|
||||
## Administration sidebar
|
||||
|
||||
The Administration sidebar exposes the same one-shot operation for the workspace selected in the
|
||||
|
||||
@@ -266,6 +266,20 @@ the lock; after a forcibly killed process, confirm that its owner is no longer r
|
||||
before explicitly removing a stale lock. A different release requires the upgrade
|
||||
path rather than this command.
|
||||
|
||||
If apply is interrupted during synchronization or preprocessing, repeat the same command.
|
||||
Persisted Catalog runs are read again and pending human decisions remain pending. Active
|
||||
preprocessing is awaited. If its owner has exited, recovery also checks that no orphan
|
||||
worker is still running before restarting the complete pipeline. It never clears sessions,
|
||||
curated Evidence, descriptions or Memory. Do not use `workspace preprocess clear` or volume
|
||||
deletion as a recovery remedy. Older jobs without the ownership protocol require inspection
|
||||
during an upgrade.
|
||||
|
||||
A changed credential or endpoint invalidates the old plan. Correct the documents, repeat
|
||||
`validate`, then `plan` with a new filename. If a binding was already imported, apply the
|
||||
intended correction in Administration too: bootstrap inputs must agree with the Catalog
|
||||
and never overwrite administrative changes. Other stages reconcile actual Docker/Catalog
|
||||
state without recreating existing data.
|
||||
|
||||
## Advanced source build with the same prepared documents
|
||||
|
||||
Source compilation is an explicit choice before planning. It requires a ThothII
|
||||
|
||||
@@ -275,6 +275,20 @@ nuovo piano. Ctrl+C rilascia il lock; dopo un arresto forzato del processo verif
|
||||
che non sia più attivo prima di rimuovere esplicitamente il suo lock residuo.
|
||||
Un rilascio differente richiede il percorso di aggiornamento, non questo comando.
|
||||
|
||||
Se `apply` viene interrotto durante sync o preprocessing, ripetere lo stesso comando.
|
||||
I run Catalog persistiti vengono riletti; una decisione umana pendente resta pendente.
|
||||
Il preprocessing in corso viene atteso. Se il suo proprietario è terminato, la ripresa
|
||||
verifica anche l'assenza di processi figli ancora attivi e riesegue la pipeline completa
|
||||
con il contratto esistente. Non cancella sessioni, Evidence curate, descrizioni o Memory.
|
||||
Non usare `workspace preprocess clear` o la cancellazione dei volumi come rimedio.
|
||||
I vecchi job senza il protocollo di ownership richiedono un'ispezione durante upgrade.
|
||||
|
||||
Una credenziale o un endpoint modificato rende il piano vecchio inutilizzabile.
|
||||
Correggere i documenti e ripetere `validate` e `plan` con un nome di piano nuovo.
|
||||
Se il binding era già importato, applicare la correzione voluta anche in Amministrazione:
|
||||
il bootstrap deve corrispondere al Catalog, non sovrascrive modifiche amministrative.
|
||||
Le altre fasi vengono riconciliate con Docker e Catalog senza ricreare dati già presenti.
|
||||
|
||||
## Percorso avanzato da sorgenti con gli stessi documenti
|
||||
|
||||
La build è una scelta esplicita precedente alla predisposizione del piano.
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
# Installation recovery — T09/#51
|
||||
|
||||
The installer retains pending schema review even when a durable synchronization's
|
||||
reservation blocks binding import. It waits for busy operations, retries interrupted
|
||||
sync through the domain API and explicitly requests guarded preprocessing recovery.
|
||||
|
||||
Preprocessing now uses the existing kernel writer-lock mechanism plus inherited
|
||||
worker locks and an owner-generation check. A surviving orphan worker prevents
|
||||
recovery; a delayed worker from an older generation cannot start. Once absence of
|
||||
writers is established, the Catalog fingerprint/revision/run-identity CAS marks an orphaned
|
||||
current-protocol run interrupted and the full pipeline can run again. Legacy owners
|
||||
without this protocol are not silently adopted. Clear operations use the same guard
|
||||
but are never invoked by installation recovery.
|
||||
|
||||
No new Catalog authority or generic reset was added. Existing document seals detect
|
||||
changed credentials and inputs; corrected documents need a new plan. Imported binding
|
||||
changes must also be reconciled through Administration, preserving intentional edits.
|
||||
Source and prebuilt installations share this behavior.
|
||||
|
||||
Migration 015 stores the attempt identity so a late completion cannot finish a new
|
||||
attempt using the same inputs. Ownership is rechecked after asynchronous work before
|
||||
updating the job. Regression tests kill the real lock holder during semantic preflight
|
||||
and verify rejection of a stale completion against real PostgreSQL.
|
||||
|
||||
Real source installation exposed two additional contract defects: containerd image
|
||||
stores may identify a locally loaded image by its manifest rather than Buildx's config
|
||||
digest; unsupported Git ports must fail document validation before runtime startup.
|
||||
Both now have regression tests. A fresh installation also uses `low` reasoning for
|
||||
the Pi smoke when neither installation nor saved settings select a level.
|
||||
|
||||
Verification includes real kernel-lock/child-process tests, delayed-worker rejection,
|
||||
service retry after Catalog completion loss, legacy-owner refusal, authenticated route
|
||||
conflict handling and installation client readiness checks. Full suite results and
|
||||
published consumer acceptance are recorded after completion, not inferred from mocks.
|
||||
|
||||
Validation before publication: the full backend suite and all Go packages passed;
|
||||
backend typecheck, source-producer tests and the strict documentation build passed.
|
||||
After aligning the in-memory Catalog test double with the new run identity, the
|
||||
focused Catalog route/service/identity suite passed (39 tests), as did typecheck.
|
||||
Standards and Spec reviews found no remaining production blocker. Real consumer
|
||||
fault-recovery acceptance remains pending at this commit.
|
||||
@@ -92,7 +92,7 @@ func installationApplyCommand(ctx context.Context, installationPath string, args
|
||||
result, err := installapply.Run(ctx, installapply.Request{PlanPath: planPath, InstallationPath: installationPath}, runner, check)
|
||||
write(result)
|
||||
if err != nil {
|
||||
if result.WorkspacePreparation != nil && result.WorkspacePreparation.Code == "schema_review_required" {
|
||||
if result.NeedsReview() {
|
||||
return 3
|
||||
}
|
||||
return 1
|
||||
|
||||
@@ -440,6 +440,9 @@ func validateRepositoryRemote(remote, access string) error {
|
||||
if access == "ssh" && parsed.Scheme != "ssh" {
|
||||
return errors.New("workspaceRepository remote does not match SSH access")
|
||||
}
|
||||
if parsed.Port() != "" && !(parsed.Scheme == "https" && parsed.Port() == "443") {
|
||||
return errors.New("workspaceRepository remote uses a port unsupported by the runtime registry")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -490,3 +490,11 @@ func containsSequence(values, wanted []string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
func TestPreparedGitRemoteRejectsPortsUnsupportedByRuntimeRegistry(t *testing.T) {
|
||||
if validateRepositoryRemote("https://git.example.test:8443/workspaces.git", "https") == nil {
|
||||
t.Fatal("runtime-rejected Git port accepted during document preparation")
|
||||
}
|
||||
if err := validateRepositoryRemote("https://git.example.test:443/workspaces.git", "https"); err != nil {
|
||||
t.Fatal("standard HTTPS port must match URL normalization")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,7 +130,7 @@ func importBindings(ctx context.Context, plan preflight.Plan, runner compose.Run
|
||||
|
||||
func runPreparedClient(ctx context.Context, plan preflight.Plan, runner compose.Runner, payload []byte, prepare bool) (BindingReport, error) {
|
||||
client, success, timeout := bindingClient, "bindings_ready", 15*time.Minute
|
||||
codes := []string{"bindings_ready", "authentication_required", "workspace_reconciliation_required", "binding_reconciliation_required", "container_connection_failed", "binding_import_failed"}
|
||||
codes := []string{"bindings_ready", "authentication_required", "workspace_reconciliation_required", "binding_reconciliation_required", "container_connection_failed", "binding_import_failed", "binding_operation_pending", "schema_review_required"}
|
||||
if prepare {
|
||||
client, success, timeout = readinessClient, "workspaces_prepared", 60*time.Minute
|
||||
codes = append(codes, "workspaces_prepared", "workspace_preparation_failed", "session_transport_unsupported", "schema_review_required", "schema_sync_failed", "schema_sync_pending", "preprocessing_failed", "preprocessing_blocked", "preprocessing_pending")
|
||||
|
||||
@@ -5,6 +5,25 @@ const jsonResponse = async (response, code) => {
|
||||
return response.json();
|
||||
};
|
||||
|
||||
export async function importBinding(request, entry, revision, pause = () => new Promise(resolve => setTimeout(resolve, 2000))) {
|
||||
for (let attempt = 0; attempt < 300; attempt++) {
|
||||
const response = await request("/installation/bindings", { ...entry, revision });
|
||||
if (response.status === 409) {
|
||||
const value = await response.json();
|
||||
if (value.code !== "installation_operation_pending") throw stopped("binding_reconciliation_required");
|
||||
const databases = await jsonResponse(await request("/catalog/databases"), "binding_import_failed");
|
||||
const active = databases.find(item => item.workspaceId === entry.configuration.workspaceId)?.activeSyncRun;
|
||||
if (active?.state === "awaiting_confirmation") throw stopped("schema_review_required", active.id);
|
||||
await pause(); continue;
|
||||
}
|
||||
if (response.status === 422) throw stopped("container_connection_failed");
|
||||
const value = await jsonResponse(response, "binding_import_failed");
|
||||
if (value.connectionStatus !== "reachable" || !["applied", "unchanged"].includes(value.status)) throw stopped("binding_import_failed");
|
||||
return;
|
||||
}
|
||||
throw stopped("binding_operation_pending");
|
||||
}
|
||||
|
||||
export async function prepareWorkspace(request, workspaceId, revision, pause = () => new Promise(resolve => setTimeout(resolve, 2000))) {
|
||||
const databases = await jsonResponse(await request("/catalog/databases"), "workspace_preparation_failed");
|
||||
const database = databases.find(item => item.workspaceId === workspaceId);
|
||||
@@ -12,6 +31,11 @@ export async function prepareWorkspace(request, workspaceId, revision, pause = (
|
||||
if (database.binding.transport === "ssh_tunnel") throw stopped("session_transport_unsupported");
|
||||
const runs = await jsonResponse(await request(`/catalog/databases/${database.id}/sync-runs`), "schema_sync_failed");
|
||||
let active = runs.find(run => ["queued", "running", "awaiting_confirmation", "applying"].includes(run.state));
|
||||
const interrupted = runs.find(run => ["interrupted", "failed"].includes(run.state) && run.requestedDatabaseVersion === database.version &&
|
||||
run.scope === "all" && (database.schemaSyncedVersion !== database.version || run.phase === "memory_cleanup"));
|
||||
if (!active && interrupted) {
|
||||
active = await jsonResponse(await request(`/catalog/sync-runs/${interrupted.id}/retry`, {}), "schema_sync_failed");
|
||||
}
|
||||
const waitForSync = async run => {
|
||||
for (let attempt = 0; attempt < 900; attempt++) {
|
||||
if (run.state === "awaiting_confirmation") throw stopped("schema_review_required", run.id);
|
||||
@@ -40,6 +64,11 @@ export async function prepareWorkspace(request, workspaceId, revision, pause = (
|
||||
for (let attempt = 0; attempt < 900; attempt++) {
|
||||
if (state.state === "ready") return { workspaceId, state: "ready" };
|
||||
if (state.state === "blocked") throw stopped("preprocessing_blocked");
|
||||
if (state.state === "running" && attempt % 15 === 0) {
|
||||
const response = await request(path, { recoverInterrupted: true });
|
||||
if (response.status !== 409) await jsonResponse(response, "preprocessing_failed");
|
||||
started = true;
|
||||
} else
|
||||
if (["required", "failed"].includes(state.state) && !started) {
|
||||
started = true;
|
||||
await jsonResponse(await request(path, {}), "preprocessing_failed");
|
||||
@@ -51,7 +80,8 @@ export async function prepareWorkspace(request, workspaceId, revision, pause = (
|
||||
}
|
||||
|
||||
const readinessCodes = new Set(["workspace_preparation_failed", "workspace_reconciliation_required", "session_transport_unsupported",
|
||||
"schema_review_required", "schema_sync_failed", "schema_sync_pending", "preprocessing_failed", "preprocessing_blocked", "preprocessing_pending"]);
|
||||
"schema_review_required", "schema_sync_failed", "schema_sync_pending", "preprocessing_failed", "preprocessing_blocked", "preprocessing_pending",
|
||||
"binding_reconciliation_required", "container_connection_failed", "binding_import_failed", "binding_operation_pending"]);
|
||||
|
||||
export async function importPreparedBindings(base = "http://core:8787", mode = "bindings") {
|
||||
let cookie = "", csrf = "", origin = "", completed = 0, code = "authentication_required";
|
||||
@@ -77,6 +107,7 @@ try {
|
||||
if (!source.ok) throw Error();
|
||||
const { revision } = await source.json();
|
||||
for (const entry of prepared.databases) {
|
||||
workspaceId = entry.configuration.workspaceId;
|
||||
if (mode === "workspaces") {
|
||||
workspaceId = entry.configuration.workspaceId;
|
||||
code = "workspace_preparation_failed";
|
||||
@@ -85,12 +116,7 @@ try {
|
||||
continue;
|
||||
}
|
||||
code = "binding_import_failed";
|
||||
const response = await request("/installation/bindings", { ...entry, revision });
|
||||
if (response.status === 409) code = "binding_reconciliation_required";
|
||||
if (response.status === 422) code = "container_connection_failed";
|
||||
if (!response.ok) throw Error();
|
||||
const value = await response.json();
|
||||
if (value.connectionStatus !== "reachable" || !["applied", "unchanged"].includes(value.status)) throw Error();
|
||||
await importBinding(request, entry, revision);
|
||||
completed++;
|
||||
}
|
||||
workspaceId = undefined;
|
||||
|
||||
@@ -52,6 +52,11 @@ type journal struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
func (r Result) NeedsReview() bool {
|
||||
return (r.WorkspacePreparation != nil && r.WorkspacePreparation.Code == "schema_review_required") ||
|
||||
(r.BindingImport != nil && r.BindingImport.Code == "schema_review_required")
|
||||
}
|
||||
|
||||
// Check must repeat document validation and live prerequisite probes at the public CLI boundary.
|
||||
// It is mandatory; historical success in the plan never authorizes skipping current checks.
|
||||
type Check func(context.Context, preflight.Plan) error
|
||||
@@ -255,7 +260,7 @@ func Run(ctx context.Context, request Request, runner compose.Runner, check Chec
|
||||
// A journal entry alone is never proof that a container or migration still exists.
|
||||
for _, stage := range stages {
|
||||
if err := operation(stage.name, stage.run); err != nil {
|
||||
if result.WorkspacePreparation != nil && result.WorkspacePreparation.Code == "schema_review_required" {
|
||||
if result.NeedsReview() {
|
||||
return fail(stage.name, "Review the pending schema synchronization in application Administration, then repeat apply. No destructive change was confirmed by the installer.")
|
||||
}
|
||||
return fail(stage.name, err.Error())
|
||||
|
||||
Reference in New Issue
Block a user