mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-04 02:32:07 +01:00
## Thinking Path > - Paperclip manages agent work through shared server and database services. > - High query volume can spend main-thread time on SQL construction and result decoding. > - The existing bounded response capture counts rows and bytes, but it cannot name the operation that executed a query. > - Bundled callers can be missing, and measuring every parsed JSON value adds work to the diagnostic. > - This pull request carries a semantic execution owner into each measured query and bounds response sizing. > - Operators can rank query volume by owner before choosing a performance fix. ## Linked Issues or Issue Description Refs #17504, #17522, #17537, #17564. **What existing behavior does this improve?** The opt-in `PAPERCLIP_DB_RESPONSE_CAPTURE_WINDOW` diagnostic. **Subsystem affected** Database diagnostics and existing server execution boundaries. **Current behavior** The capture groups by table, operation, and builder caller. It cannot distinguish execution owners that reuse a prepared query. Bundled deployments need source maps for caller locations. The capture visits every returned value and serializes parsed JSON again to estimate its size. **Proposed behavior** Version 2 captures use fixed semantic owners for HTTP requests, delivery queues, execution phases, and budget work. They count completed calls, returned rows, errors, and completion wall time. They sample successful results 1, 17, 33, and so on, with fixed cell and string/byte limits. Complex values remain explicitly unmeasured. Semantic ownership works without source maps. **Reason and benefit** A short census can identify which operations issue the most queries or return the most rows. It preserves each query's execution owner through pooled connections, concurrent operations, and prepared-query reuse. It reduces diagnostic work without claiming per-query CPU attribution. **Breaking changes** Opt-in capture output moves from `entry.v1`/`summary.v1` to `entry.v2`/`summary.v2`. Sampled primitive byte lower bounds replace all-result byte estimates. Consumers must use the new fields and must not extrapolate them into a total. There is no database migration or application API change. ## What Changed - Added `withDatabaseOperation(owner, action)` to the DB package. The server owns semantic labels. Queries retain execution ownership in their completion closure. - Added fixed owners at existing HTTP, delivery, budget, and execution timing boundaries. Delivery work replaces the context of the producer that woke it. - Added complete call/row/error counters and completion wall durations within the existing bounded window. Durations include waits and are not CPU measurements. - Sampled and bounded primitive-value sizing. Complex and oversized values remain unmeasured. Known owners skip repeated stack extraction. - Preserved the deadline, group limit, paced output, query outcomes, and existing coverage exclusions. Updated the operator documentation. - Added real PostgreSQL owner-isolation and prepared-query tests, server scope tests, and plain bundled-runtime proof. - Moved projection-test and benchmark full-response sizing into an explicit test helper. Existing payload-size thresholds remain unchanged; these synthetic checks do not use the production sampler. ## Verification - Final-commit DB capture suites: 43 tests passed in 13.86 seconds against the actual PostgreSQL driver, including concurrent owners, prepared reuse, transaction failure, a dedicated client, sampling, and a query crossing the deadline. DB typecheck passed. - Server attribution and existing delivery/execution/budget suites: 53 tests passed. Final concurrent HTTP GET/JSON POST scope refinement: 5 tests passed. - Runtime bundle suite: 8 existing tests passed. The new no-source-map owner test passed after its fixture was corrected to use a driver thenable. An ordinary native Promise can bypass an overridden `.then`; the real PostgreSQL tests separately cover driver integration. - Observer-only experiment: three alternating pairs per case on Node 24.22.2, macOS arm64, 3,000 calls per run after warm-up. For an already-materialized synthetic JSON result, median capture CPU fell from 82.37 to 1.87 microseconds/call. For a 100-row primitive result, it fell from 8.10 to 4.40 microseconds/call. Every result retained identity and all calls were counted. The new diagnostic intentionally measures less byte data; these are observer costs, not database latency or a hosted application speedup. Disabled-case timings were below one microsecond/call and too small for a performance conclusion. - Final lifecycle regression: 28 unit tests and DB typecheck passed. Closing the last capture disables and replaces owner storage; overlapping captures retain it. - Final-commit full recursive typecheck passed in 38.38 seconds and full build passed in 40.81 seconds. The build stamp matches `83ed4ba9cebd68d48929c46f15ab32d5c0b9687b`. Focused server attribution tests also passed 5/5 before the test-helper-only migration. Full test acceptance will use the repository's parallel CI gates; the unsharded local command takes hours. - Verification failures retained: initial sandbox runs could not open local IPC/PostgreSQL listeners; permitted reruns exercised the real services. One old test expected JSON serialization and was updated to assert explicit unmeasured complex values. The first bundle fixture used the wrong promise boundary, as described above. A retained-callback regression also demonstrated that disabling and reusing the same AsyncLocalStorage instance could resurrect an old owner; replacing the instance after the last capture closes fixes that case. - The first CI run found older projection tests consuming the previous full-response fields. Those consumers now use the full-response test helper, preserving their byte thresholds. The two complete affected route suites plus helper tests passed 115/115 in 73.08 seconds. A temporary full-row query negative control then failed the unchanged 2,048-byte limit at 5,000,812 bytes and was restored; five other service suites passed 34/34 and the affected chat cases passed 3/3. All three previously failing CI shards passed on the corrected head. A local skill-list benchmark smoke check completed 255 captured queries with no in-flight queries or overflow; this was integration verification under concurrent test load, not a timing benchmark. - Two final-head runner jobs lost communication with GitHub before reporting a test result. One targeted retry of those jobs and their dependent aggregate passed. All 53 final-head checks passed, with 3 intentional skips; previously passing suites were preserved. - Hosted capture remains pending until the reviewed revision is deployed and a bounded window is explicitly configured. Reproduce the focused checks with Node 24 and the repository pnpm version: ```sh pnpm exec vitest run packages/db/src/response-capture.test.ts packages/db/src/response-capture-postgres.test.ts pnpm --dir server exec vitest run --config vitest.config.ts src/__tests__/database-operation-attribution.test.ts scripts/bundle-runtime.test.mjs pnpm -r typecheck pnpm build ``` ## Risks - Owner context is active while a valid future capture window is armed, up to 30 minutes before accounting starts. No-window and expired calls take the direct path. Diagnostics still add bounded work while enabled. - A nearest nested owner is reported. Broad `http.request` and unattributed groups remain visible; this does not identify every service callsite or SQL shape. - The existing census excludes tagged/raw explicit-execute/streaming paths and internal protocol commands. Its counts are not PostgreSQL transaction totals. - Completion wall time includes queue/database/network/scheduling waits. Concurrent durations overlap. Sampled bytes exclude complex values, large strings, and values beyond the sizing limits. - Activation is startup-only. Operators must choose the window after artifact preparation, allow rollout/warm-up time, and remove the expired setting afterward. ## Model Used OpenAI Codex, GPT-6 family, with code execution, repository inspection, and parallel agents. The exact deployment model ID and context-window size are not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
337 lines
19 KiB
TypeScript
337 lines
19 KiB
TypeScript
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
|
|
import { EMBEDDED_POSTGRES_TEST_TIMEOUT_MS } from "@paperclipai/db";
|
|
import { randomBytes, randomUUID } from "node:crypto";
|
|
import { createFullDatabaseResponseCapture, installDatabaseResponseCapture } from "./helpers/full-database-response-capture.js";
|
|
import { spawn } from "node:child_process";
|
|
import os from "node:os";
|
|
import { and, eq, sql } from "drizzle-orm";
|
|
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
|
import {
|
|
agents,
|
|
authUsers,
|
|
companies,
|
|
companyMemberships,
|
|
createDb,
|
|
environmentLeases,
|
|
heartbeatRunEvents,
|
|
heartbeatRuns,
|
|
issues,
|
|
nativeRunFinalizations,
|
|
} from "@paperclipai/db";
|
|
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
|
import { appendHeartbeatRunEvent } from "../services/heartbeat-run-events.js";
|
|
import { persistHeartbeatRunProcessMetadata } from "../services/heartbeat/run-lifecycle.js";
|
|
import {
|
|
hasNativeLocalProcessStop,
|
|
readNativeLocalProcessStop,
|
|
discoverSettledNativeRunProcesses,
|
|
pendingSettledNativeRunProcessIds,
|
|
releaseSettledNativeRunProcess,
|
|
retryPendingSettledNativeRunProcesses,
|
|
settleNativeRunProcess,
|
|
withReleasedNativeRunProcess,
|
|
} from "../services/native-local-process-stop.js";
|
|
import { remoteTerminationReceipt } from "../services/remote-execution-termination.js";
|
|
import { heartbeatService } from "../services/heartbeat.js";
|
|
|
|
const execute = vi.hoisted(() => vi.fn());
|
|
vi.mock("../adapters/index.js", async () => {
|
|
const actual = await vi.importActual<typeof import("../adapters/index.js")>("../adapters/index.js");
|
|
return { ...actual, getServerAdapter: vi.fn(() => ({ supportsLocalAgentJwt: false, execute })) };
|
|
});
|
|
|
|
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_SETTLED_PROCESS_TEST_DATABASE_URL");
|
|
const support = await getEmbeddedPostgresTestSupport();
|
|
const suite = external || support.supported ? describe : describe.skip;
|
|
|
|
function startDetached() {
|
|
const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { detached: true, stdio: "ignore" });
|
|
child.unref();
|
|
return child;
|
|
}
|
|
|
|
async function exitedPid() {
|
|
const child = startDetached();
|
|
const pid = child.pid!;
|
|
await new Promise<void>(resolve => { child.once("exit", () => resolve()); child.kill("SIGKILL"); });
|
|
return pid;
|
|
}
|
|
|
|
suite("settled native run process identity", () => {
|
|
let db: ReturnType<typeof createDb>;
|
|
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
|
|
let companyId: string;
|
|
let agentId: string;
|
|
const children: ReturnType<typeof startDetached>[] = [];
|
|
|
|
beforeAll(async () => {
|
|
if (!external) temporary = await startEmbeddedPostgresTestDatabase("native-settled-process-");
|
|
db = createDb(external ?? temporary!.connectionString, { maxConnections: 6 });
|
|
if (external) await db.execute(sql`truncate companies cascade`);
|
|
companyId = randomUUID();
|
|
agentId = randomUUID();
|
|
await db.insert(companies).values({ id: companyId, name: "Settled processes", issuePrefix: "SPR", defaultResponsibleUserId: "owner" });
|
|
await db.insert(authUsers).values({ id: "owner", name: "Fixture user", email: "owner@example.test", createdAt: new Date(), updatedAt: new Date() }).onConflictDoNothing();
|
|
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "owner", status: "active", membershipRole: "member" });
|
|
await db.insert(agents).values({ id: agentId, companyId, name: "Worker", role: "engineer", status: "idle", adapterType: "process",
|
|
adapterConfig: {}, permissions: {}, runtimeConfig: { heartbeat: { enabled: false, wakeOnDemand: true, maxConcurrentRuns: 20 } } });
|
|
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
|
|
|
|
afterEach(() => {
|
|
for (const child of children.splice(0)) {
|
|
try { process.kill(-child.pid!, "SIGKILL"); } catch { }
|
|
}
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await db?.$client.end({ timeout: 0 });
|
|
await temporary?.cleanup();
|
|
});
|
|
|
|
type Fixture = {
|
|
status?: string;
|
|
phase?: string | null;
|
|
pid?: number;
|
|
hostname?: string;
|
|
checkpoint?: boolean;
|
|
providerEvidence?: boolean;
|
|
leases?: Array<"local" | "local_unreleased" | "remote_stopped" | "remote_unconfirmed">;
|
|
finishedAt?: Date;
|
|
};
|
|
|
|
async function seed(fixture: Fixture = {}) {
|
|
const issueId = randomUUID();
|
|
const runId = randomUUID();
|
|
const pid = fixture.pid ?? await exitedPid();
|
|
await db.insert(issues).values({ id: issueId, companyId, title: "Settled process", status: "in_progress", assigneeAgentId: agentId });
|
|
await db.insert(heartbeatRuns).values({
|
|
id: runId, companyId, agentId, status: "running", runtimeMode: "native", nativeIssueId: issueId,
|
|
invocationSource: "assignment", triggerDetail: "system", contextSnapshot: { issueId },
|
|
runnerProfileJson: fixture.checkpoint === false ? {} : { sessionCheckpoint: { providerSessionId: "thread" } },
|
|
});
|
|
if (fixture.hostname) {
|
|
await db.update(heartbeatRuns).set({ processPid: pid, processGroupId: pid, processStartedAt: new Date() }).where(eq(heartbeatRuns.id, runId));
|
|
await appendHeartbeatRunEvent(db, { companyId, runId, agentId, eventType: "native.process_identity_recorded", stream: "system", level: "info",
|
|
message: "Process identity recorded", payload: { targetKind: "local", hostname: fixture.hostname, processPid: pid, processGroupId: pid } });
|
|
} else {
|
|
await persistHeartbeatRunProcessMetadata(db, runId, { pid, processGroupId: pid, startedAt: new Date().toISOString(), targetKind: "local" });
|
|
}
|
|
if (fixture.providerEvidence) {
|
|
await appendHeartbeatRunEvent(db, { companyId, runId, agentId, eventType: "harness.ready", stream: "system", level: "info", message: "ready" });
|
|
}
|
|
if (fixture.phase !== null) {
|
|
await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: fixture.phase ?? "committed" });
|
|
}
|
|
for (const kind of fixture.leases ?? ["local"]) {
|
|
const remote = kind.startsWith("remote");
|
|
const [lease] = await db.insert(environmentLeases).values({
|
|
companyId, issueId, heartbeatRunId: runId, provider: remote ? "sandbox-fixture" : "local",
|
|
providerLeaseId: remote ? randomUUID() : null, leasePolicy: "ephemeral",
|
|
status: kind === "local_unreleased" ? "active" : "released", releasedAt: kind === "local_unreleased" ? null : new Date(),
|
|
cleanupStatus: kind === "local_unreleased" ? null : "success",
|
|
}).returning();
|
|
if (kind === "remote_stopped") {
|
|
await db.update(environmentLeases).set({ metadata: {
|
|
remoteExecutionTermination: remoteTerminationReceipt(lease!, { providerLeaseId: lease!.providerLeaseId, state: "stopped" }),
|
|
} }).where(eq(environmentLeases.id, lease!.id));
|
|
}
|
|
}
|
|
await db.update(heartbeatRuns).set({ status: fixture.status ?? "failed", finishedAt: fixture.finishedAt ?? new Date() })
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
return { runId, issueId, pid };
|
|
}
|
|
|
|
const readRun = (runId: string) => db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).then(rows => rows[0]!);
|
|
|
|
it("releases a failed native run's local identity with a stop receipt once its process is gone", async () => {
|
|
const { runId, pid } = await seed();
|
|
expect(await readRun(runId)).toMatchObject({ processPid: pid, processGroupId: pid });
|
|
const before = await readRun(runId);
|
|
expect(await releaseSettledNativeRunProcess(db, runId)).toBe("released");
|
|
const after = await readRun(runId);
|
|
expect(after).toMatchObject({ status: "failed", processPid: null, processGroupId: null, processStartedAt: null });
|
|
expect(await hasNativeLocalProcessStop(db, companyId, runId)).toBe(true);
|
|
expect(await readNativeLocalProcessStop(db, companyId, runId)).toEqual({
|
|
processPid: pid, processGroupId: pid, processStartedAt: before.processStartedAt!.toISOString(),
|
|
});
|
|
expect(await withReleasedNativeRunProcess(db, after)).toMatchObject({
|
|
processPid: pid, processGroupId: pid, processStartedAt: before.processStartedAt,
|
|
});
|
|
expect(await releaseSettledNativeRunProcess(db, runId)).toBe("skipped");
|
|
});
|
|
|
|
it("releases the identity from the periodic recovery sweep", async () => {
|
|
const { runId } = await seed({ status: "timed_out" });
|
|
const child = startDetached();
|
|
children.push(child);
|
|
const alive = await seed({ pid: child.pid! });
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.reapOrphanedRuns();
|
|
expect((await readRun(runId)).processPid).toBeNull();
|
|
expect(await hasNativeLocalProcessStop(db, companyId, runId)).toBe(true);
|
|
expect((await readRun(alive.runId)).processPid).toBe(child.pid);
|
|
await new Promise<void>(resolve => { child.once("exit", () => resolve()); process.kill(-child.pid!, "SIGKILL"); });
|
|
await heartbeat.reapOrphanedRuns();
|
|
expect((await readRun(alive.runId)).processPid).toBeNull();
|
|
}, 30_000);
|
|
|
|
it.each([
|
|
["failed", true],
|
|
["succeeded", false],
|
|
] as const)("releases a %s native run's identity when its executor settles: %s", async (status, released) => {
|
|
const pid = await exitedPid();
|
|
const issueId = randomUUID();
|
|
await db.insert(issues).values({ id: issueId, companyId, title: "Executor settlement", status: "todo", assigneeAgentId: agentId, responsibleUserId: "owner" });
|
|
let runId = "";
|
|
execute.mockReset().mockImplementation(async (context: { runId: string }) => {
|
|
if (runId) return { exitCode: 0, signal: null, timedOut: false, summary: "Follow-up" };
|
|
runId = context.runId;
|
|
await db.update(heartbeatRuns).set({ runtimeMode: "native", nativeIssueId: issueId,
|
|
runnerProfileJson: { sessionCheckpoint: { providerSessionId: "thread" } } }).where(eq(heartbeatRuns.id, runId));
|
|
await persistHeartbeatRunProcessMetadata(db, runId, { pid, processGroupId: pid, startedAt: new Date().toISOString(), targetKind: "local" });
|
|
await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "committed" });
|
|
await db.update(heartbeatRuns).set({ status, finishedAt: new Date() }).where(eq(heartbeatRuns.id, runId));
|
|
return { exitCode: status === "failed" ? 1 : 0, signal: null, timedOut: false, summary: "Settled" };
|
|
});
|
|
const heartbeat = heartbeatService(db);
|
|
await heartbeat.invoke(agentId, "on_demand", { issueId }, "manual");
|
|
await heartbeat.drainActiveRunExecutions();
|
|
const run = await readRun(runId);
|
|
expect(run.status).toBe(status);
|
|
expect(run.processPid).toBe(released ? null : pid);
|
|
expect(await hasNativeLocalProcessStop(db, companyId, runId)).toBe(released);
|
|
const events = await db.select().from(heartbeatRunEvents).where(and(eq(heartbeatRunEvents.runId, runId),
|
|
eq(heartbeatRunEvents.eventType, "native.local_process_stopped")));
|
|
expect(events).toHaveLength(released ? 1 : 0);
|
|
}, 30_000);
|
|
|
|
it.each(["cancelled", "timed_out", "interrupted"])("releases a settled %s native run", async status => {
|
|
const { runId } = await seed({ status });
|
|
expect(await releaseSettledNativeRunProcess(db, runId)).toBe("released");
|
|
expect((await readRun(runId)).processPid).toBeNull();
|
|
});
|
|
|
|
it("releases the stopped identity without reading saved execution payloads", async () => {
|
|
const { runId } = await seed();
|
|
const bulk = randomBytes(128 * 1024).toString("base64");
|
|
const before = await readRun(runId);
|
|
await db.update(heartbeatRuns).set({ contextSnapshot: { ...before.contextSnapshot, savedTask: bulk },
|
|
runnerProfileJson: { ...before.runnerProfileJson, sessionCheckpoint: { providerSessionId: "thread", savedState: bulk },
|
|
nativeExecutionInput: { task: bulk } }, resultJson: { savedResult: bulk }, stdoutExcerpt: bulk,
|
|
}).where(eq(heartbeatRuns.id, runId));
|
|
const saved = await readRun(runId);
|
|
const events: Array<Record<string, unknown>> = [];
|
|
const now = Date.now();
|
|
const capture = createFullDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event));
|
|
installDatabaseResponseCapture(db, { heartbeatRuns }, capture);
|
|
try { expect(await releaseSettledNativeRunProcess(db, runId)).toBe("released"); }
|
|
finally { capture.flush(); }
|
|
const summary = events.find(event => event.event === "paperclip.test_db_response_capture.summary.v1")!;
|
|
expect(summary.responseValueBytes).toBeLessThan(8192);
|
|
const after = await readRun(runId);
|
|
expect(after).toEqual({ ...saved, processPid: null, processGroupId: null, processStartedAt: null,
|
|
nextEventSeq: saved.nextEventSeq + 1, updatedAt: after.updatedAt });
|
|
expect(await hasNativeLocalProcessStop(db, companyId, runId)).toBe(true);
|
|
expect(JSON.stringify(events)).not.toContain(bulk.slice(0, 64));
|
|
});
|
|
|
|
it.each([null, false, 0, "", {}, []].map(checkpoint => ({ checkpoint })))(
|
|
"preserves checkpoint presence semantics when releasing an identity ($checkpoint)", async ({ checkpoint }) => {
|
|
const { runId, pid } = await seed({ checkpoint: false });
|
|
await db.update(heartbeatRuns).set({ runnerProfileJson: { sessionCheckpoint: checkpoint } })
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
expect(await releaseSettledNativeRunProcess(db, runId)).toBe(checkpoint === null ? "skipped" : "released");
|
|
expect((await readRun(runId)).processPid).toBe(checkpoint === null ? pid : null);
|
|
},
|
|
);
|
|
|
|
it.each(["absent", "live", "foreign host", "known birth mismatch"])("preserves exact legacy null-birth compatibility without clearing unsafe identity: %s", async kind => {
|
|
const child = kind === "live" ? startDetached() : undefined;
|
|
if (child) children.push(child);
|
|
const { runId, pid } = await seed({ ...(child ? { pid: child.pid! } : {}),
|
|
...(kind === "foreign host" ? { hostname: `${os.hostname()}-foreign` } : {}) });
|
|
await db.update(heartbeatRuns).set({ processStartedAt: kind === "known birth mismatch" ? new Date(0) : null })
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
expect(await releaseSettledNativeRunProcess(db, runId)).toBe(kind === "absent" ? "released" : kind === "live" ? "pending" : "skipped");
|
|
expect((await readRun(runId)).processPid).toBe(kind === "absent" ? null : pid);
|
|
expect(await hasNativeLocalProcessStop(db, companyId, runId)).toBe(kind === "absent");
|
|
});
|
|
it("keeps the identity while the process is still alive, then releases it after exit", async () => {
|
|
const child = startDetached();
|
|
children.push(child);
|
|
const { runId } = await seed({ pid: child.pid! });
|
|
expect(await releaseSettledNativeRunProcess(db, runId)).toBe("pending");
|
|
expect((await readRun(runId)).processPid).toBe(child.pid);
|
|
expect(await hasNativeLocalProcessStop(db, companyId, runId)).toBe(false);
|
|
await new Promise<void>(resolve => { child.once("exit", () => resolve()); process.kill(-child.pid!, "SIGKILL"); });
|
|
expect(await releaseSettledNativeRunProcess(db, runId)).toBe("released");
|
|
expect((await readRun(runId)).processPid).toBeNull();
|
|
});
|
|
|
|
it.each([
|
|
["a succeeded run that can hand its runner to the next turn", { status: "succeeded" }, "skipped"],
|
|
["a same-run retry that still owns the process identity", { phase: "retryable_failure" }, "skipped"],
|
|
["unfinished workspace finalization", { phase: "workspace_finalizing" }, "skipped"],
|
|
["an unreleased local lease", { leases: ["local_unreleased"] }, "pending"],
|
|
["a process recorded by another host", { hostname: `${os.hostname()}-other` }, "skipped"],
|
|
["a launch without provider evidence or checkpoint", { checkpoint: false }, "skipped"],
|
|
["a sandbox without a termination receipt", { leases: ["remote_unconfirmed"] }, "pending"],
|
|
["a mixed local and sandbox run", { leases: ["local", "remote_stopped"] }, "pending"],
|
|
] as const)("keeps the identity for %s", async (_name, fixture, outcome) => {
|
|
const { runId, pid } = await seed(fixture as Fixture);
|
|
expect(await releaseSettledNativeRunProcess(db, runId)).toBe(outcome);
|
|
expect(await readRun(runId)).toMatchObject({ processPid: pid, processGroupId: pid });
|
|
});
|
|
|
|
it("releases evidence-only launches and runs without a coordinator", async () => {
|
|
const evidence = await seed({ checkpoint: false, providerEvidence: true });
|
|
const uncoordinated = await seed({ phase: null });
|
|
expect(await releaseSettledNativeRunProcess(db, evidence.runId)).toBe("released");
|
|
expect(await releaseSettledNativeRunProcess(db, uncoordinated.runId)).toBe("released");
|
|
});
|
|
|
|
it("releases a sandbox identity only after every lease confirmed termination", async () => {
|
|
const { runId } = await seed({ leases: ["remote_stopped"] });
|
|
expect(await releaseSettledNativeRunProcess(db, runId)).toBe("released");
|
|
expect((await readRun(runId)).processPid).toBeNull();
|
|
expect(await hasNativeLocalProcessStop(db, companyId, runId)).toBe(false);
|
|
});
|
|
|
|
it("discovers settled runs in pages, skips live executions, and retries only pending releases", async () => {
|
|
const first = await seed();
|
|
const skipped = await seed();
|
|
const child = startDetached();
|
|
children.push(child);
|
|
const alive = await seed({ pid: child.pid! });
|
|
await discoverSettledNativeRunProcesses(db, { limit: 1, skip: runId => runId === skipped.runId });
|
|
expect((await readRun(first.runId)).processPid).toBeNull();
|
|
expect((await readRun(skipped.runId)).processPid).toBe(skipped.pid);
|
|
expect((await readRun(alive.runId)).processPid).toBe(child.pid);
|
|
expect(pendingSettledNativeRunProcessIds()).toContain(alive.runId);
|
|
expect(pendingSettledNativeRunProcessIds()).not.toContain(skipped.runId);
|
|
await new Promise<void>(resolve => { child.once("exit", () => resolve()); process.kill(-child.pid!, "SIGKILL"); });
|
|
await retryPendingSettledNativeRunProcesses(db);
|
|
expect((await readRun(alive.runId)).processPid).toBeNull();
|
|
expect(pendingSettledNativeRunProcessIds()).not.toContain(alive.runId);
|
|
await settleNativeRunProcess(db, skipped.runId);
|
|
expect(pendingSettledNativeRunProcessIds()).not.toContain(skipped.runId);
|
|
for (let attempt = 0; attempt < 25 && pendingSettledNativeRunProcessIds().length; attempt += 1) {
|
|
await retryPendingSettledNativeRunProcesses(db);
|
|
}
|
|
expect(pendingSettledNativeRunProcessIds()).toEqual([]);
|
|
const idle = new Proxy({}, { get: () => { throw new Error("idle retry touched the database"); } }) as typeof db;
|
|
await retryPendingSettledNativeRunProcesses(idle);
|
|
});
|
|
|
|
it("stops retrying a release that never becomes ready", async () => {
|
|
const { runId } = await seed({ leases: ["local_unreleased"] });
|
|
expect(await settleNativeRunProcess(db, runId)).toBe("pending");
|
|
expect(pendingSettledNativeRunProcessIds()).toContain(runId);
|
|
for (let attempt = 0; attempt < 18; attempt += 1) await retryPendingSettledNativeRunProcesses(db);
|
|
expect(pendingSettledNativeRunProcessIds()).toContain(runId);
|
|
await retryPendingSettledNativeRunProcesses(db);
|
|
expect(pendingSettledNativeRunProcessIds()).not.toContain(runId);
|
|
expect((await readRun(runId)).processPid).not.toBeNull();
|
|
});
|
|
});
|