feat: recover interrupted installation preparation safely
This commit is contained in:
@@ -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;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user