mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-06 07:38:47 +01:00
merge: preserve current Native diagnostics and master changes
* commit 'f7a3497e9d865487b6071fbedaa4b56a20ce44ad': fix(evals): compare browser zones by clock, wait for the reloaded profile name, bind accounting reads by returned run (#21760) test(restart-chaos): count distinct warm close failures and let R5 wait out environment acquire (#21852) fix(native): stop a finished warm owner's retained Runner when suspend is refused, and release a suspended Runner whose process left (#21853)
This commit is contained in:
commit
958211c061
31 files changed
+1142
-77
No files matched your search
@@ -438,6 +438,7 @@ import {
|
||||
closeIdleWarmNativeSessionsForRestart,
|
||||
WARM_IDLE_CLOSE_MAX_RETRIES,
|
||||
WARM_IDLE_CLOSE_RETRY_MS,
|
||||
warmRetainedRunnerStopWait,
|
||||
readNativeSessionIdleWork,
|
||||
createGovernedWaitEventObservation,
|
||||
createRemoteRunnerProcessLauncher,
|
||||
@@ -12528,6 +12529,201 @@ describe("native warm session supervision", () => {
|
||||
expect(await closeIdleWarmNativeSessionsForRestart()).toMatchObject({ closed: 1, failed: 0 });
|
||||
});
|
||||
|
||||
it("keeps retrying a failed idle warm close after a failed environment sweep cleared its retry timer", async () => {
|
||||
const name = "warm-idle-close-retry-after-sweep";
|
||||
const current = { ...execution,
|
||||
binding: { ...execution.binding, runId: name, executionWorkspaceId: name },
|
||||
session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 20 } },
|
||||
} as NativeExecutionInputV1;
|
||||
const close = vi.fn<() => Promise<void>>(async () => { throw new Error("native_runner_checkpoint_owner_lost"); });
|
||||
state.execute.mockReset().mockImplementationOnce(async options => {
|
||||
await options.onSession?.({ close });
|
||||
return { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" },
|
||||
turnId: name, normalizedSessionId: name, providerSessionId: name, driverKind: "test", driverVersion: "1",
|
||||
nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null };
|
||||
});
|
||||
const target = { kind: "remote" as const, transport: "sandbox" as const, environmentId: name,
|
||||
remoteCwd: `/tmp/${name}`, sandboxLeaseAcquisition: { outcome: "created" as const, providerLeaseId: name } };
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
|
||||
try {
|
||||
await executePaperclipNativeSession({ db: leaseDb(current), execution: current, runnerInstanceId: name, runnerExecutionTarget: target });
|
||||
await vi.advanceTimersByTimeAsync(20);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
expect(await closeWarmNativeSessionsForEnvironment({ environmentId: name, reason: "environment deleted" }))
|
||||
.toMatchObject({ closed: 0, failed: 1 });
|
||||
expect(close).toHaveBeenCalledTimes(2);
|
||||
await vi.advanceTimersByTimeAsync(WARM_IDLE_CLOSE_RETRY_MS);
|
||||
expect(close).toHaveBeenCalledTimes(3);
|
||||
} finally { vi.useRealTimers(); }
|
||||
close.mockResolvedValue(undefined);
|
||||
expect(await closeWarmNativeSessionsForEnvironment({ environmentId: name, reason: "test cleanup" })).toMatchObject({ closed: 1 });
|
||||
});
|
||||
|
||||
function fakeRetainedRunnerSandbox(input: { runId: string; normalizedSessionId: string; remoteCwd: string;
|
||||
lifecycle?: string; stopsOn?: "TERM" | "never"; runnerIdCarriers?: number[]; unreadableProcesses?: number }) {
|
||||
const runnerInstanceId = "runner-instance-retained";
|
||||
const sessionDirectory = createHash("sha256").update(input.normalizedSessionId).digest("hex");
|
||||
const stateDirectory = `${input.remoteCwd}/.paperclip-runtime/paperclip-runner/sessions/${sessionDirectory}/runner`;
|
||||
const identity = `retainednonce\n522\n2026-11-16T00:47:54.000Z\n${runnerInstanceId}\nlinux:abcd-1234:100\n`;
|
||||
const runnerState = { runnerInstanceId, runId: input.runId, normalizedSessionId: input.normalizedSessionId,
|
||||
lifecycle: input.lifecycle ?? "ready", outbox: [], pendingTerminalDelivery: null, pendingProviderCleanup: null, warmTransition: null };
|
||||
const sandbox = { alive: true, signals: [] as string[], labels: [] as string[] };
|
||||
const encode = (value: string) => Buffer.from(value).toString("base64");
|
||||
const runner = { execute: vi.fn(async (request: { args?: string[] }) => {
|
||||
const args = request.args ?? [];
|
||||
const label = args[2] ?? "";
|
||||
sandbox.labels.push(label);
|
||||
if (label === "paperclip-runner-port-holders") {
|
||||
return { exitCode: 0, timedOut: false, stderr: "",
|
||||
stdout: `${stateDirectory}/runner-process.identity\t${encode(identity)}\t${encode(JSON.stringify(runnerState))}\n` };
|
||||
}
|
||||
if (label === "paperclip-runner-port-holder-check" || label === "paperclip-runner-exit-check") {
|
||||
const signal = args[8];
|
||||
if (signal) {
|
||||
sandbox.signals.push(signal);
|
||||
if (input.stopsOn !== "never") sandbox.alive = false;
|
||||
return { exitCode: 0, timedOut: false, stdout: "", stderr: "" };
|
||||
}
|
||||
return { exitCode: sandbox.alive ? 0 : 45, timedOut: false, stdout: "", stderr: "" };
|
||||
}
|
||||
if (label === "paperclip-runner-session-inspect") {
|
||||
expect(args[4]).toBe(stateDirectory);
|
||||
return { exitCode: 0, timedOut: false, stderr: "", stdout: JSON.stringify({
|
||||
state: { lifecycle: runnerState.lifecycle, runId: input.runId, normalizedSessionId: input.normalizedSessionId,
|
||||
runnerInstanceId, settled: true },
|
||||
markerPid: 522, markerRunnerIdMatchesState: true, procfs: true, unreadableProcesses: input.unreadableProcesses ?? 0,
|
||||
processes: (input.runnerIdCarriers ?? (sandbox.alive && runnerState.lifecycle !== "suspended" ? [522] : []))
|
||||
.map(pid => ({ pid, state: "S", carriesRunnerId: true })),
|
||||
}) };
|
||||
}
|
||||
return { exitCode: 1, timedOut: false, stdout: "", stderr: "" };
|
||||
}) };
|
||||
return { sandbox, runner };
|
||||
}
|
||||
|
||||
async function startRetainedWarmOwner(name: string, close: () => Promise<void>, sandboxInput: Omit<Parameters<typeof fakeRetainedRunnerSandbox>[0], "runId" | "normalizedSessionId" | "remoteCwd">) {
|
||||
const runId = randomUUID();
|
||||
const current = { ...execution,
|
||||
binding: { ...execution.binding, runId, executionWorkspaceId: name },
|
||||
session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 60_000 } },
|
||||
} as NativeExecutionInputV1;
|
||||
const fake = fakeRetainedRunnerSandbox({ runId, normalizedSessionId: name, remoteCwd: `/tmp/${name}`, ...sandboxInput });
|
||||
const target = { kind: "remote" as const, transport: "sandbox" as const, environmentId: name, remoteCwd: `/tmp/${name}`,
|
||||
sandboxLeaseAcquisition: { outcome: "created" as const, providerLeaseId: name }, runner: fake.runner };
|
||||
state.execute.mockReset().mockImplementationOnce(async options => {
|
||||
await options.onSession?.({ close });
|
||||
return { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" },
|
||||
turnId: name, normalizedSessionId: name, providerSessionId: name, driverKind: "test", driverVersion: "1",
|
||||
nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null };
|
||||
});
|
||||
await expect(executePaperclipNativeSession({ db: leaseDb(current), execution: current, runnerInstanceId: name,
|
||||
runnerExecutionTarget: target as never })).resolves.toMatchObject({ exitCode: 0 });
|
||||
return { current, ...fake, finishedDb: leaseDb(current, {}, {}, [], {}, "succeeded") };
|
||||
}
|
||||
|
||||
const refusedSuspend = () => new NativeSessionCloseUnrecoverableError({ runnerSuspended: false, runnerRetained: true,
|
||||
providerDrained: true, suspensionState: { commandStatus: "failed", runnerLifecycle: "ready", runnerIdentityMatches: true },
|
||||
proofWindowEnd: "suspend_not_completed" });
|
||||
|
||||
it("stops the retained Runner of a finished warm owner that refused suspend and releases it without a checkpoint when its environment is deleted", async () => {
|
||||
const name = "warm-retained-runner-refused-suspend";
|
||||
const close = vi.fn<() => Promise<void>>(async () => { throw refusedSuspend(); });
|
||||
const { sandbox, finishedDb, current } = await startRetainedWarmOwner(name, close, {});
|
||||
state.persistActivity.mockClear();
|
||||
expect(await closeWarmNativeSessionsForEnvironment({ environmentId: name, reason: "environment deleted",
|
||||
forceStopUnsettled: true, db: finishedDb })).toEqual({ closed: 1, busy: 0, failed: 0, failures: [] });
|
||||
expect(close).toHaveBeenCalledOnce();
|
||||
expect(sandbox.signals).toEqual(["TERM"]);
|
||||
expect(sandbox.alive).toBe(false);
|
||||
expect(sandbox.labels).toContain("paperclip-runner-exit-check");
|
||||
expect(state.persistActivity).toHaveBeenCalledWith(finishedDb, expect.objectContaining({
|
||||
action: "native.runner_port_holder_retired", details: expect.objectContaining({ holderRunId: current.binding.runId, outcome: "stopped" }) }));
|
||||
expect(readNativeSessionIdleWork()).toBe("none");
|
||||
});
|
||||
|
||||
it("keeps a finished warm owner whose retained Runner survives the stop", async () => {
|
||||
const name = "warm-retained-runner-survives";
|
||||
const close = vi.fn<() => Promise<void>>(async () => { throw refusedSuspend(); });
|
||||
const { sandbox, finishedDb } = await startRetainedWarmOwner(name, close, { stopsOn: "never" });
|
||||
const wait = { ...warmRetainedRunnerStopWait };
|
||||
Object.assign(warmRetainedRunnerStopWait, { waitMs: 20, pollMs: 5 });
|
||||
try {
|
||||
expect(await closeWarmNativeSessionsForEnvironment({ environmentId: name, reason: "environment deleted",
|
||||
forceStopUnsettled: true, db: finishedDb })).toMatchObject({ closed: 0, failed: 1 });
|
||||
} finally { Object.assign(warmRetainedRunnerStopWait, wait); }
|
||||
expect(sandbox.signals).toEqual(["TERM", "KILL"]);
|
||||
expect(sandbox.labels).not.toContain("paperclip-runner-exit-check");
|
||||
expect(readNativeSessionIdleWork()).toBe("present");
|
||||
close.mockResolvedValue(undefined);
|
||||
expect(await closeWarmNativeSessionsForEnvironment({ environmentId: name, reason: "test cleanup" })).toMatchObject({ closed: 1 });
|
||||
});
|
||||
|
||||
it("never stops the retained Runner of a warm owner whose run has not finished", async () => {
|
||||
const name = "warm-retained-runner-unfinished";
|
||||
const close = vi.fn<() => Promise<void>>(async () => { throw refusedSuspend(); });
|
||||
const { sandbox, current } = await startRetainedWarmOwner(name, close, {});
|
||||
expect(await closeWarmNativeSessionsForEnvironment({ environmentId: name, reason: "environment deleted",
|
||||
forceStopUnsettled: true, db: leaseDb(current, {}, {}, [], {}, "running") })).toMatchObject({ closed: 0, failed: 1 });
|
||||
expect(sandbox.signals).toEqual([]);
|
||||
close.mockResolvedValue(undefined);
|
||||
expect(await closeWarmNativeSessionsForEnvironment({ environmentId: name, reason: "test cleanup" })).toMatchObject({ closed: 1 });
|
||||
});
|
||||
|
||||
it("logs sandbox Runner evidence for a close failure of a warm session reused by a later run", async () => {
|
||||
const name = "warm-reused-close-evidence";
|
||||
const close = vi.fn<() => Promise<void>>(async () => undefined);
|
||||
const session = { close };
|
||||
const { current, runner, sandbox } = await startRetainedWarmOwner(name, close, {});
|
||||
const second = { ...current, binding: { ...current.binding, runId: randomUUID() } } as NativeExecutionInputV1;
|
||||
state.execute.mockReset().mockImplementationOnce(async options => {
|
||||
expect(options.existingSession).toBeDefined();
|
||||
await options.onSession?.(options.existingSession ?? session);
|
||||
return { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" },
|
||||
turnId: name, normalizedSessionId: name, providerSessionId: name, driverKind: "test", driverVersion: "1",
|
||||
nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null };
|
||||
});
|
||||
await expect(executePaperclipNativeSession({ db: leaseDb(second), execution: second, runnerInstanceId: name,
|
||||
runnerExecutionTarget: { kind: "remote", transport: "sandbox", environmentId: name, remoteCwd: `/tmp/${name}`,
|
||||
sandboxLeaseAcquisition: { outcome: "resumed", providerLeaseId: name }, runner } as never })).resolves.toMatchObject({ exitCode: 0 });
|
||||
expect(state.execute).toHaveBeenCalledOnce();
|
||||
close.mockImplementation(async () => {
|
||||
throw new RemoteRunnerRecoveryError({ stage: "process_verification", reason: "marker_missing" });
|
||||
});
|
||||
sandbox.labels.length = 0;
|
||||
expect(await closeIdleWarmNativeSessionsForRestart()).toMatchObject({ closed: 0, failed: 1 });
|
||||
expect(sandbox.labels).toContain("paperclip-runner-session-inspect");
|
||||
close.mockResolvedValue(undefined);
|
||||
expect(await closeIdleWarmNativeSessionsForRestart()).toMatchObject({ closed: 1 });
|
||||
});
|
||||
|
||||
it("releases at controller restart a warm owner whose Runner durably suspended and exited but whose check found a live process without its runner id", async () => {
|
||||
const name = "warm-suspended-runner-id-missing";
|
||||
const close = vi.fn<() => Promise<void>>(async () => {
|
||||
throw new RemoteRunnerRecoveryError({ stage: "process_verification", reason: "process_runner_id_missing" });
|
||||
});
|
||||
const { sandbox } = await startRetainedWarmOwner(name, close, { lifecycle: "suspended" });
|
||||
sandbox.alive = false;
|
||||
expect(await closeIdleWarmNativeSessionsForRestart()).toEqual({ closed: 1, busy: 0, failed: 0, failures: [] });
|
||||
expect(sandbox.signals).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a live process still carries its runner id", "process_runner_id_missing", [522], 0],
|
||||
["a process command line could not be read", "process_runner_id_missing", [], 1],
|
||||
["the check reported only a changed identity", "process_identity_changed", [], 0],
|
||||
] as const)("keeps a durably suspended warm owner when %s", async (label, reason, carriers, unreadableProcesses) => {
|
||||
const name = `warm-suspended-kept-${label.replaceAll(" ", "-")}`;
|
||||
const close = vi.fn<() => Promise<void>>(async () => {
|
||||
throw new RemoteRunnerRecoveryError({ stage: "process_verification", reason });
|
||||
});
|
||||
const { sandbox } = await startRetainedWarmOwner(name, close, { lifecycle: "suspended", runnerIdCarriers: [...carriers],
|
||||
unreadableProcesses });
|
||||
sandbox.alive = false;
|
||||
expect(await closeIdleWarmNativeSessionsForRestart()).toMatchObject({ closed: 0, failed: 1 });
|
||||
close.mockResolvedValue(undefined);
|
||||
expect(await closeIdleWarmNativeSessionsForRestart()).toMatchObject({ closed: 1 });
|
||||
});
|
||||
|
||||
it.each(["failed", "cancelled"] as const)("retires a %s session even if its warm checkpoint rejects", async (runTerminalState) => {
|
||||
const name = `warm-checkpoint-rejects-${runTerminalState}`;
|
||||
const current = { ...execution,
|
||||
|
||||
@@ -67,7 +67,9 @@ import { preparePluginRunnerCredentials } from "./plugin-runner-credentials.js";
|
||||
import { createPluginRunnerTaskOwner, verifyPluginRunnerTaskReattachment } from "./plugin-runner-task.js";
|
||||
import { findNativeFailedBeforeProviderTurn, NATIVE_FAILED_BEFORE_PROVIDER_TURN_CODE, NativeFailedBeforeProviderTurnError } from "./failed-before-provider-turn.js";
|
||||
import { findNativePredecessorRetirementUnproven, NATIVE_PREDECESSOR_RETIREMENT_UNPROVEN_CODE, NativePredecessorRetirementDirectoryBusyError, NativePredecessorRetirementUnprovenError } from "./predecessor-retirement.js";
|
||||
import { retireSandboxRunnerPortHolders } from "./sandbox-runner-port-holders.js";
|
||||
import {
|
||||
inspectSandboxSessionRunner, retireSandboxRunnerPortHolders, sandboxSessionRunnerExited, type SandboxSessionRunnerInspection,
|
||||
} from "./sandbox-runner-port-holders.js";
|
||||
import { AgentDirectoryOperationBusyError } from "../agent-directory-working-copies.js";
|
||||
import { agentDirectoryBusyRetryDelayMs } from "../heartbeat/agent-directory-busy.js";
|
||||
import { NativeExecutionContext } from "./native-execution-context.js";
|
||||
@@ -721,6 +723,8 @@ type WarmNativeSession = {
|
||||
/** The sandbox that holds this owner's Runner, when it runs in one. */
|
||||
providerLeaseId?: string;
|
||||
sandboxLeaseDb?: Db;
|
||||
sandboxRunner?: { runner: CommandManagedRuntimeRunner; remoteCwd: string };
|
||||
closeFailureEvidenceLogged?: boolean;
|
||||
/** A successor's retirement of this owner failed; it stays registered for its own sandbox. */
|
||||
retirementUnproven?: boolean;
|
||||
observabilityCompatibilityKey?: string;
|
||||
@@ -834,6 +838,11 @@ async function closeWarmNativeSession(entry: WarmNativeSession, reason: string,
|
||||
finally { await stopping; }
|
||||
}
|
||||
|
||||
function warmSandboxRunner(target?: AdapterExecutionTarget | null): WarmNativeSession["sandboxRunner"] {
|
||||
return target?.kind === "remote" && target.transport === "sandbox" && target.runner && !target.runnerTask
|
||||
? { runner: target.runner, remoteCwd: target.remoteCwd } : undefined;
|
||||
}
|
||||
|
||||
function sandboxProviderLeaseId(target?: AdapterExecutionTarget | null): string | null {
|
||||
return target?.kind === "remote" && target.transport === "sandbox" ? target.sandboxLeaseAcquisition?.providerLeaseId ?? null : null;
|
||||
}
|
||||
@@ -1161,12 +1170,88 @@ async function warmRunnerPortTakenBySuccessor(db: Db, entry: WarmNativeSession):
|
||||
async function warmCloseFailureProvesOwnerGone(entry: WarmNativeSession, error: unknown, db = entry.sandboxLeaseDb): Promise<boolean> {
|
||||
const diagnostic = readRemoteRunnerRecoveryError(error);
|
||||
if (diagnostic?.stage === "process_verification" && diagnostic.reason === "process_not_running") return true;
|
||||
const runnerIdMissing = diagnostic?.stage === "process_verification" && diagnostic.reason === "process_runner_id_missing";
|
||||
const logEvidence = Boolean(entry.sandboxRunner) && !entry.closeFailureEvidenceLogged
|
||||
&& (diagnostic !== null || error instanceof NativeSessionCloseUnrecoverableError);
|
||||
const inspection = entry.sandboxRunner && (runnerIdMissing || logEvidence)
|
||||
? await inspectSandboxSessionRunner({ runner: entry.sandboxRunner.runner,
|
||||
stateDirectory: remoteRunnerStateDirectory(entry.sandboxRunner.remoteCwd, entry.normalizedSessionId) }) : null;
|
||||
if (logEvidence) {
|
||||
entry.closeFailureEvidenceLogged = true;
|
||||
logger.warn({ runId: entry.runId, issueId: entry.issueId, environmentId: entry.environmentId,
|
||||
providerLeaseId: entry.providerLeaseId ?? null, ...warmCloseFailureEvidence(entry, error, inspection) },
|
||||
"warm native session close failed; sandbox Runner evidence");
|
||||
}
|
||||
if (runnerIdMissing && suspendedRunnerHasExited(entry, inspection)) return true;
|
||||
try {
|
||||
return db ? await warmSandboxTerminated(db, entry) || await warmRunnerPortTakenBySuccessor(db, entry) : false;
|
||||
if (db && (await warmSandboxTerminated(db, entry) || await warmRunnerPortTakenBySuccessor(db, entry))) return true;
|
||||
} catch (proofError) {
|
||||
logger.warn({ err: proofError, runId: entry.runId }, "could not read the warm session's sandbox lease");
|
||||
return false;
|
||||
}
|
||||
return db ? stopRetainedRunnerOfFinishedOwner(entry, error, db) : false;
|
||||
}
|
||||
|
||||
function warmCloseFailureEvidence(entry: WarmNativeSession, error: unknown, inspection: SandboxSessionRunnerInspection | null) {
|
||||
const diagnostic = readRemoteRunnerRecoveryError(error);
|
||||
const settlement = error instanceof NativeSessionCloseUnrecoverableError ? error.settlement : undefined;
|
||||
const suspension = settlement?.suspensionState && typeof settlement.suspensionState === "object"
|
||||
? settlement.suspensionState as Record<string, unknown> : null;
|
||||
return {
|
||||
closeStage: diagnostic?.stage ?? null,
|
||||
closeReason: diagnostic?.reason ?? (error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : null),
|
||||
closeRunnerLifecycle: diagnostic?.runnerLifecycle ?? suspension?.runnerLifecycle ?? null,
|
||||
runnerSuspended: settlement?.runnerSuspended ?? null,
|
||||
runnerRetained: settlement?.runnerRetained ?? null,
|
||||
suspendCommandStatus: suspension?.commandStatus ?? null,
|
||||
proofWindowEnd: settlement?.proofWindowEnd ?? null,
|
||||
sandboxRunner: inspection ? {
|
||||
lifecycle: inspection.state?.lifecycle ?? null,
|
||||
settled: inspection.state?.settled ?? null,
|
||||
identityMatches: inspection.state !== null && inspection.state.runId === entry.runId
|
||||
&& inspection.state.normalizedSessionId === entry.normalizedSessionId && inspection.markerRunnerIdMatchesState,
|
||||
markerPid: inspection.markerPid,
|
||||
procfs: inspection.procfs,
|
||||
unreadableProcesses: inspection.unreadableProcesses,
|
||||
processes: inspection.processes.slice(0, 20),
|
||||
} : "unavailable",
|
||||
};
|
||||
}
|
||||
|
||||
function suspendedRunnerHasExited(entry: WarmNativeSession, inspection: SandboxSessionRunnerInspection | null): boolean {
|
||||
return inspection !== null && inspection.procfs && inspection.unreadableProcesses === 0 && inspection.state?.lifecycle === "suspended" && inspection.state.settled
|
||||
&& inspection.state.runId === entry.runId && inspection.state.normalizedSessionId === entry.normalizedSessionId
|
||||
&& inspection.markerRunnerIdMatchesState && !inspection.processes.some(process => process.carriesRunnerId);
|
||||
}
|
||||
|
||||
export const warmRetainedRunnerStopWait = { waitMs: 10_000, pollMs: 500 };
|
||||
|
||||
async function stopRetainedRunnerOfFinishedOwner(entry: WarmNativeSession, error: unknown, db: Db): Promise<boolean> {
|
||||
if (!entry.sandboxRunner || !(error instanceof NativeSessionCloseUnrecoverableError)
|
||||
|| error.settlement?.runnerRetained !== true || error.settlement.runnerSuspended === true) return false;
|
||||
const { runner, remoteCwd } = entry.sandboxRunner;
|
||||
const runtimeRoot = posix.join(remoteCwd, ".paperclip-runtime", "paperclip-runner");
|
||||
const sessionDirectory = createHash("sha256").update(entry.normalizedSessionId).digest("hex");
|
||||
try {
|
||||
await retireSandboxRunnerPortHolders({ db, companyId: entry.companyId, agentId: entry.agentId, runId: entry.runId,
|
||||
runner, runtimeRoot, ownSessionRoot: "", providerLeaseId: entry.providerLeaseId ?? null,
|
||||
only: { sessionDirectory, runId: entry.runId }, retireInProcess: async () => false, ...warmRetainedRunnerStopWait });
|
||||
} catch (stopError) {
|
||||
logger.warn({ runId: entry.runId, providerLeaseId: entry.providerLeaseId ?? null, stopFailure: describeWarmCloseFailure(stopError) },
|
||||
"could not stop the retained Runner of a finished warm session");
|
||||
return false;
|
||||
}
|
||||
if (!await sandboxSessionRunnerExited({ runner, runtimeRoot, sessionDirectory })) return false;
|
||||
logger.warn({ runId: entry.runId, issueId: entry.issueId, environmentId: entry.environmentId,
|
||||
providerLeaseId: entry.providerLeaseId ?? null },
|
||||
"stopped the retained Runner of a finished warm session whose suspend was refused; released it without a checkpoint");
|
||||
return true;
|
||||
}
|
||||
|
||||
function armWarmIdleCloseRetry(sessionId: string, entry: WarmNativeSession): void {
|
||||
if (warmNativeSessions.get(sessionId) !== entry || entry.released || (entry.idleCloseRetries ?? 0) >= WARM_IDLE_CLOSE_MAX_RETRIES) return;
|
||||
entry.idleCloseRetries = (entry.idleCloseRetries ?? 0) + 1;
|
||||
armWarmNativeSessionIdleTimer(sessionId, entry, WARM_IDLE_CLOSE_RETRY_MS);
|
||||
}
|
||||
|
||||
/** Detach released owners and checkpoint unreleased owners before a controller
|
||||
@@ -1198,6 +1283,7 @@ async function closeIdleWarmNativeSessions(input: {
|
||||
let busy = 0;
|
||||
let failed = 0;
|
||||
const failures: WarmNativeSessionCloseFailure[] = [];
|
||||
const retryIdleCloseAfterSweep: [string, WarmNativeSession][] = [];
|
||||
let stopped = false;
|
||||
const closeEntry = async (sessionId: string, entry: WarmNativeSession) => {
|
||||
if (entry.busy || entry.preparingRunId || executingRunnerdSessionScopes.has(sessionId)
|
||||
@@ -1244,6 +1330,7 @@ async function closeIdleWarmNativeSessions(input: {
|
||||
return;
|
||||
}
|
||||
failed += 1;
|
||||
if (!detach && entry.idleCloseRetries !== undefined) retryIdleCloseAfterSweep.push([sessionId, entry]);
|
||||
const forced = forcedStopFailure === undefined ? "" : `; forced Runner stop failed: ${describeWarmCloseFailure(forcedStopFailure)}`;
|
||||
failures.push({ runId: entry.runId, issueId: entry.issueId, environmentId: entry.environmentId,
|
||||
providerLeaseId: entry.providerLeaseId ?? null,
|
||||
@@ -1278,6 +1365,7 @@ async function closeIdleWarmNativeSessions(input: {
|
||||
const concurrency = input.canRetire ? 1 : WARM_NATIVE_SESSION_CLOSE_CONCURRENCY;
|
||||
await Promise.all(Array.from({ length: Math.min(concurrency, pendingAgents.length) }, closeAgentQueues));
|
||||
if (failures.length > 0) logger.warn({ reason: input.reason, failures }, "idle warm native sessions did not close");
|
||||
for (const [sessionId, entry] of retryIdleCloseAfterSweep) armWarmIdleCloseRetry(sessionId, entry);
|
||||
return { closed, busy, failed, failures };
|
||||
}
|
||||
|
||||
@@ -8913,9 +9001,7 @@ function armWarmNativeSessionIdleTimer(
|
||||
forgetWarmNativeSession(sessionId, current);
|
||||
return;
|
||||
}
|
||||
if ((current.idleCloseRetries ?? 0) >= WARM_IDLE_CLOSE_MAX_RETRIES) return;
|
||||
current.idleCloseRetries = (current.idleCloseRetries ?? 0) + 1;
|
||||
armWarmNativeSessionIdleTimer(sessionId, current, WARM_IDLE_CLOSE_RETRY_MS);
|
||||
armWarmIdleCloseRetry(sessionId, current);
|
||||
});
|
||||
})
|
||||
.finally(() => {
|
||||
@@ -12776,6 +12862,8 @@ async function executePaperclipNativeSessionAttempt(
|
||||
existing.ingressOwner = ingress ? { ...input.execution.binding, ingress,
|
||||
controllerBootId: controller.bootId, controllerGeneration } : undefined;
|
||||
existing.session = session;
|
||||
existing.sandboxRunner = warmSandboxRunner(input.runnerExecutionTarget);
|
||||
existing.closeFailureEvidenceLogged = false;
|
||||
existing.runId = input.execution.binding.runId;
|
||||
existing.issueId = input.execution.binding.issueId;
|
||||
} else
|
||||
@@ -12793,6 +12881,7 @@ async function executePaperclipNativeSessionAttempt(
|
||||
? input.runnerExecutionTarget.sandboxLeaseAcquisition?.providerLeaseId : undefined,
|
||||
providerLeaseId: sandboxProviderLeaseId(input.runnerExecutionTarget) ?? undefined,
|
||||
sandboxLeaseDb: input.db,
|
||||
sandboxRunner: warmSandboxRunner(input.runnerExecutionTarget),
|
||||
runId: input.execution.binding.runId,
|
||||
issueId: input.execution.binding.issueId,
|
||||
instructionWorkingCopy: input.instructionWorkingCopy?.checkpointWarm ? undefined : input.instructionWorkingCopy,
|
||||
|
||||
@@ -6,7 +6,7 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
REMOTE_RECOVERY_MARKER_READ_SCRIPT, REMOTE_RECOVERY_PROCESS_CHECK_SCRIPT, REMOTE_RUNNER_EXIT_EVIDENCE_MAX_CHARS,
|
||||
REMOTE_RUNNER_EXIT_EVIDENCE_SCRIPT, RemoteRunnerRecoveryError, boundRemoteRunnerExitEvidence, describeExitedRemoteRunnerReason,
|
||||
readRemoteRunnerRecoveryDiagnostic, readRemoteRunnerRecoveryError,
|
||||
readRemoteRunnerRecoveryDiagnostic, readRemoteRunnerRecoveryError, remoteRecoveryProbeReason,
|
||||
} from "./remote-runner-recovery-diagnostics.js";
|
||||
|
||||
function shellExit(script: string, args: string[]) {
|
||||
@@ -35,7 +35,7 @@ describe("remote recovery diagnostic shell receipts", () => {
|
||||
it.each([
|
||||
{ fingerprint: "linux:abcd-1234:100", code: 45 },
|
||||
{ fingerprint: "linux:abcd-1234:101", code: 47 },
|
||||
{ fingerprint: "", code: 44 },
|
||||
{ fingerprint: "", code: 48 },
|
||||
])("requires the saved generation before accepting a zombie receipt (%j)", async ({ fingerprint, code }) => {
|
||||
const root = await mkdtemp(join(tmpdir(), "remote-probe-zombie-"));
|
||||
const marker = join(root, "marker");
|
||||
@@ -53,6 +53,30 @@ describe("remote recovery diagnostic shell receipts", () => {
|
||||
} finally { await rm(root, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ cmdline: ["paperclip-runnerd", "--runner-id", "runner"], code: 0 },
|
||||
{ cmdline: ["paperclip-runnerd", "--state-dir", "/state"], code: 48 },
|
||||
{ cmdline: [""], code: 48 },
|
||||
])("reports a live process without its runner id apart from a changed marker (%j)", async ({ cmdline, code }) => {
|
||||
const root = await mkdtemp(join(tmpdir(), "remote-probe-runner-id-"));
|
||||
const marker = join(root, "marker");
|
||||
try {
|
||||
await writeFile(marker, `nonce\n${process.pid}\n2026-11-16T00:28:42.758Z\nrunner\n`);
|
||||
await writeFile(join(root, "cmdline"), cmdline.join("\0"));
|
||||
await writeFile(join(root, "stat"), `${process.pid} (runnerd) ${["S", ...Array(18).fill("0"), 100].join(" ")}\n`);
|
||||
await writeFile(join(root, "boot_id"), "abcd-1234\n");
|
||||
const script = REMOTE_RECOVERY_PROCESS_CHECK_SCRIPT
|
||||
.replaceAll('"/proc/" + pid + "/cmdline"', JSON.stringify(join(root, "cmdline")))
|
||||
.replaceAll('"/proc/" + pid + "/stat"', JSON.stringify(join(root, "stat")))
|
||||
.replaceAll('"/proc/sys/kernel/random/boot_id"', JSON.stringify(join(root, "boot_id")));
|
||||
expect(shellExit(script, [marker, "nonce", "runner", String(process.pid), "linux:abcd-1234:100"])).toBe(code);
|
||||
expect(remoteRecoveryProbeReason("process_verification", 48, false)).toBe("process_runner_id_missing");
|
||||
await writeFile(marker, `nonce\n${process.pid}\n2026-11-16T00:28:42.758Z\nother-runner\n`);
|
||||
expect(shellExit(script, [marker, "nonce", "runner", String(process.pid), "linux:abcd-1234:100"])).toBe(44);
|
||||
expect(remoteRecoveryProbeReason("process_verification", 44, false)).toBe("process_identity_changed");
|
||||
} finally { await rm(root, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
it("distinguishes missing, unsafe and valid marker reads without exposing their contents", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "remote-recovery-read-"));
|
||||
const marker = join(root, "marker");
|
||||
|
||||
@@ -3,7 +3,7 @@ export const REMOTE_RUNNER_RECOVERY_ERROR_CODE = "runner_remote_process_identity
|
||||
const stages = ["runner_state", "identity_marker", "process_verification"] as const;
|
||||
const reasons = [
|
||||
"marker_missing", "marker_unsafe", "marker_read_failed", "marker_invalid",
|
||||
"fingerprint_missing", "process_not_running", "process_identity_changed",
|
||||
"fingerprint_missing", "process_not_running", "process_identity_changed", "process_runner_id_missing",
|
||||
"fingerprint_unavailable", "process_generation_changed", "probe_timeout",
|
||||
"probe_transport_failed", "probe_failed",
|
||||
"state_read_failed", "state_invalid",
|
||||
@@ -219,7 +219,7 @@ catch (error) {
|
||||
if (expectedGeneration) verifyGeneration();
|
||||
if (!args.includes("--runner-id") || !args.includes(runnerId)) {
|
||||
requireLiveProcess();
|
||||
process.exit(44);
|
||||
process.exit(48);
|
||||
}
|
||||
' "$pid" "$expected_runner_id"` + ' "${5:-}"',
|
||||
].join("; ");
|
||||
@@ -238,6 +238,7 @@ export function remoteRecoveryProbeReason(stage: RemoteRunnerRecoveryDiagnostic[
|
||||
if (exitCode === 45) return "process_not_running";
|
||||
if (exitCode === 46) return "fingerprint_unavailable";
|
||||
if (exitCode === 47) return "process_generation_changed";
|
||||
if (exitCode === 48) return "process_runner_id_missing";
|
||||
}
|
||||
return "probe_failed";
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import { afterEach, expect, it } from "vitest";
|
||||
import { activityLog, heartbeatRuns } from "@paperclipai/db";
|
||||
import { describeEmbeddedPostgres, nativeRestartFixture } from "../../__tests__/helpers/native-restart.js";
|
||||
import { NativePredecessorRetirementUnprovenError } from "./predecessor-retirement.js";
|
||||
import { retireSandboxRunnerPortHolders } from "./sandbox-runner-port-holders.js";
|
||||
import { retireSandboxRunnerPortHolders, sandboxSessionRunnerExited } from "./sandbox-runner-port-holders.js";
|
||||
|
||||
const HOLDER_SCRIPT = 'require("node:net").createServer().listen(Number(process.argv[1]), "127.0.0.1", () => process.stdout.write("ready\\n"));';
|
||||
|
||||
@@ -121,6 +121,28 @@ describeEmbeddedPostgres("a sandbox Runner port held by another session's Runner
|
||||
expect(await bind(port)).toBe("EADDRINUSE");
|
||||
});
|
||||
|
||||
it("stops only the named session's finished Runner and then proves it exited", async () => {
|
||||
const owner = await environment.seedRun("PORT-HOLDER-ONLY-OWNER");
|
||||
const other = await environment.seedRun("PORT-HOLDER-ONLY-OTHER", owner.db);
|
||||
await owner.db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, owner.runId));
|
||||
await owner.db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, other.runId));
|
||||
const base = join(environment.current.runtimeRoot, "sandbox-only");
|
||||
const runtimeRoot = join(base, ".paperclip-runtime", "paperclip-runner");
|
||||
const own = await startHolder({ runtimeRoot, session: "e".repeat(64), runId: owner.runId, port: await freePort() });
|
||||
const neighbour = await startHolder({ runtimeRoot, session: "f".repeat(64), runId: other.runId, port: await freePort() });
|
||||
const exitedNow = () => sandboxSessionRunnerExited({ runner: confinedRunner(base) as never, runtimeRoot, sessionDirectory: "e".repeat(64) });
|
||||
expect(await exitedNow()).toBe(false);
|
||||
await expect(retireSandboxRunnerPortHolders({ db: owner.db, companyId: environment.current.companyId,
|
||||
agentId: environment.current.agentId, runId: owner.runId, runner: confinedRunner(base) as never, runtimeRoot,
|
||||
ownSessionRoot: "", providerLeaseId: "sandbox-1", only: { sessionDirectory: "e".repeat(64), runId: owner.runId },
|
||||
retireInProcess: async () => false, waitMs: 3_000, pollMs: 100 })).resolves.toEqual([owner.runId]);
|
||||
expect(await exited(own)).toBe(true);
|
||||
expect(await exitedNow()).toBe(true);
|
||||
expect(neighbour.exitCode).toBeNull();
|
||||
expect(await sandboxSessionRunnerExited({ runner: confinedRunner(base) as never, runtimeRoot, sessionDirectory: "f".repeat(64) })).toBe(false);
|
||||
expect(await sandboxSessionRunnerExited({ runner: confinedRunner(base) as never, runtimeRoot, sessionDirectory: "0".repeat(64) })).toBe(false);
|
||||
});
|
||||
|
||||
it("ignores this run's own session, moved-aside roots and holders that already exited", async () => {
|
||||
const current = await environment.seedRun("PORT-HOLDER-OWN");
|
||||
const base = join(environment.current.runtimeRoot, "sandbox-own");
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { inspectSandboxSessionRunner, SANDBOX_SESSION_RUNNER_INSPECT_SCRIPT } from "./sandbox-runner-port-holders.js";
|
||||
|
||||
const localRunner = (script: string) => ({ execute: async (request: { command: string; args?: string[] }) => {
|
||||
const args = [...request.args ?? []];
|
||||
args[3] = script;
|
||||
const result = spawnSync(request.command, args, { encoding: "utf8", timeout: 10_000 });
|
||||
return { exitCode: result.status, timedOut: result.error !== undefined, stdout: result.stdout ?? "", stderr: result.stderr ?? "" };
|
||||
} });
|
||||
|
||||
async function fakeProcess(proc: string, pid: number, argv: string[], state = "S") {
|
||||
await mkdir(join(proc, String(pid)), { recursive: true });
|
||||
await writeFile(join(proc, String(pid), "cmdline"), `${argv.join("\0")}\0`);
|
||||
await writeFile(join(proc, String(pid), "stat"), `${pid} (${argv[0]?.split("/").pop()}) ${state} 1 ${pid} ${pid}\n`);
|
||||
}
|
||||
|
||||
describe("sandbox session Runner inspection", () => {
|
||||
it("reports the durable state, the marker pid and each process carrying the runner id, never the nonce or command lines", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "runner-inspect-"));
|
||||
const proc = join(root, "proc");
|
||||
const state = join(root, "runner");
|
||||
try {
|
||||
await mkdir(join(proc, "self"), { recursive: true });
|
||||
await writeFile(join(proc, "self", "cmdline"), "node\0");
|
||||
await mkdir(state, { recursive: true });
|
||||
await writeFile(join(state, "runner-process.identity"), "private-nonce\n522\n2026-11-16T00:47:54.000Z\nrunner-1\nlinux:abcd:100\n");
|
||||
await writeFile(join(state, "runner-state.json"), JSON.stringify({ runnerInstanceId: "runner-1", runId: "run-1",
|
||||
normalizedSessionId: "session-1", lifecycle: "suspended", outbox: [], pendingTerminalDelivery: null, secret: "private-token" }));
|
||||
await fakeProcess(proc, 522, ["/opt/bin/paperclip-runnerd", "--runner-id", "runner-1", "--token", "private-token"]);
|
||||
await fakeProcess(proc, 600, ["/opt/bin/paperclip-runnerd", "--runner-id", "runner-2"], "Z");
|
||||
await fakeProcess(proc, 700, ["sleep", "100"]);
|
||||
const script = SANDBOX_SESSION_RUNNER_INSPECT_SCRIPT.replaceAll("'/proc", `'${proc}`);
|
||||
const inspect = () => inspectSandboxSessionRunner({ runner: localRunner(script) as never, stateDirectory: state });
|
||||
const inspection = await inspect();
|
||||
expect(inspection).toEqual({
|
||||
state: { lifecycle: "suspended", runId: "run-1", normalizedSessionId: "session-1", runnerInstanceId: "runner-1", settled: true },
|
||||
markerPid: 522, markerRunnerIdMatchesState: true, procfs: true, unreadableProcesses: 0,
|
||||
processes: [{ pid: 522, state: "S", carriesRunnerId: true }, { pid: 600, state: "Z", carriesRunnerId: false }],
|
||||
});
|
||||
expect(JSON.stringify(inspection)).not.toMatch(/private/);
|
||||
await rm(join(proc, "522"), { recursive: true });
|
||||
await writeFile(join(state, "runner-state.json"), JSON.stringify({ runnerInstanceId: "runner-1", runId: "run-1",
|
||||
normalizedSessionId: "session-1", lifecycle: "suspended", outbox: [{ seq: 1 }], pendingTerminalDelivery: null }));
|
||||
expect(await inspect()).toMatchObject({ state: { settled: false }, unreadableProcesses: 0,
|
||||
processes: [{ pid: 600, carriesRunnerId: false }] });
|
||||
await mkdir(join(proc, "800", "cmdline"), { recursive: true });
|
||||
expect(await inspect()).toMatchObject({ procfs: true, unreadableProcesses: 1, processes: [{ pid: 600 }] });
|
||||
} finally { await rm(root, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
it("fails closed without a process table and never reads state through a symlink", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "runner-inspect-noproc-"));
|
||||
const state = join(root, "runner");
|
||||
try {
|
||||
await mkdir(state, { recursive: true });
|
||||
await writeFile(join(root, "elsewhere.json"), JSON.stringify({ lifecycle: "suspended", runnerInstanceId: "runner-1" }));
|
||||
await symlink(join(root, "elsewhere.json"), join(state, "runner-state.json"));
|
||||
const script = SANDBOX_SESSION_RUNNER_INSPECT_SCRIPT.replaceAll("'/proc", `'${join(root, "missing-proc")}`);
|
||||
expect(await inspectSandboxSessionRunner({ runner: localRunner(script) as never, stateDirectory: state })).toEqual({
|
||||
state: null, markerPid: null, markerRunnerIdMatchesState: false, procfs: false, unreadableProcesses: 0, processes: [] });
|
||||
} finally { await rm(root, { recursive: true, force: true }); }
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { posix } from "node:path";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { heartbeatRuns, type Db } from "@paperclipai/db";
|
||||
import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
|
||||
@@ -68,22 +69,102 @@ export function parseSandboxRunnerHolders(stdout: string): SandboxRunnerHolder[]
|
||||
|
||||
type HolderProbe = "alive" | "gone" | "unproven";
|
||||
|
||||
async function probeHolder(runner: CommandManagedRuntimeRunner, holder: SandboxRunnerHolder,
|
||||
signal?: "TERM" | "KILL"): Promise<HolderProbe> {
|
||||
async function checkHolder(runner: CommandManagedRuntimeRunner, holder: SandboxRunnerHolder, label: string,
|
||||
signal?: "TERM" | "KILL"): Promise<number | null> {
|
||||
const result = await runner.execute({
|
||||
command: "sh",
|
||||
args: ["-c", REMOTE_RECOVERY_PROCESS_CHECK_SCRIPT + (signal ? '; kill -"$6" "$pid"' : ""),
|
||||
"paperclip-runner-port-holder-check", holder.identityPath, holder.nonce, holder.runnerInstanceId, String(holder.pid),
|
||||
label, holder.identityPath, holder.nonce, holder.runnerInstanceId, String(holder.pid),
|
||||
holder.processStartFingerprint ?? "", ...(signal ? [signal] : [])],
|
||||
bypassSession: true,
|
||||
timeoutMs: 10_000,
|
||||
}).catch(() => null);
|
||||
if (!result || result.timedOut) return "unproven";
|
||||
if (result.exitCode === 0) return "alive";
|
||||
if (result.exitCode === 45 || result.exitCode === 47) return "gone";
|
||||
return !result || result.timedOut ? null : result.exitCode;
|
||||
}
|
||||
|
||||
async function probeHolder(runner: CommandManagedRuntimeRunner, holder: SandboxRunnerHolder,
|
||||
signal?: "TERM" | "KILL"): Promise<HolderProbe> {
|
||||
const exitCode = await checkHolder(runner, holder, "paperclip-runner-port-holder-check", signal);
|
||||
if (exitCode === 0) return "alive";
|
||||
if (exitCode === 45 || exitCode === 47) return "gone";
|
||||
return "unproven";
|
||||
}
|
||||
|
||||
async function listSandboxRunnerHolders(runner: CommandManagedRuntimeRunner, runtimeRoot: string, ownSessionRoot: string) {
|
||||
const listed = await runner.execute({
|
||||
command: "sh",
|
||||
args: ["-c", SANDBOX_RUNNER_HOLDER_LIST_SCRIPT, "paperclip-runner-port-holders", runtimeRoot, ownSessionRoot],
|
||||
bypassSession: true,
|
||||
timeoutMs: 15_000,
|
||||
}).catch(() => null);
|
||||
return { listed, holders: !listed || listed.exitCode !== 0 || listed.timedOut ? null : parseSandboxRunnerHolders(listed.stdout) };
|
||||
}
|
||||
|
||||
function holderSessionDirectory(holder: SandboxRunnerHolder): string {
|
||||
return posix.basename(posix.dirname(posix.dirname(holder.identityPath)));
|
||||
}
|
||||
|
||||
export async function sandboxSessionRunnerExited(input: {
|
||||
runner: CommandManagedRuntimeRunner;
|
||||
runtimeRoot: string;
|
||||
sessionDirectory: string;
|
||||
}): Promise<boolean> {
|
||||
const { holders } = await listSandboxRunnerHolders(input.runner, input.runtimeRoot, "");
|
||||
const holder = holders?.find(candidate => holderSessionDirectory(candidate) === input.sessionDirectory);
|
||||
return holder !== undefined && await checkHolder(input.runner, holder, "paperclip-runner-exit-check") === 45;
|
||||
}
|
||||
|
||||
export const SANDBOX_SESSION_RUNNER_INSPECT_SCRIPT = [
|
||||
"const fs=require('fs'),path=require('path');",
|
||||
"const dir=process.argv[1];",
|
||||
"const readSafe=f=>{try{if(fs.lstatSync(f).isSymbolicLink())return null;return fs.readFileSync(f,'utf8')}catch{return null}};",
|
||||
"let state=null;try{const v=JSON.parse(readSafe(path.join(dir,'runner-state.json')));if(v&&typeof v==='object'&&!Array.isArray(v))state=v}catch{}",
|
||||
"const marker=(readSafe(path.join(dir,'runner-process.identity'))||'').split(String.fromCharCode(10));",
|
||||
"const runnerId=marker[3]||null,markerPid=/^[1-9][0-9]*$/.test(marker[1]||'')?Number(marker[1]):null;",
|
||||
"const str=v=>typeof v==='string'?v:null;",
|
||||
"const out={state:state&&{lifecycle:str(state.lifecycle),runId:str(state.runId),normalizedSessionId:str(state.normalizedSessionId),",
|
||||
"runnerInstanceId:str(state.runnerInstanceId),settled:Array.isArray(state.outbox)&&state.outbox.length===0&&state.pendingTerminalDelivery==null",
|
||||
"&&state.pendingProviderCleanup==null&&state.warmTransition==null},markerPid,",
|
||||
"markerRunnerIdMatchesState:runnerId!==null&&state!==null&&state.runnerInstanceId===runnerId,procfs:false,unreadableProcesses:0,processes:[]};",
|
||||
"let entries=null;try{entries=fs.readdirSync('/proc')}catch{}",
|
||||
"if(entries&&fs.existsSync('/proc/self/cmdline')){out.procfs=true;for(const d of entries){",
|
||||
"if(String(Number(d))!==d||Number(d)===process.pid||Number(d)===process.ppid)continue;",
|
||||
"let a;try{a=fs.readFileSync('/proc/'+d+'/cmdline','utf8').split(String.fromCharCode(0))}catch(e){if(e.code!=='ENOENT'&&e.code!=='ESRCH')out.unreadableProcesses++;continue}",
|
||||
"const carries=runnerId!==null&&a.includes('--runner-id')&&a.includes(runnerId);",
|
||||
"if(!carries&&(a[0]||'').split('/').pop()!=='paperclip-runnerd')continue;",
|
||||
"let st=null;try{const s=fs.readFileSync('/proc/'+d+'/stat','utf8');st=s.slice(s.lastIndexOf(')')+2).split(' ')[0]||null}catch{}",
|
||||
"out.processes.push({pid:Number(d),state:st,carriesRunnerId:carries})}}",
|
||||
"out.processes.sort((x,y)=>x.pid-y.pid);process.stdout.write(JSON.stringify(out));",
|
||||
].join("");
|
||||
|
||||
export type SandboxSessionRunnerInspection = {
|
||||
state: { lifecycle: string | null; runId: string | null; normalizedSessionId: string | null;
|
||||
runnerInstanceId: string | null; settled: boolean } | null;
|
||||
markerPid: number | null;
|
||||
markerRunnerIdMatchesState: boolean;
|
||||
procfs: boolean;
|
||||
unreadableProcesses: number;
|
||||
processes: Array<{ pid: number; state: string | null; carriesRunnerId: boolean }>;
|
||||
};
|
||||
|
||||
export async function inspectSandboxSessionRunner(input: {
|
||||
runner: CommandManagedRuntimeRunner;
|
||||
stateDirectory: string;
|
||||
}): Promise<SandboxSessionRunnerInspection | null> {
|
||||
const result = await input.runner.execute({
|
||||
command: "sh",
|
||||
args: ["-c", 'exec node -e "$1" "$2"', "paperclip-runner-session-inspect", SANDBOX_SESSION_RUNNER_INSPECT_SCRIPT,
|
||||
input.stateDirectory],
|
||||
bypassSession: true,
|
||||
timeoutMs: 5_000,
|
||||
}).catch(() => null);
|
||||
if (!result || result.timedOut || result.exitCode !== 0) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(result.stdout.trim()) as SandboxSessionRunnerInspection;
|
||||
return parsed && typeof parsed === "object" && Array.isArray(parsed.processes) ? parsed : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
async function waitUntilGone(runner: CommandManagedRuntimeRunner, holder: SandboxRunnerHolder, waitMs: number, pollMs: number) {
|
||||
const deadline = Date.now() + waitMs;
|
||||
for (;;) {
|
||||
@@ -104,24 +185,21 @@ export async function retireSandboxRunnerPortHolders(input: {
|
||||
ownSessionRoot: string;
|
||||
providerLeaseId: string | null;
|
||||
adoptedRunId?: string | null;
|
||||
only?: { sessionDirectory: string; runId: string };
|
||||
retireInProcess: (holderRunId: string) => Promise<boolean>;
|
||||
onLog?: (stream: "stdout" | "stderr", chunk: string) => Promise<void>;
|
||||
waitMs?: number;
|
||||
pollMs?: number;
|
||||
}): Promise<string[]> {
|
||||
const listed = await input.runner.execute({
|
||||
command: "sh",
|
||||
args: ["-c", SANDBOX_RUNNER_HOLDER_LIST_SCRIPT, "paperclip-runner-port-holders", input.runtimeRoot, input.ownSessionRoot],
|
||||
bypassSession: true,
|
||||
timeoutMs: 15_000,
|
||||
}).catch(() => null);
|
||||
if (!listed || listed.exitCode !== 0 || listed.timedOut) {
|
||||
const { listed, holders } = await listSandboxRunnerHolders(input.runner, input.runtimeRoot, input.ownSessionRoot);
|
||||
if (!holders) {
|
||||
throw new NativePredecessorRetirementUnprovenError(null, input.providerLeaseId,
|
||||
new Error(`runner_port_holder_inventory_unavailable: exit=${listed?.exitCode ?? "none"} timedOut=${listed?.timedOut ?? false}`));
|
||||
}
|
||||
const retired: string[] = [];
|
||||
for (const holder of parseSandboxRunnerHolders(listed.stdout)) {
|
||||
if (holder.runId === input.runId || (holder.runId !== null && holder.runId === input.adoptedRunId)) continue;
|
||||
for (const holder of holders) {
|
||||
if (input.only ? holderSessionDirectory(holder) !== input.only.sessionDirectory || holder.runId !== input.only.runId
|
||||
: holder.runId === input.runId || (holder.runId !== null && holder.runId === input.adoptedRunId)) continue;
|
||||
const initial = await probeHolder(input.runner, holder);
|
||||
if (initial === "gone") continue;
|
||||
const unproven = (reason: string) => new NativePredecessorRetirementUnprovenError(holder.runId, input.providerLeaseId,
|
||||
|
||||
@@ -199,8 +199,14 @@ also grades "no leaked sandboxes / clean warm shutdown" (`warm-shutdown.ts`). It
|
||||
the wave when the environment delete stayed blocked, when a wave sandbox is still
|
||||
running after cleanup, or when the server log shows a warm session that did not close
|
||||
on environment delete or controller shutdown. Idle closes that needed a forced Runner
|
||||
stop, or whose sandbox was already destroyed, are counted but do not fail. The result
|
||||
is in `<wave>/warm-shutdown.json` and in the wave's `SUMMARY.md`.
|
||||
stop, or whose sandbox was already destroyed, are counted but do not fail. Both counts
|
||||
are distinct (run, reason) failures, not log lines: the harness's environment-delete
|
||||
retries re-log the same failed close every few seconds (one session logged 27 times in
|
||||
w-20261116T001158-s7106). Each failure keeps its line count. On a Daytona warm wave, the
|
||||
first idle-close failure in the server output triggers one sandbox capture
|
||||
(`daytona-runner/idle-close-failure-<run>/`: processes, Runner state and logs), listed
|
||||
under `sandboxCaptures`. The result is in `<wave>/warm-shutdown.json` and in the wave's
|
||||
`SUMMARY.md`.
|
||||
|
||||
## Hosted mode (`--hosted-base-url`, `--hosted-allow`)
|
||||
|
||||
@@ -411,7 +417,7 @@ part of U3 is checked only in waves run with this harness.
|
||||
temporary instance is deleted.
|
||||
- Faults are serialized; each one hits every task running at that moment.
|
||||
- A `todo` or `in_progress` task with no live run and no named wait is not a rest. The observer keeps watching it until it resumes or passes the R5 stall limit.
|
||||
- R5 also fails a run that stays `running` with no live evidence (no new run event, `lastUsefulActionAt` or `execution.lastConfirmedActivityAt`, and no start) for more than 3 minutes after the server is ready. A `running` status alone is not proof of life. A quiet run is still live while a tool it started has not ended (for example a 4-minute `bench.sh`) or while its recorded local runner process still runs with the same PID and start time. While a provider turn is active and no tool runs, one model request is outstanding: R5 allows up to 10 minutes of quiet before it counts a dead run. A slow OpenRouter request took 303.6 s in w-20261115T044649-s7106/t028, and common provider clients time out a request at 10 minutes.
|
||||
- R5 also fails a run that stays `running` with no live evidence (no new run event, `lastUsefulActionAt` or `execution.lastConfirmedActivityAt`, and no start) for more than 3 minutes after the server is ready. A `running` status alone is not proof of life. A quiet run is still live while a tool it started has not ended (for example a 4-minute `bench.sh`) or while its recorded local runner process still runs with the same PID and start time. While a provider turn is active and no tool runs, one model request is outstanding: R5 allows up to 10 minutes of quiet before it counts a dead run. A slow OpenRouter request took 303.6 s in w-20261115T044649-s7106/t028, and common provider clients time out a request at 10 minutes. A run with no run event yet (`preparing`: its events read back empty) is still acquiring or preparing its environment, because "run started" is written only after that. R5 allows it 10 minutes too: in w-20261116T001158-s7106/t010 a Daytona restore of an archived sandbox took 251 s, including one 90 s plugin call timeout, and the Daytona provider bounds each start or restore at 5 minutes by default, so 10 minutes covers one timed-out restore and its retry. U1 uses the same bound (`PREPARATION_LIMIT_MS`) before it stops counting a preparing run as the task's owner.
|
||||
- The wave fingerprints the checkout and `packages/paperclip-runner/dist` at start and after every fault. A build, install or branch switch during a wave would make later restarts run different code, so it fails the wave as a harness error (`worktree_changed_mid_wave`). The baseline is taken after the harness's own setup (preflight rebuilds provider entrypoints) and covers the tracked diff, untracked file contents, the runner `dist` and the runnerd binary. Build before the wave, never during it.
|
||||
- `faults.json` and `task-faults.json` (each task's launch time and the faults that crossed it) are written after every fault, so `--replay` of a task in an interrupted or wedged wave, or a storm task, re-fires the faults that crossed it at the same offsets.
|
||||
- A fault that fails to complete fails the wave as a harness error (exit 2), even when recovery brings the server back.
|
||||
|
||||
@@ -21,9 +21,9 @@ export function daytonaCleanupLine(sweep: DaytonaSweepResult, cleanup: WaveClean
|
||||
}
|
||||
|
||||
export async function finishDaytonaCleanup(input: { sweeper: Pick<DaytonaWaveSweeper, "sweep" | "cleanUp">; sweep: DaytonaSweepResult | null; waveDir: string;
|
||||
timeline: { add(kind: string, data: Record<string, unknown>): void }; log?: (line: string) => void }): Promise<DaytonaCleanupOutcome> {
|
||||
timeline: { add(kind: string, data: Record<string, unknown>): void }; log?: (line: string) => void; beforeSandboxDelete?: () => Promise<void> }): Promise<DaytonaCleanupOutcome> {
|
||||
const sweep = input.sweep ?? await input.sweeper.sweep(0);
|
||||
const cleanup = await input.sweeper.cleanUp();
|
||||
const cleanup = await input.sweeper.cleanUp(undefined, undefined, input.beforeSandboxDelete);
|
||||
input.timeline.add("daytona_cleanup", cleanup);
|
||||
(input.log ?? console.info)(daytonaCleanupLine(sweep, cleanup));
|
||||
if (cleanup.environmentDeleteBlocked) input.timeline.add("daytona_environment_delete_blocked", { detail: cleanup.environmentDeleteBlocked });
|
||||
|
||||
@@ -61,6 +61,22 @@ describe("cleanup through Paperclip", () => {
|
||||
expect(rows.find(row => row.id === "other-env")!.state).toBe("archived");
|
||||
});
|
||||
|
||||
it("waits for a capture the environment delete triggered before it deletes any wave sandbox", async () => {
|
||||
const rows = waveRows(["started"]);
|
||||
const order: string[] = [];
|
||||
const { client, removeSandbox } = deletingDaytona(rows);
|
||||
const sweeper = new DaytonaWaveSweeper({ apiKey: "unused", companyId: COMPANY, environmentId: ENVIRONMENT,
|
||||
api: { delete: async () => { order.push("environment delete"); } } as never,
|
||||
removeSandbox: async id => { order.push(`delete ${id}`); await removeSandbox(id); } });
|
||||
(sweeper as unknown as { client: unknown }).client = client;
|
||||
const result = await sweeper.cleanUp(0, 1_000, async () => { await new Promise(resolve => setTimeout(resolve, 20)); order.push("capture"); });
|
||||
expect(order).toEqual(["environment delete", "capture", "delete started"]);
|
||||
expect(result.errors).toEqual([]);
|
||||
const failing = new DaytonaWaveSweeper({ apiKey: "unused", companyId: COMPANY, environmentId: ENVIRONMENT, api: { delete: async () => undefined } as never });
|
||||
(failing as unknown as { client: unknown }).client = readOnlyDaytona(listing);
|
||||
expect((await failing.cleanUp(0, 1_000, async () => { throw new Error("probe failed"); })).errors).toEqual(["before sandbox delete: probe failed"]);
|
||||
});
|
||||
|
||||
it("fails cleanup when a wave sandbox survives deletion, and never deletes a fleet snapshot even with the wave's labels", async () => {
|
||||
const rows = [...waveRows(["archived"]), ...waveRows(["fleet"], { snapshot: "fleet-sbx-9", state: "archived" })];
|
||||
const { client, removeSandbox, removed } = deletingDaytona(rows);
|
||||
|
||||
@@ -215,7 +215,7 @@ export class DaytonaWaveSweeper {
|
||||
}
|
||||
}
|
||||
|
||||
async cleanUp(settleMs = 90_000, deleteWindowMs = R6_SETTLE_MS): Promise<WaveCleanup> {
|
||||
async cleanUp(settleMs = 90_000, deleteWindowMs = R6_SETTLE_MS, beforeSandboxDelete?: () => Promise<void>): Promise<WaveCleanup> {
|
||||
const errors: string[] = [];
|
||||
let environmentDeleted = false;
|
||||
let environmentDeleteBlocked: string | null = null;
|
||||
@@ -229,6 +229,7 @@ export class DaytonaWaveSweeper {
|
||||
if (/returned 409\b/.test(message)) environmentDeleteBlocked = message;
|
||||
else errors.push(`environment delete: ${message}`);
|
||||
}
|
||||
await beforeSandboxDelete?.().catch(error => { errors.push(`before sandbox delete: ${error instanceof Error ? error.message : String(error)}`); });
|
||||
let remainingSandboxes: string[] = [];
|
||||
let archivedSandboxes: string[] = [];
|
||||
// Provider teardown is asynchronous; give it a bounded settle before reporting.
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
[18:30:55] [33mWARN[39m: [36midle warm native session close failed[39m [90m{"runId":"300f0d61-548b-4630-8f6a-f79292ed9d24","issueId":"6577ff15-9c90-4b0c-812c-ee1f6e2226b0","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"287cbe35-0b93-46f4-89f4-5a0430592870","closeFailure":"runner_remote_process_identity_unavailable: runner_remote_process_identity_unavailable [process_verification/process_identity_changed]","closeAttempt":1}[39m
|
||||
[18:31:00] [33mWARN[39m: [36midle warm native session close failed[39m [90m{"runId":"300f0d61-548b-4630-8f6a-f79292ed9d24","issueId":"6577ff15-9c90-4b0c-812c-ee1f6e2226b0","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"287cbe35-0b93-46f4-89f4-5a0430592870","closeFailure":"runner_remote_process_identity_unavailable: runner_remote_process_identity_unavailable [process_verification/process_identity_changed]","closeAttempt":2}[39m
|
||||
[18:31:05] [33mWARN[39m: [36midle warm native session close failed[39m [90m{"runId":"300f0d61-548b-4630-8f6a-f79292ed9d24","issueId":"6577ff15-9c90-4b0c-812c-ee1f6e2226b0","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"287cbe35-0b93-46f4-89f4-5a0430592870","closeFailure":"runner_remote_process_identity_unavailable: runner_remote_process_identity_unavailable [process_verification/process_identity_changed]","closeAttempt":3}[39m
|
||||
[18:31:10] [33mWARN[39m: [36midle warm native session close failed[39m [90m{"runId":"300f0d61-548b-4630-8f6a-f79292ed9d24","issueId":"6577ff15-9c90-4b0c-812c-ee1f6e2226b0","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"287cbe35-0b93-46f4-89f4-5a0430592870","closeFailure":"runner_remote_process_identity_unavailable: runner_remote_process_identity_unavailable [process_verification/process_identity_changed]","closeAttempt":4}[39m
|
||||
[18:32:50] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"controller restart","failures":[{"runId":"300f0d61-548b-4630-8f6a-f79292ed9d24","issueId":"6577ff15-9c90-4b0c-812c-ee1f6e2226b0","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"287cbe35-0b93-46f4-89f4-5a0430592870","reason":"close failed: runner_remote_process_identity_unavailable: runner_remote_process_identity_unavailable [process_verification/process_identity_changed]"}]}[39m
|
||||
[18:32:50] [33mWARN[39m: [36midle native session cleanup failed before controller shutdown[39m [90m{"idleSessions":{"closed":0,"busy":0,"failed":1,"failures":[{"runId":"300f0d61-548b-4630-8f6a-f79292ed9d24","issueId":"6577ff15-9c90-4b0c-812c-ee1f6e2226b0","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"287cbe35-0b93-46f4-89f4-5a0430592870","reason":"close failed: runner_remote_process_identity_unavailable: runner_remote_process_identity_unavailable [process_verification/process_identity_changed]"}]}}[39m
|
||||
[19:11:36] [33mWARN[39m: [36midle warm native session close failed[39m [90m{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","closeFailure":"native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}","closeAttempt":1}[39m
|
||||
[19:12:13] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:12:14] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:12:16] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:12:19] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:12:22] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:12:25] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:12:28] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:12:31] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:12:34] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:12:40] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:12:43] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:12:46] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:12:49] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:12:52] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:12:55] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:12:58] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:13:01] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:13:04] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:13:12] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:13:15] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:13:18] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:13:21] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:13:24] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:13:27] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:13:30] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:13:33] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
[19:13:36] [33mWARN[39m: [36midle warm native sessions did not close[39m [90m{"reason":"environment deleted","failures":[{"runId":"70d909cc-8b04-40ae-a0bf-0846df140cf0","issueId":"0605dbde-cd34-4728-bc68-3c1fe9ca4c06","environmentId":"d729f12b-4d52-4e10-8cae-e03bdf73b2a3","providerLeaseId":"2f139bcc-8503-4722-8943-0defefeecbab","reason":"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint {\"runnerSuspended\":false,\"runnerRetained\":true,\"providerDrained\":true,\"suspensionState\":{\"commandStatus\":\"failed\",\"runnerLifecycle\":\"ready\",\"runnerIdentityMatches\":true},\"semanticTools\":{\"persistenceFailed\":false,\"failures\":[],\"pending\":[],\"deliveries\":[]},\"finalProviderState\":null,\"timings\":{\"exitProbeMs\":0,\"stopMs\":0,\"drainMs\":225,\"suspendQueuedAfterMs\":225,\"proofReadMs\":4290,\"barrierExitProbeMs\":0,\"suspendMs\":5239,\"retainProbeMs\":0,\"releaseMs\":0,\"retireMs\":0,\"checkpointMs\":591,\"totalMs\":6055},\"proofWindowEnd\":\"suspend_not_completed\"}"}]}[39m
|
||||
@@ -0,0 +1 @@
|
||||
{"source":"w-20261116T001158-s7106/t010 (CHA-14): follow-up run aedc1f6e spent 251 s in environment.acquire (Daytona restore of an archived sandbox, one 90 s plugin RPC timeout); its first run event (\"run started\") was written after acquire; the run then succeeded","runId":"aedc1f6e-3a5e-42d2-97ab-295f19e70bb8","firstRunEventAt":"2026-11-16T01:08:19.648Z","samples":[{"at":1794791045930,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"aedc1f6e-3a5e-42d2-97ab-295f19e70bb8","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"aedc1f6e-3a5e-42d2-97ab-295f19e70bb8","status":"running","createdAt":"2026-11-16T00:59:12.296Z","startedAt":"2026-11-16T01:04:05.882Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-16T01:04:05.882Z"},{"id":"91d61efb-4a8b-4ed2-87ba-f640d6065cbf","status":"succeeded","createdAt":"2026-11-16T00:26:58.075Z","startedAt":"2026-11-16T00:26:58.346Z","finishedAt":"2026-11-16T00:38:17.936Z","errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":"blocked","lastEvidenceAt":"2026-11-16T00:38:17.875Z"}]},{"at":1794791049786,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"aedc1f6e-3a5e-42d2-97ab-295f19e70bb8","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"aedc1f6e-3a5e-42d2-97ab-295f19e70bb8","status":"running","createdAt":"2026-11-16T00:59:12.296Z","startedAt":"2026-11-16T01:04:05.882Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-16T01:04:05.882Z"},{"id":"91d61efb-4a8b-4ed2-87ba-f640d6065cbf","status":"succeeded","createdAt":"2026-11-16T00:26:58.075Z","startedAt":"2026-11-16T00:26:58.346Z","finishedAt":"2026-11-16T00:38:17.936Z","errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":"blocked","lastEvidenceAt":"2026-11-16T00:38:17.875Z"}]},{"at":1794791053308,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"aedc1f6e-3a5e-42d2-97ab-295f19e70bb8","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"aedc1f6e-3a5e-42d2-97ab-295f19e70bb8","status":"running","createdAt":"2026-11-16T00:59:12.296Z","startedAt":"2026-11-16T01:04:05.882Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-16T01:04:05.882Z"},{"id":"91d61efb-4a8b-4ed2-87ba-f640d6065cbf","status":"succeeded","createdAt":"2026-11-16T00:26:58.075Z","startedAt":"2026-11-16T00:26:58.346Z","finishedAt":"2026-11-16T00:38:17.936Z","errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":"blocked","lastEvidenceAt":"2026-11-16T00:38:17.875Z"}]},{"at":1794791056820,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"aedc1f6e-3a5e-42d2-97ab-295f19e70bb8","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"aedc1f6e-3a5e-42d2-97ab-295f19e70bb8","status":"running","createdAt":"2026-11-16T00:59:12.296Z","startedAt":"2026-11-16T01:04:05.882Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-16T01:04:05.882Z"},{"id":"91d61efb-4a8b-4ed2-87ba-f640d6065cbf","status":"succeeded","createdAt":"2026-11-16T00:26:58.075Z","startedAt":"2026-11-16T00:26:58.346Z","finishedAt":"2026-11-16T00:38:17.936Z","errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":"blocked","lastEvidenceAt":"2026-11-16T00:38:17.875Z"}]},{"at":1794791060250,"reachable":true,"serverReady":true,"issueStatus":"in_progress","interruption":{"state":"working","canRetry":false,"retryWait":false,"workspaceFailure":null,"observedRunId":"aedc1f6e-3a5e-42d2-97ab-295f19e70bb8","userAction":null},"activeRecoveryAction":false,"recoveryOwner":null,"executionBlocker":false,"scheduledRetry":false,"runs":[{"id":"aedc1f6e-3a5e-42d2-97ab-295f19e70bb8","status":"running","createdAt":"2026-11-16T00:59:12.296Z","startedAt":"2026-11-16T01:04:05.882Z","finishedAt":null,"errorCode":null,"retryOfRunId":null,"wakeCommentIds":[],"livenessState":null,"lastEvidenceAt":"2026-11-16T01:04:05.882Z"},{"id":"91d61efb-4a8b-4ed2-87ba-f640d6065cbf","status":"succeeded","createdAt":"2026-11-16T00:26:58.075Z","startedAt":"2026-11-16T00:26:58.346Z","finishedAt":"2026-11-16T00:Line truncated
|
||||
@@ -8,6 +8,7 @@ import { enforcedUniversalFailures, gradeUniversal, type SlotFree, type Universa
|
||||
export const ACTIVE_RUN_STATUSES = new Set(["queued", "running", "scheduled_retry"]);
|
||||
export const STALL_LIMIT_MS = 3 * 60_000;
|
||||
export const PROVIDER_TURN_LIMIT_MS = 10 * 60_000;
|
||||
export const PREPARATION_LIMIT_MS = 10 * 60_000;
|
||||
const REST_STATUSES_WITH_WORK = new Set(["todo", "in_progress"]);
|
||||
|
||||
const ms = (iso: string | null | undefined) => (iso ? Date.parse(iso) : NaN);
|
||||
@@ -211,7 +212,7 @@ export function deadRunningRun(sample: TaskSample, readySince: number): { id: st
|
||||
if (run.status !== "running") continue;
|
||||
// Quiet is not dead while a tool is still in flight or the run's process is verifiably alive.
|
||||
if (run.toolInFlight || run.processAlive) continue;
|
||||
const limit = run.providerTurnActive ? PROVIDER_TURN_LIMIT_MS : STALL_LIMIT_MS;
|
||||
const limit = run.preparing ? PREPARATION_LIMIT_MS : run.providerTurnActive ? PROVIDER_TURN_LIMIT_MS : STALL_LIMIT_MS;
|
||||
const evidence = Math.max(ms(run.lastEvidenceAt) || 0, ms(run.startedAt) || 0, readySince);
|
||||
if (sample.at - evidence > limit) return { id: run.id, idleMs: sample.at - Math.max(ms(run.lastEvidenceAt) || 0, ms(run.startedAt) || 0) };
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ import { matrixMayLaunch, planMatrixWave } from "./journey-matrix.js";
|
||||
import { redeployWave } from "./redeploy.js";
|
||||
import { withT1CrossingCheck } from "./workloads.js";
|
||||
import { parseRecoveryStepReceipts, withRecoveryStepCheck } from "./recovery-step-faults.js";
|
||||
import { captureWaveRunnerLogs, executeInWaveSandboxes } from "./daytona-runner-logs.js";
|
||||
import { captureWaveRunnerLogs, executeInWaveSandboxes, RUNNER_LOG_CAPTURE_DEADLINE_MS } from "./daytona-runner-logs.js";
|
||||
import { isClassRFault, killedPidsFromOutput, providerKillCommand, watchLabels, withClassRCheck, type ProviderKillRecord } from "./class-r.js";
|
||||
import { TASK_FAULT_LOG, observedFaultSchedule, planWave, replayOnCurrentBuild, replayRecordFor, replayWave, type TaskFaultLog } from "./scheduler.js";
|
||||
import { chaosLifecycleOverrides, seedChaosLab } from "./seed.js";
|
||||
@@ -59,7 +59,7 @@ import { guardedRunnerOutputs, worktreeFingerprint } from "./wave-guard.js";
|
||||
import { checkCrossServer, readCrossServerEvidence } from "./multi-server.js";
|
||||
import { ReleaseSwapWave, stormRunFor } from "./release-swap-setup.js";
|
||||
import { runnerBindFaultServerEnvironment, sessionFaultServerEnvironment } from "./session-faults.js";
|
||||
import { controllerLogNames, gradeWarmShutdown, isWarmWave, warmShutdownMarkdown, type WarmShutdownCleanup } from "./warm-shutdown.js";
|
||||
import { controllerLogNames, gradeWarmShutdown, isWarmWave, waitBounded, warmShutdownMarkdown, watchFirstIdleCloseFailure, type WarmShutdownCleanup } from "./warm-shutdown.js";
|
||||
import type { FaultKind, FaultReceipt, OracleArtifacts, TriggerId, WavePlan } from "./types.js";
|
||||
|
||||
const repositoryRoot = path.resolve(import.meta.dirname, "../..");
|
||||
@@ -318,6 +318,12 @@ async function main(): Promise<number> {
|
||||
let storageSection: string | null = null;
|
||||
let warmShutdownSection: string | null = null;
|
||||
let daytonaCleanup: WarmShutdownCleanup | null = null;
|
||||
let idleCloseCapture: Promise<void> | null = null;
|
||||
const idleCloseCaptures: string[] = [];
|
||||
const waitForIdleCloseCapture = async (phase: string) => {
|
||||
const outcome = await waitBounded(() => idleCloseCapture, RUNNER_LOG_CAPTURE_DEADLINE_MS + 5_000);
|
||||
if (outcome === "timed_out") timeline.add("idle_close_failure_capture_wait_timed_out", { phase });
|
||||
};
|
||||
let harnessError: unknown;
|
||||
process.on("uncaughtException", error => {
|
||||
if (isSocketTypeOfServiceRace(error)) { timeline.add("harness_socket_race_ignored", { error: String(error) }); return; }
|
||||
@@ -461,6 +467,12 @@ async function main(): Promise<number> {
|
||||
if (sandboxEvidence) {
|
||||
runnerLogTarget = { companyId: owned.companyId, environmentId: owned.environmentId };
|
||||
if (redeployWave(plan)) supervisor.redeployEvidence = (faultId, phase) => captureRunnerLogs(`${faultId}-${phase}`);
|
||||
if (isWarmWave(plan.options)) supervisor.onServerOutput = watchFirstIdleCloseFailure(failure => {
|
||||
const label = `idle-close-failure-${(failure.runId ?? "unknown").slice(0, 8)}`;
|
||||
idleCloseCaptures.push(label);
|
||||
timeline.add("idle_close_failure_seen", { runId: failure.runId, label, line: failure.line.slice(0, 2_000) });
|
||||
idleCloseCapture = captureRunnerLogs(label).catch(error => { timeline.add("idle_close_failure_capture_failed", { label, error: String(error) }); });
|
||||
});
|
||||
// `--sandbox-watch-seconds`: capture on a clock too, for Runner exits that no fault announces (W2 re-wake).
|
||||
if (plan.options.sandboxWatchMs) faultWork.push(watchSandboxes(plan.options.sandboxWatchMs));
|
||||
}
|
||||
@@ -919,8 +931,10 @@ async function main(): Promise<number> {
|
||||
if (supervisor.serverReady) await recordWaveSpend().catch(() => undefined);
|
||||
await board?.close().catch(() => undefined);
|
||||
await closeJourneyApps();
|
||||
await waitForIdleCloseCapture("before_cleanup");
|
||||
try { if (sweeper) try {
|
||||
const outcome = await finishDaytonaCleanup({ sweeper: sweeper as DaytonaWaveSweeper, sweep: sandboxSweep, waveDir, timeline });
|
||||
const outcome = await finishDaytonaCleanup({ sweeper: sweeper as DaytonaWaveSweeper, sweep: sandboxSweep, waveDir, timeline,
|
||||
beforeSandboxDelete: () => waitForIdleCloseCapture("before_sandbox_delete") });
|
||||
sandboxSweep = outcome.sweep;
|
||||
daytonaCleanup = outcome.cleanup;
|
||||
if (outcome.failed) anyFailure = true;
|
||||
@@ -942,7 +956,8 @@ async function main(): Promise<number> {
|
||||
const logDir = path.dirname(supervisor.paths.serverLogPath);
|
||||
const controllerLogs = controllerLogNames(await readdir(logDir).catch(() => [] as string[]));
|
||||
const serverLog = (await Promise.all(controllerLogs.map(name => readFile(path.join(logDir, name), "utf8").catch(() => "")))).join("\n");
|
||||
const warmShutdown = gradeWarmShutdown({ cleanup: daytonaCleanup, serverLog });
|
||||
await waitForIdleCloseCapture("before_grade");
|
||||
const warmShutdown = gradeWarmShutdown({ cleanup: daytonaCleanup, serverLog, sandboxCaptures: idleCloseCaptures });
|
||||
timeline.add("warm_shutdown", { ...warmShutdown });
|
||||
if (warmShutdown.verdict === "fail") anyFailure = true;
|
||||
warmShutdownSection = warmShutdownMarkdown(warmShutdown);
|
||||
|
||||
@@ -555,8 +555,10 @@ export class TaskObserver {
|
||||
private async runEvidence(run: RunSample): Promise<RunSample> {
|
||||
if (run.status !== "running") return run;
|
||||
const cursor = this.runEventCursors.get(run.id) ?? { seq: 0, lastAt: null, openTools: 0, process: null };
|
||||
let eventsRead = false;
|
||||
for (let page = 0; page < 3; page += 1) {
|
||||
const events = await this.api.get<Json[]>(`/api/heartbeat-runs/${run.id}/events?afterSeq=${cursor.seq}&limit=${RUN_EVENT_PAGE}`, 5_000).catch(() => null);
|
||||
if (Array.isArray(events)) eventsRead = true;
|
||||
if (!events?.length) break;
|
||||
for (const event of events) {
|
||||
if (typeof event.seq === "number" && event.seq > cursor.seq) cursor.seq = event.seq;
|
||||
@@ -571,6 +573,7 @@ export class TaskObserver {
|
||||
}
|
||||
this.runEventCursors.set(run.id, cursor);
|
||||
return { ...run, lastEvidenceAt: latestIso([run.lastEvidenceAt, cursor.lastAt]),
|
||||
...(eventsRead && cursor.seq === 0 ? { preparing: true } : {}),
|
||||
...(cursor.openTools > 0 ? { toolInFlight: true } : {}),
|
||||
...(cursor.turnActive ? { providerTurnActive: true } : {}),
|
||||
...(cursor.process && this.processAlive(cursor.process.pid, cursor.process.startedAt) ? { processAlive: true } : {}) };
|
||||
|
||||
@@ -183,6 +183,7 @@ export class ChaosSupervisor {
|
||||
deployShape: { overlap: boolean; freshHome: boolean } = { overlap: false, freshHome: false };
|
||||
ephemeralServer = false;
|
||||
swapHook: ((info: SwapPhaseInfo) => Promise<string | void>) | null = null;
|
||||
onServerOutput: ((chunk: Buffer | string, source: string) => void) | null = null;
|
||||
private rollingRedeploys = 0;
|
||||
/** `--k15-fresh-home`: the instance home and config of the serving generation (generation 0 uses `paths`). */
|
||||
private serverHome: { home: string; configPath: string };
|
||||
@@ -232,6 +233,10 @@ export class ChaosSupervisor {
|
||||
/** K14 waves: whether the older build or this checkout is serving. */
|
||||
get serverBuild(): "upgrade_from" | "current" { return this.serverRoot === this.repositoryRoot ? "current" : "upgrade_from"; }
|
||||
|
||||
private noteServerOutput(chunk: Buffer | string, source: string): void {
|
||||
try { this.onServerOutput?.(chunk, source); } catch (error) { this.timeline.add("server_output_hook_failed", { error: String(error) }); }
|
||||
}
|
||||
|
||||
serverLogOffset(): number {
|
||||
try { return statSync(this.paths.serverLogPath).size + this.log.writableLength; } catch { return 0; }
|
||||
}
|
||||
@@ -321,8 +326,8 @@ export class ChaosSupervisor {
|
||||
this.child = child;
|
||||
const window = this.trackWindow(child, "primary");
|
||||
|
||||
child.stdout?.on("data", chunk => this.log.write(chunk));
|
||||
child.stderr?.on("data", chunk => this.log.write(chunk));
|
||||
child.stdout?.on("data", chunk => { this.log.write(chunk); this.noteServerOutput(chunk, `${child.pid}:stdout`); });
|
||||
child.stderr?.on("data", chunk => { this.log.write(chunk); this.noteServerOutput(chunk, `${child.pid}:stderr`); });
|
||||
child.once("error", error => { this.spawnErrors.set(child, error); });
|
||||
child.once("exit", (code, signal) => {
|
||||
if (window) window.exitedAt = Date.now();
|
||||
@@ -741,8 +746,8 @@ export class ChaosSupervisor {
|
||||
record.secondary = { pid: child.pid ?? null, port, spawnedAt: Date.now(), readyAt: null, stoppedAt: null };
|
||||
const secondary = { child, port, log, exit: null as string | null };
|
||||
this.secondary = secondary;
|
||||
child.stdout?.on("data", chunk => log.write(chunk));
|
||||
child.stderr?.on("data", chunk => log.write(chunk));
|
||||
child.stdout?.on("data", chunk => { log.write(chunk); this.noteServerOutput(chunk, `${child.pid}:stdout`); });
|
||||
child.stderr?.on("data", chunk => { log.write(chunk); this.noteServerOutput(chunk, `${child.pid}:stderr`); });
|
||||
child.once("error", error => { this.spawnErrors.set(child, error); });
|
||||
child.once("exit", (code, signal) => {
|
||||
if (window) window.exitedAt = Date.now();
|
||||
|
||||
@@ -6,7 +6,8 @@ import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { isSocketTypeOfServiceRace, type ChaosApi } from "./api.js";
|
||||
import { parseCommand } from "./config.js";
|
||||
import { gradeR5 } from "./grader.js";
|
||||
import { gradeR5, PREPARATION_LIMIT_MS } from "./grader.js";
|
||||
import { DEFAULT_UNIVERSAL_BOUNDS, gradeU1 } from "./universal.js";
|
||||
import { latestIso, localProcessAlive, noteLivenessEvent, QUEUED_TRIGGER_MAX_EMPTY_SAMPLES, TaskObserver, TRIGGER_LATE_MS } from "./observer.js";
|
||||
import { observedFaultSchedule, planTasks, taskFaultSchedule, TRIGGER_DELAY_RANGE_MS } from "./scheduler.js";
|
||||
import type { ChaosLab } from "./seed.js";
|
||||
@@ -424,7 +425,7 @@ describe("R5 live evidence", () => {
|
||||
expect(gradeR5(record(slow.samples)).verdict).toBe("pass");
|
||||
});
|
||||
|
||||
const quietTurn = (live: { providerTurnActive?: boolean }, quietMs: number) => {
|
||||
const quietTurn = (live: { providerTurnActive?: boolean; preparing?: boolean }, quietMs: number) => {
|
||||
const start = Date.parse("2026-11-15T05:00:00Z");
|
||||
const run = { id: "r1", status: "running", createdAt: null, startedAt: new Date(start - 600_000).toISOString(), finishedAt: null,
|
||||
errorCode: null, retryOfRunId: null, wakeCommentIds: [], livenessState: null, lastEvidenceAt: new Date(start).toISOString(), ...live };
|
||||
@@ -440,6 +441,62 @@ describe("R5 live evidence", () => {
|
||||
detail: expect.stringMatching(/^silent_dead_run r1 .* for 630s/) });
|
||||
});
|
||||
|
||||
it("does not flag a run that is still acquiring its environment before its first run event (w-20261116T001158-s7106/t010)", () => {
|
||||
const slow = JSON.parse(readFileSync(path.join(import.meta.dirname, "fixtures/t010-slow-environment-acquire.json"), "utf8")) as
|
||||
{ runId: string; firstRunEventAt: string; samples: TaskSample[] };
|
||||
const firstEventAt = Date.parse(slow.firstRunEventAt);
|
||||
const quiet = slow.samples.filter(sample => sample.at < firstEventAt);
|
||||
expect(quiet.at(-1)!.at - quiet[0]!.at).toBeGreaterThan(240_000);
|
||||
expect(quiet.every(sample => sample.runs!.find(run => run.id === slow.runId)!.lastEvidenceAt
|
||||
=== sample.runs!.find(run => run.id === slow.runId)!.startedAt)).toBe(true);
|
||||
expect(gradeR5(record(slow.samples))).toMatchObject({ verdict: "fail", detail: expect.stringMatching(/^silent_dead_run aedc1f6e/) });
|
||||
const observed = slow.samples.map(sample => ({ ...sample, runs: sample.runs?.map(run =>
|
||||
run.id === slow.runId && run.status === "running" && sample.at < firstEventAt ? { ...run, preparing: true } : run) }));
|
||||
expect(gradeR5(record(observed)).verdict).toBe("pass");
|
||||
expect(gradeU1(record(observed), DEFAULT_UNIVERSAL_BOUNDS).verdict).toBe("pass");
|
||||
});
|
||||
|
||||
it("R5 and U1 agree on a preparing run: a 6 and 7 minute restore passes both, silence past the preparation bound fails both", () => {
|
||||
for (const quietMs of [360_000, 420_000]) {
|
||||
expect(gradeR5(quietTurn({ preparing: true }, quietMs)).verdict).toBe("pass");
|
||||
expect(gradeU1(quietTurn({ preparing: true }, quietMs), DEFAULT_UNIVERSAL_BOUNDS).verdict).toBe("pass");
|
||||
}
|
||||
const pastBound = PREPARATION_LIMIT_MS + DEFAULT_UNIVERSAL_BOUNDS.orphanMs + 60_000;
|
||||
expect(gradeR5(quietTurn({ preparing: true }, pastBound))).toMatchObject({ verdict: "fail", detail: expect.stringMatching(/^silent_dead_run r1/) });
|
||||
expect(gradeU1(quietTurn({ preparing: true }, pastBound), DEFAULT_UNIVERSAL_BOUNDS)).toMatchObject({ verdict: "fail",
|
||||
detail: expect.stringMatching(/^no_owner_no_action/) });
|
||||
expect(gradeU1(quietTurn({}, 420_000), DEFAULT_UNIVERSAL_BOUNDS).verdict).toBe("fail");
|
||||
});
|
||||
|
||||
it("still fails a run silent past the preparation bound, and a started run silent past the stall bound", () => {
|
||||
expect(gradeR5(quietTurn({ preparing: true }, 570_000)).verdict).toBe("pass");
|
||||
expect(gradeR5(quietTurn({ preparing: true }, 630_000))).toMatchObject({ verdict: "fail",
|
||||
detail: expect.stringMatching(/^silent_dead_run r1 .* for 630s/) });
|
||||
expect(gradeR5(quietTurn({ preparing: false }, 240_000))).toMatchObject({ verdict: "fail", detail: expect.stringMatching(/^silent_dead_run r1/) });
|
||||
});
|
||||
|
||||
it("marks a running run as preparing only while its events read back empty", async () => {
|
||||
const startedAt = new Date().toISOString();
|
||||
const state = { runs: [{ runId: "r1", status: "running", startedAt }] as Json[], issue: { id: "i1", status: "in_progress" }, events: [] as Json[] };
|
||||
const observer = new TaskObserver({ ...base, workload: "B5" }, scriptedApi(state), lab, new Timeline(null), ready);
|
||||
await observer.launch();
|
||||
await observer.poll(Date.now());
|
||||
expect(observer.record.samples.at(-1)!.runs![0]).toMatchObject({ preparing: true });
|
||||
state.events.push({ seq: 1, eventType: "lifecycle", message: "run started", payload: {}, createdAt: startedAt });
|
||||
await observer.poll(Date.now() + 3_000);
|
||||
expect(observer.record.samples.at(-1)!.runs![0]!.preparing).toBeUndefined();
|
||||
|
||||
const unread = scriptedApi({ ...state, events: [] });
|
||||
const failing = { ...unread, get: async (route: string) => {
|
||||
if (route.includes("/events")) throw new Error("events unavailable");
|
||||
return (unread as unknown as { get(route: string): Promise<unknown> }).get(route);
|
||||
} } as unknown as ChaosApi;
|
||||
const blind = new TaskObserver({ ...base, workload: "B5" }, failing, lab, new Timeline(null), ready);
|
||||
await blind.launch();
|
||||
await blind.poll(Date.now());
|
||||
expect(blind.record.samples.at(-1)!.runs![0]!.preparing).toBeUndefined();
|
||||
});
|
||||
|
||||
it("derives tool-in-flight and process liveness from run events", async () => {
|
||||
const startedAt = new Date().toISOString();
|
||||
const identity = { processPid: 4242, processGroupId: 4242, processStartedAt: "2026-11-06T10:00:00.000Z", targetKind: "local" };
|
||||
|
||||
@@ -271,6 +271,7 @@ export interface RunSample {
|
||||
processAlive?: boolean;
|
||||
/** A provider turn started and has no turn terminal yet. */
|
||||
providerTurnActive?: boolean;
|
||||
preparing?: boolean;
|
||||
}
|
||||
|
||||
export interface InterruptionSample {
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
* (reported in the grade and ledger, never fails the task). The split comes
|
||||
* from the false-positive audit over saved waves; see README "Universal checks".
|
||||
*/
|
||||
import { PREPARATION_LIMIT_MS } from "./grader.js";
|
||||
import type { RunSample, TaskRecord, TaskSample } from "./types.js";
|
||||
|
||||
export type UniversalId = "U1" | "U2" | "U3" | "U4" | "U5";
|
||||
@@ -137,7 +138,8 @@ export function liveOwner(sample: TaskSample, queuedFor: ReadonlyMap<string, num
|
||||
if (run.status === "running") {
|
||||
if (run.toolInFlight || run.processAlive) return `run ${run.id} running (tool or process alive)`;
|
||||
const evidence = Math.max(ms(run.lastEvidenceAt) || 0, ms(run.startedAt) || 0);
|
||||
if (!evidence || sample.at - evidence <= bounds.silentRunMs) return `run ${run.id} running`;
|
||||
const silentLimit = run.preparing ? Math.max(bounds.silentRunMs, PREPARATION_LIMIT_MS) : bounds.silentRunMs;
|
||||
if (!evidence || sample.at - evidence <= silentLimit) return `run ${run.id} ${run.preparing ? "preparing" : "running"}`;
|
||||
}
|
||||
if (run.status === "queued" || run.status === "scheduled_retry") {
|
||||
if ((queuedFor.get(run.id) ?? 0) <= bounds.queuedMs) return `run ${run.id} ${run.status}`;
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { controllerLogNames, gradeWarmShutdown, isWarmWave, warmShutdownMarkdown } from "./warm-shutdown.js";
|
||||
import { controllerLogNames, gradeWarmShutdown, isWarmWave, waitBounded, warmShutdownMarkdown, watchFirstIdleCloseFailure } from "./warm-shutdown.js";
|
||||
|
||||
const esc = String.fromCharCode(27);
|
||||
const clean = { environmentDeleted: true, environmentDeleteBlocked: null, remainingSandboxes: [] };
|
||||
@@ -31,7 +33,9 @@ describe("clean warm shutdown check", () => {
|
||||
expect(check.verdict).toBe("fail");
|
||||
expect(check.environmentDeleteBlocked).toBe(blocked);
|
||||
expect(check.leakedSandboxes).toEqual(["sbx-1:started", "sbx-2:started"]);
|
||||
expect(check.shutdownCloseFailures).toEqual(['[14:20:17] WARN: idle native session cleanup failed before controller shutdown {"idleSessions":{"failed":2}}']);
|
||||
expect(check.shutdownCloseFailures).toEqual([{ runId: null, lines: 1,
|
||||
reason: 'WARN: idle native session cleanup failed before controller shutdown {"idleSessions":{"failed":2}}',
|
||||
firstLine: '[14:20:17] WARN: idle native session cleanup failed before controller shutdown {"idleSessions":{"failed":2}}' }]);
|
||||
expect(check.problems).toHaveLength(3);
|
||||
expect(warmShutdownMarkdown(check)).toContain("Verdict: FAIL");
|
||||
});
|
||||
@@ -39,7 +43,7 @@ describe("clean warm shutdown check", () => {
|
||||
it("reports a forced stop without failing when cleanup still finished", () => {
|
||||
const check = gradeWarmShutdown({ cleanup: clean,
|
||||
serverLog: "WARN: warm native session close did not settle; its Runner was stopped and the session discarded {}\n" });
|
||||
expect(check).toMatchObject({ verdict: "pass", idleCloseFailures: [expect.stringContaining("did not settle")] });
|
||||
expect(check).toMatchObject({ verdict: "pass", idleCloseFailures: [{ firstLine: expect.stringContaining("did not settle") }] });
|
||||
expect(gradeWarmShutdown({ cleanup: clean,
|
||||
serverLog: "WARN: warm native session's sandbox was already destroyed; released its owner {}\n" }).idleCloseFailures).toHaveLength(1);
|
||||
});
|
||||
@@ -51,4 +55,66 @@ describe("clean warm shutdown check", () => {
|
||||
expect(gradeWarmShutdown({ cleanup: null,
|
||||
serverLog: 'WARN: idle warm native sessions did not close {"reason":"terminal heartbeat run destroyed its environment lease"}' }).verdict).toBe("pass");
|
||||
});
|
||||
|
||||
const a1Log = readFileSync(path.join(import.meta.dirname, "fixtures/a1-warm-close-failures.log"), "utf8");
|
||||
const run300 = "300f0d61-548b-4630-8f6a-f79292ed9d24";
|
||||
const run70d = "70d909cc-8b04-40ae-a0bf-0846df140cf0";
|
||||
|
||||
it("reports each distinct (run, reason) once, not each log line (w-20261116T001158-s7106 A1: 2 sessions, 29 lines)", () => {
|
||||
expect(a1Log.split("\n").filter(line => /did not close|cleanup failed before controller shutdown/.test(line))).toHaveLength(29);
|
||||
const check = gradeWarmShutdown({ cleanup: clean, serverLog: a1Log });
|
||||
expect(check.verdict).toBe("fail");
|
||||
expect(check.shutdownCloseFailures.map(({ runId, lines }) => ({ runId, lines }))).toEqual([
|
||||
{ runId: run300, lines: 2 }, { runId: run70d, lines: 27 }]);
|
||||
expect(check.shutdownCloseFailures[0]!.reason).toMatch(/process_identity_changed\]$/);
|
||||
expect(check.shutdownCloseFailures[1]!.reason).toBe(
|
||||
"close failed: native_session_close_unrecoverable: provider_transport_failed: runner did not durably suspend before checkpoint");
|
||||
expect(check.idleCloseFailures.map(({ runId, lines }) => ({ runId, lines }))).toEqual([
|
||||
{ runId: run300, lines: 4 }, { runId: run70d, lines: 1 }]);
|
||||
expect(check.problems).toHaveLength(2);
|
||||
expect(warmShutdownMarkdown(check)).toContain("warm sessions that did not close: 2; idle closes that needed a forced stop or failed: 2.");
|
||||
});
|
||||
|
||||
it("still fails on one distinct failure, and keeps different reasons for the same run apart", () => {
|
||||
const one = a1Log.split("\n").filter(line => line.includes(run70d) && line.includes("did not close"));
|
||||
expect(gradeWarmShutdown({ cleanup: clean, serverLog: one.join("\n") })).toMatchObject({ verdict: "fail",
|
||||
shutdownCloseFailures: [{ runId: run70d, lines: 27 }] });
|
||||
const twoReasons = [
|
||||
'WARN: idle warm native sessions did not close {"reason":"controller restart","failures":[{"runId":"r1","reason":"close failed: a"}]}',
|
||||
'WARN: idle warm native sessions did not close {"reason":"controller restart","failures":[{"runId":"r1","reason":"close failed: b"}]}',
|
||||
].join("\n");
|
||||
expect(gradeWarmShutdown({ cleanup: clean, serverLog: twoReasons }).problems).toHaveLength(2);
|
||||
const unparsed = gradeWarmShutdown({ cleanup: clean, serverLog: 'WARN: idle warm native sessions did not close {"reason":"environment deleted","failures":[' });
|
||||
expect(unparsed).toMatchObject({ verdict: "fail", shutdownCloseFailures: [{ runId: null, lines: 1 }] });
|
||||
});
|
||||
|
||||
it("names the first idle-close failure once, across chunk boundaries and interleaved streams", () => {
|
||||
const seen: Array<{ runId: string | null }> = [];
|
||||
const watch = watchFirstIdleCloseFailure(failure => { seen.push(failure); });
|
||||
const failed = a1Log.split("\n").find(line => line.includes("idle warm native session close failed") && line.includes(run70d))!;
|
||||
watch("INFO: server ready\n", "1:stdout");
|
||||
watch(failed.slice(0, 40), "1:stdout");
|
||||
watch("WARN: unrelated stderr line\n", "1:stderr");
|
||||
expect(seen).toEqual([]);
|
||||
watch(`${failed.slice(40)}\n`, "1:stdout");
|
||||
watch(`${failed}\n`, "1:stdout");
|
||||
expect(seen).toEqual([expect.objectContaining({ runId: run70d })]);
|
||||
const quiet: unknown[] = [];
|
||||
const none = watchFirstIdleCloseFailure(failure => { quiet.push(failure); });
|
||||
none("WARN: warm native session close did not settle; its Runner was stopped and the session discarded {}\n");
|
||||
expect(quiet).toEqual([]);
|
||||
});
|
||||
|
||||
it("lists the sandbox captures taken at the first idle-close failure", () => {
|
||||
const check = gradeWarmShutdown({ cleanup: clean, serverLog: a1Log, sandboxCaptures: ["idle-close-failure-300f0d61"] });
|
||||
expect(check.sandboxCaptures).toEqual(["idle-close-failure-300f0d61"]);
|
||||
expect(warmShutdownMarkdown(check)).toContain("idle-close-failure-300f0d61");
|
||||
});
|
||||
|
||||
it("waits for a pending capture only up to its bound", async () => {
|
||||
expect(await waitBounded(() => null, 10)).toBe("none");
|
||||
expect(await waitBounded(() => Promise.resolve(), 1_000)).toBe("settled");
|
||||
expect(await waitBounded(() => Promise.reject(new Error("probe failed")), 1_000)).toBe("settled");
|
||||
expect(await waitBounded(() => new Promise(() => undefined), 20)).toBe("timed_out");
|
||||
});
|
||||
});
|
||||
@@ -5,19 +5,29 @@ export interface WarmShutdownCleanup {
|
||||
undeletedSandboxes?: string[];
|
||||
}
|
||||
|
||||
export interface WarmCloseFailure {
|
||||
runId: string | null;
|
||||
reason: string;
|
||||
lines: number;
|
||||
firstLine: string;
|
||||
}
|
||||
|
||||
export interface WarmShutdownCheck {
|
||||
verdict: "pass" | "fail";
|
||||
environmentDeleted: boolean | null;
|
||||
environmentDeleteBlocked: string | null;
|
||||
leakedSandboxes: string[];
|
||||
shutdownCloseFailures: string[];
|
||||
idleCloseFailures: string[];
|
||||
shutdownCloseFailures: WarmCloseFailure[];
|
||||
idleCloseFailures: WarmCloseFailure[];
|
||||
sandboxCaptures: string[];
|
||||
problems: string[];
|
||||
}
|
||||
|
||||
const SHUTDOWN_CLOSE_FAILURE = /idle native session cleanup failed before controller shutdown|idle warm native sessions did not close.*"reason":"(environment deleted|controller restart)"/;
|
||||
const IDLE_CLOSE_FAILURE = /idle warm native session (close|detach) failed|warm native session close did not settle|warm native session's sandbox was already destroyed/;
|
||||
const FIRST_IDLE_CLOSE_FAILURE = /idle warm native session (close|detach) failed|idle warm native sessions did not close|idle native session cleanup failed before controller shutdown/;
|
||||
const ANSI = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, "g");
|
||||
const MAX_PARTIAL_LINE = 256 * 1024;
|
||||
|
||||
export function controllerLogNames(names: readonly string[]): string[] {
|
||||
return names.filter(name => /^server(-[a-z0-9]+)?\.log$/.test(name)).sort();
|
||||
@@ -27,16 +37,75 @@ export function isWarmWave(options: { lifecycle?: string; daytonaWarm?: boolean
|
||||
return options.lifecycle === "warm" || options.daytonaWarm === true;
|
||||
}
|
||||
|
||||
export function gradeWarmShutdown(input: { cleanup: WarmShutdownCleanup | null; serverLog: string }): WarmShutdownCheck {
|
||||
const lines = input.serverLog.split("\n").map(line => line.replace(ANSI, "").trim()).filter(Boolean);
|
||||
const shutdownCloseFailures = lines.filter(line => SHUTDOWN_CLOSE_FAILURE.test(line));
|
||||
const idleCloseFailures = lines.filter(line => IDLE_CLOSE_FAILURE.test(line));
|
||||
function cleanLine(line: string): string {
|
||||
return line.replace(ANSI, "").trim();
|
||||
}
|
||||
|
||||
function lineDetail(line: string): Record<string, unknown> | null {
|
||||
const start = line.indexOf("{");
|
||||
if (start < 0) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(line.slice(start)) as unknown;
|
||||
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed as Record<string, unknown> : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function lineMessage(line: string): string {
|
||||
const brace = line.indexOf("{");
|
||||
return (brace < 0 ? line : line.slice(0, brace)).replace(/^\[[^\]]*\]\s*/, "").trim();
|
||||
}
|
||||
|
||||
function failureReason(value: unknown): string | null {
|
||||
if (typeof value !== "string" || !value.trim()) return null;
|
||||
return value.split(" {")[0]!.trim();
|
||||
}
|
||||
|
||||
function lineFailures(line: string): Array<{ runId: string | null; reason: string }> {
|
||||
const detail = lineDetail(line);
|
||||
const listed = Array.isArray(detail?.failures) ? detail.failures
|
||||
: Array.isArray((detail?.idleSessions as Record<string, unknown> | undefined)?.failures)
|
||||
? (detail!.idleSessions as Record<string, unknown>).failures as unknown[] : null;
|
||||
const fromList = (listed ?? []).flatMap(entry => {
|
||||
if (!entry || typeof entry !== "object") return [];
|
||||
const item = entry as Record<string, unknown>;
|
||||
const reason = failureReason(item.reason) ?? failureReason(item.closeFailure);
|
||||
return [{ runId: typeof item.runId === "string" ? item.runId : null, reason: reason ?? lineMessage(line) }];
|
||||
});
|
||||
if (fromList.length) return fromList;
|
||||
if (detail && typeof detail.runId === "string") {
|
||||
return [{ runId: detail.runId, reason: failureReason(detail.closeFailure) ?? lineMessage(line) }];
|
||||
}
|
||||
const body = line.replace(/^\[[^\]]*\]\s*/, "");
|
||||
return [{ runId: null, reason: body }];
|
||||
}
|
||||
|
||||
export function distinctCloseFailures(lines: readonly string[]): WarmCloseFailure[] {
|
||||
const byKey = new Map<string, WarmCloseFailure>();
|
||||
for (const line of lines) {
|
||||
for (const failure of lineFailures(line)) {
|
||||
const key = `${failure.runId ?? ""}\u0000${failure.reason}`;
|
||||
const existing = byKey.get(key);
|
||||
if (existing) existing.lines += 1;
|
||||
else byKey.set(key, { runId: failure.runId, reason: failure.reason, lines: 1, firstLine: line });
|
||||
}
|
||||
}
|
||||
return [...byKey.values()];
|
||||
}
|
||||
|
||||
export function gradeWarmShutdown(input: { cleanup: WarmShutdownCleanup | null; serverLog: string; sandboxCaptures?: readonly string[] }): WarmShutdownCheck {
|
||||
const lines = input.serverLog.split("\n").map(cleanLine).filter(Boolean);
|
||||
const shutdownCloseFailures = distinctCloseFailures(lines.filter(line => SHUTDOWN_CLOSE_FAILURE.test(line)));
|
||||
const idleCloseFailures = distinctCloseFailures(lines.filter(line => IDLE_CLOSE_FAILURE.test(line)));
|
||||
const problems: string[] = [];
|
||||
if (input.cleanup?.environmentDeleteBlocked) problems.push(`environment delete blocked: ${input.cleanup.environmentDeleteBlocked}`);
|
||||
else if (input.cleanup && !input.cleanup.environmentDeleted) problems.push("environment was not deleted");
|
||||
if (input.cleanup?.remainingSandboxes.length) problems.push(`sandboxes still running after cleanup: ${input.cleanup.remainingSandboxes.join(", ")}`);
|
||||
if (input.cleanup?.undeletedSandboxes?.length) problems.push(`wave sandboxes left after the harness deleted them: ${input.cleanup.undeletedSandboxes.join(", ")}`);
|
||||
for (const line of shutdownCloseFailures) problems.push(`warm session did not close: ${line}`);
|
||||
for (const failure of shutdownCloseFailures) {
|
||||
problems.push(`warm session did not close: run ${failure.runId ?? "unknown"} (${failure.lines} log line${failure.lines === 1 ? "" : "s"}): ${failure.reason}`);
|
||||
}
|
||||
return {
|
||||
verdict: problems.length ? "fail" : "pass",
|
||||
environmentDeleted: input.cleanup?.environmentDeleted ?? null,
|
||||
@@ -44,15 +113,45 @@ export function gradeWarmShutdown(input: { cleanup: WarmShutdownCleanup | null;
|
||||
leakedSandboxes: [...new Set([...input.cleanup?.remainingSandboxes ?? [], ...input.cleanup?.undeletedSandboxes ?? []])],
|
||||
shutdownCloseFailures,
|
||||
idleCloseFailures,
|
||||
sandboxCaptures: [...input.sandboxCaptures ?? []],
|
||||
problems,
|
||||
};
|
||||
}
|
||||
|
||||
export function watchFirstIdleCloseFailure(onFailure: (failure: { runId: string | null; line: string }) => void): (chunk: Buffer | string, source?: string) => void {
|
||||
const partials = new Map<string, string>();
|
||||
let fired = false;
|
||||
return (chunk, source = "") => {
|
||||
if (fired) return;
|
||||
const lines = `${partials.get(source) ?? ""}${typeof chunk === "string" ? chunk : chunk.toString("utf8")}`.split("\n");
|
||||
const rest = lines.pop() ?? "";
|
||||
partials.set(source, rest.length > MAX_PARTIAL_LINE ? "" : rest);
|
||||
for (const raw of lines) {
|
||||
const line = cleanLine(raw);
|
||||
if (!FIRST_IDLE_CLOSE_FAILURE.test(line)) continue;
|
||||
fired = true;
|
||||
onFailure({ runId: lineFailures(line)[0]?.runId ?? null, line });
|
||||
return;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export async function waitBounded(pending: () => Promise<unknown> | null, ms: number): Promise<"settled" | "timed_out" | "none"> {
|
||||
const work = pending();
|
||||
if (!work) return "none";
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
const outcome = await Promise.race([work.then(() => "settled" as const, () => "settled" as const),
|
||||
new Promise<"timed_out">(resolve => { timer = setTimeout(() => resolve("timed_out"), ms); })]);
|
||||
clearTimeout(timer);
|
||||
return outcome;
|
||||
}
|
||||
|
||||
export function warmShutdownMarkdown(check: WarmShutdownCheck): string {
|
||||
const out = ["## Clean warm shutdown (no leaked sandboxes)", "",
|
||||
`Verdict: ${check.verdict.toUpperCase()}. Environment deleted: ${check.environmentDeleted ?? "n/a"}; sandboxes left running: ${check.leakedSandboxes.length}; `
|
||||
+ `warm sessions that did not close: ${check.shutdownCloseFailures.length}; idle closes that needed a forced stop or failed: ${check.idleCloseFailures.length}.`, ""];
|
||||
for (const problem of check.problems) out.push(`- ${problem.slice(0, 2_000)}`);
|
||||
if (check.problems.length) out.push("");
|
||||
if (check.sandboxCaptures.length) out.push(`Sandbox captures at the first idle-close failure: ${check.sandboxCaptures.join(", ")} (daytona-runner/).`, "");
|
||||
return out.join("\n");
|
||||
}
|
||||
@@ -235,7 +235,7 @@
|
||||
"chat-catalog-domains/internal-routine-audit.ts",
|
||||
"run-observations.ts"
|
||||
],
|
||||
"oracleVersion": "paperclip.chat-catalog.internal.routine-audit.v6",
|
||||
"oracleVersion": "paperclip.chat-catalog.internal.routine-audit.v7",
|
||||
"coverageGaps": [],
|
||||
"expectedRunCount": 2,
|
||||
"minimumRunCount": 2,
|
||||
@@ -1259,7 +1259,7 @@
|
||||
"chat-catalog-domains/api-read-receipts.ts",
|
||||
"run-observations.ts"
|
||||
],
|
||||
"oracleVersion": "paperclip.chat-catalog.spend-breakdown.structural.v5",
|
||||
"oracleVersion": "paperclip.chat-catalog.spend-breakdown.structural.v6",
|
||||
"expectedRunCount": 2,
|
||||
"turnTimeoutMs": 120000,
|
||||
"attemptTimeoutMs": 600000,
|
||||
@@ -3668,7 +3668,7 @@
|
||||
"chat-catalog-domains/internal-support.ts",
|
||||
"chat-scenarios/navigation-preferences.yaml"
|
||||
],
|
||||
"oracleVersion": "paperclip.chat-catalog.identity-profile.v3",
|
||||
"oracleVersion": "paperclip.chat-catalog.identity-profile.v4",
|
||||
"expectedRunCount": 1,
|
||||
"turnTimeoutMs": 120000,
|
||||
"attemptTimeoutMs": 300000,
|
||||
|
||||
@@ -15,7 +15,8 @@ function valid(scenarioId: string): IdentityObservation {
|
||||
activity: repair ? [{ id: "retry", action: "accounting.retry_requested", entityId: "original", actorType: "user" }] : [],
|
||||
state: { worker: { id: "morgan" }, project: { id: "launch" }, preflightTask: { id: "preflight", identifier: "ACO-5" }, morganReceiptTask: { id: "morgan-receipt" }, rileyReceiptTask: { id: "riley-receipt" }, originalRunId: "original",
|
||||
originalRun: { id: "original", status: "succeeded", usageJson: { inputTokens: 10 } }, afterOriginalRun: { id: "original", status: "succeeded", usageJson: { inputTokens: 10 } },
|
||||
originalUsagePreserved: true, originalLogPreserved: true, originalTaskPreserved: true, unresolvedBefore: { canRetry: true, runs: [{ runId: "original", reason: "retryable" }], events: [] },
|
||||
originalUsagePreserved: true, originalLogPreserved: true, originalTaskPreserved: true, unresolvedBefore: repair ? { canRetry: true, runs: [{ runId: "original", reason: "retryable" }], events: [] }
|
||||
: { canRetry: false, runs: [], events: [{ runId: "original", reason: "missing_price", occurredAt: "2026-10-28T10:00:00.000Z" }] },
|
||||
receiptOrigin: "public-imported-synthetic-fixture", weekFrom: "2026-10-26T00:00:00Z", weekTo: "2026-11-02T00:00:00Z",
|
||||
issueCosts: [{ costCents: 137 }, { costCents: 263 }], projectCosts: [{ projectId: "launch", costCents: 400 }], agentRetryStatus: 403, humanRetryHttpStatus: 200, retryAccounted: false, retryReceiptVisible: true, retryQuality: { runs: [{ runId: "original", reason: "retryable" }], events: [] }, retryLedger: [],
|
||||
initialReplyCommentIds: ["c1"], leadApiCalls: repair ? [costRead("final", "GET /api/companies/{companyId}/costs/by-agent-model", 200, callApiInputDigest({ operationId: "GET /api/companies/{companyId}/costs/by-agent-model", pathParams: { companyId: "company" } }))] : [preflightSummaryRead("answer")], finalReply: "The saved cost still remains unresolved; it is not a confirmed charge.", finalReplyRunId: "final", retryHumanFollowup: "Actual retry receipt", confirmedPricedRepair: false, afterStillUnresolved: true } };
|
||||
@@ -50,6 +51,90 @@ describe("actual saved native accounting contexts", () => {
|
||||
const workerRead = valid("budgets-costs.spend-breakdown"); workerRead.state.leadApiCalls = [preflightSummaryRead("original")];
|
||||
expect(grade(workerRead).passed).toBe(false);
|
||||
});
|
||||
it("spend breakdown accepts a cost report whose checked date range covers the unpriced run (cohort 16)", () => {
|
||||
const grade = accountingIdentityCases[0]!.grade;
|
||||
const byAgent = "GET /api/companies/{companyId}/costs/by-agent";
|
||||
// The run-log receipt keeps only the input digest; the grader recomputes digests of covering ranges.
|
||||
const ranged = (query: { from?: string; to?: string; period?: string }, runId = "answer", status = 200, operationId = byAgent, pathParams: Record<string, string> = { companyId: "company" }) =>
|
||||
costRead(runId, operationId, status, callApiInputDigest({ operationId, pathParams, query }));
|
||||
const list = (digest: string) => costRead("answer", "GET /api/companies/{companyId}/heartbeat-runs", 200, digest);
|
||||
// Cohort 16: costs/by-agent and costs/summary for the requested week (copied from the task), plus run-list pages.
|
||||
const cohort16 = (calls: LeadApiCall[]) => { const o = valid("budgets-costs.spend-breakdown");
|
||||
Object.assign(o.state.originalRun as object, { startedAt: "2026-11-15T11:41:02.000Z", finishedAt: "2026-11-15T11:43:40.000Z" });
|
||||
o.state.unresolvedBefore = { canRetry: false, runs: [], events: [{ runId: "original", reason: "missing_price", occurredAt: "2026-11-15T11:43:40.000Z" }] };
|
||||
o.state.weekFrom = "2026-11-09T00:00:00.000Z"; o.state.weekTo = "2026-11-16T00:00:00.000Z";
|
||||
o.reply = "| Agent | Launch charges |\n|---|---|\n| Riley | $2.63 |\n| Morgan | $1.37 |\n| **Total** | **$4.00** |\n\nMorgan also finished a session on [ACO-5](/ACO/issues/ACO-5) ([the run](/ACO/agents/morgan/runs/original)) whose usage is saved but not yet priced.";
|
||||
o.links.push("/ACO/issues/ACO-5", "/ACO/agents/morgan/runs/original"); o.state.leadApiCalls = calls; return o; };
|
||||
const week = { from: "2026-11-09T00:00:00.000Z", to: "2026-11-16T00:00:00.000Z" };
|
||||
expect(grade(cohort16([ranged(week), list("page-one"), list("page-two")])).passed).toBe(true);
|
||||
// Covering ranges in the forms the grader recognizes: date-only, seconds-less, open-ended, a local-midnight offset
|
||||
// form, a from equal to the run's startedAt, and an all-time read. The cost event is at 11:43:40Z.
|
||||
for (const query of [{ from: "2026-11-09", to: "2026-11-15T23:59:59Z" }, { from: "2026-11-15T00:00Z" }, { to: "2026-11-16" },
|
||||
{ from: "2026-11-15T00:00:00-03:00", to: "2026-11-16T00:00:00-03:00" }, { from: "2026-11-15T11:41:02.000Z", to: "2026-11-15T11:43:40.000Z" },
|
||||
{ from: "2026-11-15T11:41:02Z" }, { period: "all" }, { from: "2026-11-15T00:00:00+00:00" }, { from: "2026-11-09T00:00:00-00:00", to: "2026-11-16T00:00:00-00:00" },
|
||||
{ period: "month", from: "2026-11-09T00:00:00.000Z", to: "2026-11-16T00:00:00.000Z" }, { from: "2026-11-01" }, { from: "2026-11-01T00:00:00Z", to: "2026-12-01T00:00:00Z" }])
|
||||
expect(grade(cohort16([ranged(query)])).passed, JSON.stringify(query)).toBe(true);
|
||||
expect(grade(cohort16([ranged(week, "answer", 200, "GET /api/companies/{companyId}/costs/summary", {})])).passed).toBe(true);
|
||||
// Negative controls: no read, run-list pages whose inputs prove nothing, a range that excludes the run, another
|
||||
// company, a denied read, and a read by another run. A link to the run (its id is in the task) proves no read.
|
||||
expect(grade(cohort16([])).passed).toBe(false);
|
||||
expect(grade(cohort16([list("page-one"), list("page-two")])).passed).toBe(false);
|
||||
// Ranges that exclude the cost event: an earlier week, one ending before the event (also in an offset form), one
|
||||
// starting after it.
|
||||
// An explicit range wins over period=month: last week's bounds with period=month exclude the event too.
|
||||
for (const query of [{ from: "2026-11-02", to: "2026-11-09" }, { to: "2026-11-15T11:43:00Z" }, { from: "2026-11-14T00:00:00-03:00", to: "2026-11-15T00:00:00-03:00" },
|
||||
{ from: "2026-11-15T11:44:00Z" }, { from: "2026-11-16" }, { period: "month", from: "2026-11-02", to: "2026-11-09" }])
|
||||
expect(grade(cohort16([ranged(query)])).passed, JSON.stringify(query)).toBe(false);
|
||||
// The digest names the company: another company's report does not count.
|
||||
expect(grade(cohort16([ranged(week, "answer", 200, byAgent, { companyId: "other-company" })])).passed).toBe(false);
|
||||
expect(grade(cohort16([ranged(week, "answer", 403)])).passed).toBe(false);
|
||||
expect(grade(cohort16([ranged(week, "original")])).passed).toBe(false);
|
||||
// The target's cost event sets the range: a range covering the run but ending before its late cost event fails.
|
||||
const lateEvent = cohort16([ranged({ from: "2026-11-15T00:00:00Z", to: "2026-11-15T11:50:00Z" })]);
|
||||
(lateEvent.state.unresolvedBefore as { events: unknown[] }).events = [{ runId: "original", reason: "missing_price", occurredAt: "2026-11-15T11:52:00.000Z" }];
|
||||
expect(grade(lateEvent).passed).toBe(false);
|
||||
// A pending target (saved usage, no cost event) never appears in by-agent or other ledger groupings: a by-agent read
|
||||
// with a correct-looking reply fails, while summary, data-quality or the run record itself still count.
|
||||
const pendingTarget = (calls: LeadApiCall[]) => { const o = cohort16(calls); (o.state.unresolvedBefore as { runs: unknown[]; events: unknown[] }).runs = [{ runId: "original", reason: "waiting_for_receipt" }];
|
||||
(o.state.unresolvedBefore as { events: unknown[] }).events = []; return o; };
|
||||
expect(grade(pendingTarget([ranged(week)])).passed).toBe(false);
|
||||
expect(grade(pendingTarget([ranged({ period: "all" })])).passed).toBe(false);
|
||||
expect(grade(pendingTarget([preflightSummaryRead("answer")])).passed).toBe(false);
|
||||
for (const operationId of ["GET /api/companies/{companyId}/costs/summary", "GET /api/companies/{companyId}/costs/data-quality"])
|
||||
expect(grade(pendingTarget([ranged(week, "answer", 200, operationId)])).passed, operationId).toBe(true);
|
||||
const targetRecord = costRead("answer", "GET /api/heartbeat-runs/{runId}", 200, callApiInputDigest({ operationId: "GET /api/heartbeat-runs/{runId}", pathParams: { runId: "original" } }));
|
||||
expect(grade(pendingTarget([targetRecord])).passed).toBe(true);
|
||||
// A late-month event (Nov 29) read with a month-start from (28 days earlier) or an end-of-month to counts.
|
||||
for (const query of [{ from: "2026-11-01" }, { from: "2026-11-01T00:00:00Z", to: "2026-11-30T23:59:59.999Z" }, { from: "2026-11-01T00:00:00+00:00", to: "2026-12-01T00:00:00+00:00" }]) {
|
||||
const late = cohort16([ranged(query)]);
|
||||
Object.assign(late.state.originalRun as object, { startedAt: "2026-11-29T10:00:00.000Z", finishedAt: "2026-11-29T10:02:00.000Z" });
|
||||
late.state.unresolvedBefore = { canRetry: false, runs: [], events: [{ runId: "original", reason: "missing_price", occurredAt: "2026-11-29T10:02:00.000Z" }] };
|
||||
expect(grade(late).passed, JSON.stringify(query)).toBe(true);
|
||||
}
|
||||
// A report ending at 11:43:40Z excludes an event at 11:43:40.598Z (bounds are compared as parsed instants).
|
||||
const subSecond = cohort16([ranged({ from: "2026-11-15T00:00:00Z", to: "2026-11-15T11:43:40Z" })]);
|
||||
subSecond.state.unresolvedBefore = { canRetry: false, runs: [], events: [{ runId: "original", reason: "missing_price", occurredAt: "2026-11-15T11:43:40.598Z" }] };
|
||||
expect(grade(subSecond).passed).toBe(false);
|
||||
const subSecondExact = cohort16([ranged({ from: "2026-11-15T00:00:00Z", to: "2026-11-15T11:43:40.598Z" })]);
|
||||
subSecondExact.state.unresolvedBefore = subSecond.state.unresolvedBefore;
|
||||
expect(grade(subSecondExact).passed).toBe(true);
|
||||
// Unranged and period=month reads cover the UTC month when the read ran. In-month they count; across a month
|
||||
// rollover (event on Oct 31, read on Nov 1) they do not, while an all-time read still does.
|
||||
const monthRead = (query: { period?: string } | undefined, eventAt: string, readStart: string, readEnd: string) => {
|
||||
const o = cohort16([costRead("answer", byAgent, 200, callApiInputDigest({ operationId: byAgent, pathParams: { companyId: "company" }, ...(query ? { query } : {}) }))]);
|
||||
Object.assign(o.state.originalRun as object, { startedAt: eventAt, finishedAt: eventAt });
|
||||
o.state.unresolvedBefore = { canRetry: false, runs: [], events: [{ runId: "original", reason: "missing_price", occurredAt: eventAt }] };
|
||||
Object.assign(o.runs.find(run => run.id === "answer")!, { startedAt: readStart, finishedAt: readEnd }); return o; };
|
||||
for (const query of [{ period: "month" }, undefined]) {
|
||||
expect(grade(monthRead(query, "2026-11-15T11:43:40.000Z", "2026-11-15T11:50:00.000Z", "2026-11-15T11:52:00.000Z")).passed, JSON.stringify(query)).toBe(true);
|
||||
expect(grade(monthRead(query, "2026-10-31T23:58:00.000Z", "2026-11-01T00:01:00.000Z", "2026-11-01T00:03:00.000Z")).passed, JSON.stringify(query)).toBe(false);
|
||||
expect(grade(monthRead(query, "2026-10-31T23:58:00.000Z", "2026-10-31T23:59:00.000Z", "2026-11-01T00:01:00.000Z")).passed, JSON.stringify(query)).toBe(false);
|
||||
}
|
||||
expect(grade(monthRead({ period: "all" }, "2026-10-31T23:58:00.000Z", "2026-11-01T00:01:00.000Z", "2026-11-01T00:03:00.000Z")).passed).toBe(true);
|
||||
// The answering run reads a different run's record but links the target run's id: still no read of its accounting.
|
||||
const otherRecord = costRead("answer", "GET /api/heartbeat-runs/{runId}", 200, callApiInputDigest({ operationId: "GET /api/heartbeat-runs/{runId}", pathParams: { runId: "answer" } }));
|
||||
expect(grade(cohort16([otherRecord, list("page-one")])).passed).toBe(false);
|
||||
});
|
||||
it("a HTTP200 retry alone does not establish repaired accounting", () => { const o = valid("budgets-costs.repair-cost-recording"); o.state.afterStillUnresolved = false; expect(accountingIdentityCases[1]!.grade(o).passed).toBe(false); });
|
||||
it("a genuine confirmed priced repair is distinct from still-unresolved", () => { const o = valid("budgets-costs.repair-cost-recording"); o.state.confirmedPricedRepair = true; o.state.afterStillUnresolved = false; o.state.retryAccounted = true; o.state.retryQuality = { runs: [], events: [] }; o.state.retryLedger = [{ agentId: "morgan", eventCount: 1, estimatedEventCount: 0 }]; o.state.finalReply = "The saved usage cost is now recorded. The original work was not rerun."; expect(accountingIdentityCases[1]!.grade(o).passed).toBe(true); });
|
||||
it("grades no reply wording: reworded guidance and explanations pass on the same saved evidence", () => {
|
||||
|
||||
@@ -91,12 +91,24 @@ export function leadApiCalls(events: readonly Record<string, unknown>[]): LeadAp
|
||||
* date range (a range could exclude the run), the prerequisite task's cost summary including the task itself,
|
||||
* and the original run's record (which carries its saved accounting state and usage cost status). */
|
||||
const COMPANY_COST_SEGMENTS = ["summary", "by-agent", "by-agent-model", "by-provider", "by-biller", "by-project", "data-quality"];
|
||||
/** The company reports that also count runs with saved usage but no cost event yet (pendingRunCount, unresolved runs).
|
||||
* The ledger groupings (by-agent, by-project, ...) only sum cost events, so they never show such a run. */
|
||||
const PENDING_RUN_SEGMENTS = ["summary", "data-quality"];
|
||||
export interface SavedAccountingTarget { companyId?: string; task?: Pick<Entity, "id" | "identifier">; originalRunId?: string;
|
||||
/** Run-record reads the reading run itself cites in its saved result, as `GET /api/heartbeat-runs/<runId>`. */
|
||||
citedRunReads?: readonly string[];
|
||||
/** Run records this reading run saved with `saveResponse`, read back from the product's saved asset. */
|
||||
savedRunRecords?: readonly SavedRunRecord[];
|
||||
runListPosition?: RunListPosition }
|
||||
runListPosition?: RunListPosition;
|
||||
/** When the original run started and finished. A company cost report whose `from`/`to` range covers it returns
|
||||
* the run's saved accounting, so that ranged read counts as well as an unranged one. */
|
||||
originalRunWindow?: { startedAt: string; finishedAt: string };
|
||||
/** When the original run's unresolved cost events occurred. An empty list means the run is pending with no cost event,
|
||||
* so only reports that include pending runs (summary, data-quality) or the run record can show it. Left out, every
|
||||
* company report counts (the post-retry check, which reads after the person recorded the cost). */
|
||||
costEventTimes?: readonly string[];
|
||||
/** When the reading run started and finished; month-relative reads are compared with it. */
|
||||
readingRunWindow?: { startedAt: string; finishedAt: string } }
|
||||
export interface RunListPosition { agentId: string; companyAhead: number; agentAhead: number }
|
||||
const RUN_LIST_OPERATION = "GET /api/companies/{companyId}/heartbeat-runs";
|
||||
const runListCache = new Map<string, ReadonlySet<string>>();
|
||||
@@ -125,12 +137,106 @@ export function runListPosition(runs: ReadonlyArray<{ id: string; agentId: strin
|
||||
/** A `call_api` read saved with `saveResponse` becomes a company asset that the product logs as
|
||||
* `asset.created` by the reading run. Its saved content names the record actually read. */
|
||||
export interface SavedRunRecord { runId: string; assetId: string; recordId: string; companyId: string }
|
||||
const coveringCache = new Map<string, { digests: Set<string>; pending: Generator<string> }>();
|
||||
/** Calendar spans (in days) of the ranges people ask for: a day or a few, a week, two weeks and a month. */
|
||||
const RANGE_DAYS = [1, 2, 3, 7, 8, 14, 15, 28, 29, 30, 31, 32];
|
||||
/** Local-midnight ranges at an offset: a day, a week, two weeks or a calendar month. */
|
||||
const LOCAL_RANGE_DAYS = [1, 7, 14, 28, 29, 30, 31];
|
||||
/**
|
||||
* Whether one of the run's company cost-report reads (by input digest) has a `from`/`to` covering the window. Run-log receipts keep only the input
|
||||
* digest, so the grader regenerates the inputs people write and re-parses each bound as the costs route does (both
|
||||
* bounds inclusive, as in resolveCostDateRange). Bounds are UTC day boundaries (with or without milliseconds or seconds,
|
||||
* date-only, end of day) or local midnights at a whole-hour offset (UTC also as +00:00 and -00:00), paired within one
|
||||
* form, open-ended or spanning one of RANGE_DAYS, plus the window's own instants. Every range is also generated with
|
||||
* period=month, since explicit bounds take precedence. A covering range outside these forms is not recognized: a false
|
||||
* negative, never a false pass.
|
||||
*/
|
||||
export function coveringCostReportRead(companyId: string, window: { startedAt: string; finishedAt: string }, segments: readonly string[],
|
||||
extraInstants: readonly string[], readDigests: ReadonlySet<string>): boolean {
|
||||
if (!readDigests.size) return false;
|
||||
// One lazily filled digest set per company, window and report; hashing stops at the first matching read and resumes
|
||||
// from there for the next check, so each covering input is hashed at most once.
|
||||
return segments.some(segment => {
|
||||
const key = JSON.stringify([companyId, window, segment, extraInstants]);
|
||||
let state = coveringCache.get(key);
|
||||
if (!state) coveringCache.set(key, state = { digests: new Set(), pending: coveringDigests(companyId, window, segment, extraInstants) });
|
||||
for (const digest of readDigests) if (state.digests.has(digest)) return true;
|
||||
for (let next = state.pending.next(); !next.done; next = state.pending.next()) { state.digests.add(next.value); if (readDigests.has(next.value)) return true; }
|
||||
return false;
|
||||
});
|
||||
}
|
||||
function* coveringDigests(companyId: string, window: { startedAt: string; finishedAt: string }, segment: string, extraInstants: readonly string[]): Generator<string> {
|
||||
const started = Date.parse(window.startedAt), finished = Date.parse(window.finishedAt);
|
||||
if (!Number.isFinite(started) || !Number.isFinite(finished)) return;
|
||||
const day = 86_400_000, parse = (text: string) => new Date(text).getTime();
|
||||
const iso = (at: number) => new Date(at).toISOString();
|
||||
// Bound forms: each maps a UTC date to the string a person writes for that day's midnight in the form's zone.
|
||||
const ms = (at: number) => iso(at), seconds = (at: number) => iso(at).replace(".000Z", "Z"), minutes = (at: number) => iso(at).replace(":00.000Z", "Z");
|
||||
const date = (at: number) => iso(at).slice(0, 10), endMs = (at: number) => iso(at - 1), endSeconds = (at: number) => iso(at - 1000).replace(".000Z", "Z");
|
||||
const starts = [ms, seconds, minutes, date], ends = [ms, seconds, minutes, date, endMs, endSeconds];
|
||||
// Pairs are written in one style: a precise start with a precise or end-of-day end, a date with a date or end of day.
|
||||
const forms: Array<{ from: Array<(midnight: number) => string>; to: Array<(midnight: number) => string>; month?: boolean; spans?: readonly number[] }> = [
|
||||
{ from: [ms, seconds], to: [ms, seconds, endMs, endSeconds], month: true }, { from: [minutes], to: [minutes], month: true }, { from: [date], to: [date, endMs, endSeconds], month: true }];
|
||||
for (const offset of Array.from({ length: 27 }, (_, index) => index - 12)) for (const zone of offset === 0 ? ["+00:00", "-00:00"] : [`${offset < 0 ? "-" : "+"}${String(Math.abs(offset)).padStart(2, "0")}:00`]) {
|
||||
const write = (midnight: number) => `${iso(midnight).slice(0, 10)}T00:00:00${zone}`;
|
||||
forms.push({ from: [write], to: [write], spans: LOCAL_RANGE_DAYS });
|
||||
}
|
||||
// UTC-form ranges are also generated with period=month (explicit bounds take precedence); offset forms are not.
|
||||
const queries: Array<Record<string, string>> = [], monthQueries: Array<Record<string, string>> = [];
|
||||
const firstDay = Math.floor(started / day) * day, lastDay = Math.floor(finished / day) * day;
|
||||
for (const { from, to, month, spans = RANGE_DAYS } of forms) {
|
||||
const before = queries.length;
|
||||
// Start days reach back as far as the longest span (32 days, so a month-start `from` is included for any event).
|
||||
for (let midnight = firstDay - 32 * day; midnight <= firstDay + day; midnight += day) for (const writeFrom of from) {
|
||||
const fromText = writeFrom(midnight); if (parse(fromText) > started) continue;
|
||||
queries.push({ from: fromText });
|
||||
for (const span of spans) for (const writeTo of to) {
|
||||
const toText = writeTo(midnight + span * day); if (parse(toText) >= finished) queries.push({ from: fromText, to: toText });
|
||||
}
|
||||
}
|
||||
for (let midnight = lastDay; midnight <= lastDay + 32 * day; midnight += day) for (const writeTo of to) { const toText = writeTo(midnight); if (parse(toText) >= finished) queries.push({ to: toText }); }
|
||||
if (month) monthQueries.push(...queries.slice(before));
|
||||
}
|
||||
const instantStart = queries.length;
|
||||
const instants = [window.startedAt, window.finishedAt, ...extraInstants].map(parse).filter(Number.isFinite).flatMap(at => [iso(at), iso(at).replace(/\.\d{3}Z$/, "Z")]);
|
||||
for (const fromText of instants) if (parse(fromText) <= started) { queries.push({ from: fromText }); for (const toText of instants) if (parse(toText) >= finished) queries.push({ from: fromText, to: toText }); }
|
||||
for (const toText of instants) if (parse(toText) >= finished) queries.push({ to: toText });
|
||||
// A UTC day-boundary bound paired with one of the window's own instants (e.g. from today's midnight to the event).
|
||||
const dayStarts = Array.from({ length: 33 }, (_, index) => firstDay - (32 - index) * day + day).flatMap(at => starts.map(write => write(at))).filter(text => parse(text) <= started);
|
||||
const dayEnds = Array.from({ length: 33 }, (_, index) => lastDay + index * day).flatMap(at => ends.map(write => write(at))).filter(text => parse(text) >= finished);
|
||||
for (const instant of instants) {
|
||||
if (parse(instant) >= finished) for (const fromText of dayStarts) queries.push({ from: fromText, to: instant });
|
||||
if (parse(instant) <= started) for (const toText of dayEnds) queries.push({ from: instant, to: toText });
|
||||
}
|
||||
for (const query of [...monthQueries, ...queries.slice(instantStart)]) queries.push({ ...query, period: "month" });
|
||||
for (const query of queries) for (const pathParams of [{ companyId }, {}, undefined])
|
||||
yield callApiInputDigest({ operationId: `GET /api/companies/{companyId}/costs/${segment}`, ...(pathParams ? { pathParams } : {}), query });
|
||||
}
|
||||
export function readSavedAccounting(calls: readonly LeadApiCall[], runId: string, target: SavedAccountingTarget) {
|
||||
const { companyId, task, originalRunId } = target;
|
||||
const companyDigests = companyId ? apiReadDigests(COMPANY_COST_SEGMENTS.map(segment => ({ operationId: `GET /api/companies/{companyId}/costs/${segment}`,
|
||||
// runnerApiUrl fills companyId from the run's company when the call omits it, so that form reads the same report.
|
||||
pathParams: [...recordParams("companyId", companyId), undefined], queries: [{ period: "all" }, { period: "month" }] }))) : new Set<string>();
|
||||
const taskDigests = task ? apiReadDigests([{ operationId: "GET /api/issues/{id}/cost-summary", pathParams: recordParams("id", task.id, task.identifier), queries: [{ excludeRoot: "false" }] }]) : new Set<string>();
|
||||
// A run with cost events shows in every report whose range covers those events; a pending run only in the reports
|
||||
// that count pending runs, over a range covering the run itself.
|
||||
const eventTimes = (target.costEventTimes ?? []).map(Date.parse).filter(Number.isFinite);
|
||||
const pending = !!target.costEventTimes && !eventTimes.length;
|
||||
const segments = pending ? PENDING_RUN_SEGMENTS : COMPANY_COST_SEGMENTS;
|
||||
const window = !target.costEventTimes ? target.originalRunWindow : pending ? target.originalRunWindow
|
||||
: { startedAt: new Date(Math.min(...eventTimes)).toISOString(), finishedAt: new Date(Math.max(...eventTimes)).toISOString() };
|
||||
// runnerApiUrl fills companyId from the run's company when the call omits it, so that form reads the same report.
|
||||
const reportReads = (queries: Array<Record<string, unknown>>) => companyId ? apiReadDigests(segments.map(segment => ({ operationId: `GET /api/companies/{companyId}/costs/${segment}`,
|
||||
pathParams: [...recordParams("companyId", companyId), undefined], queries }))) : new Set<string>();
|
||||
// An unranged read and period=month cover the current UTC month when the read ran. They count only when the target's
|
||||
// cost event (or the pending run) falls in that month for the whole reading run, so a month rollover cannot pass.
|
||||
const monthDigests = reportReads([{ period: "month" }]);
|
||||
const monthCovers = (() => {
|
||||
if (!("readingRunWindow" in target)) return true;
|
||||
if (!target.readingRunWindow || !window) return false;
|
||||
const month = (text: string) => { const at = new Date(text); return Number.isNaN(at.getTime()) ? "" : `${at.getUTCFullYear()}-${at.getUTCMonth()}`; };
|
||||
const months = new Set([window.startedAt, window.finishedAt, target.readingRunWindow.startedAt, target.readingRunWindow.finishedAt].map(month));
|
||||
return months.size === 1 && !months.has("");
|
||||
})();
|
||||
const companyDigests = new Set([...[...reportReads([{ period: "all" }])].filter(digest => !monthDigests.has(digest)), ...(monthCovers ? monthDigests : [])]);
|
||||
// A task's cost summary sums cost events, so it cannot show a pending run either.
|
||||
const taskDigests = task && !pending ? apiReadDigests([{ operationId: "GET /api/issues/{id}/cost-summary", pathParams: recordParams("id", task.id, task.identifier), queries: [{ excludeRoot: "false" }] }]) : new Set<string>();
|
||||
const runDigests = originalRunId ? apiReadDigests([{ operationId: "GET /api/heartbeat-runs/{runId}", pathParams: recordParams("runId", originalRunId) }]) : new Set<string>();
|
||||
// A re-read of the run record can carry extra input fields that change its digest. It still counts when the reading
|
||||
// run's own saved result names exactly that read of the original run; a read of any other run does not.
|
||||
@@ -139,11 +245,18 @@ export function readSavedAccounting(calls: readonly LeadApiCall[], runId: string
|
||||
// unlisted digest. A response the run saved is bound by its content instead: the saved run record is the original run.
|
||||
const originalRunSaved = !!originalRunId && (target.savedRunRecords ?? []).some(saved => saved.runId === runId
|
||||
&& saved.recordId === originalRunId && (!companyId || saved.companyId === companyId));
|
||||
// A from equal to the run's own startedAt (copied from its record) is a natural covering bound too.
|
||||
// Generated per report actually read by this run, since the covering set is large.
|
||||
const readSegments = segments.filter(segment => calls.some(call => call.runId === runId && call.operationId === `GET /api/companies/{companyId}/costs/${segment}`));
|
||||
const ok = (call: LeadApiCall) => call.runId === runId && call.ok && call.status >= 200 && call.status < 300;
|
||||
const rangedReads = new Set(calls.filter(call => ok(call) && readSegments.some(segment => call.operationId === `GET /api/companies/{companyId}/costs/${segment}`)
|
||||
&& !companyDigests.has(call.digest)).map(call => call.digest));
|
||||
const listDigests = companyId && target.runListPosition ? runListDigests(companyId, target.runListPosition) : new Set<string>();
|
||||
return calls.some(call => call.runId === runId && call.ok && call.status >= 200 && call.status < 300
|
||||
&& (companyDigests.has(call.digest) || taskDigests.has(call.digest)
|
||||
|| call.operationId === RUN_LIST_OPERATION && listDigests.has(call.digest)
|
||||
|| call.operationId === "GET /api/heartbeat-runs/{runId}" && (runDigests.has(call.digest) || originalRunCited || originalRunSaved)));
|
||||
|| call.operationId === "GET /api/heartbeat-runs/{runId}" && (runDigests.has(call.digest) || originalRunCited || originalRunSaved)))
|
||||
|| !!companyId && !!window && coveringCostReportRead(companyId, window, readSegments, target.originalRunWindow ? [target.originalRunWindow.startedAt] : [], rangedReads);
|
||||
}
|
||||
/** Run records the given run saved through `call_api` `saveResponse`, from the product's own activity and asset. */
|
||||
export async function savedRunRecordReads(ctx: ChatCatalogContext, runId: string, agentId: string): Promise<SavedRunRecord[]> {
|
||||
@@ -219,7 +332,9 @@ export function gradeAccounting(value: unknown) {
|
||||
const savedRunRecords = Array.isArray(o.state.savedRunRecords) ? o.state.savedRunRecords as SavedRunRecord[] : [];
|
||||
c.add("unresolved-record-read-from-saved-accounting", !!calls && o.runs.some(run => run.agentId === o.leadId && run.status === "succeeded"
|
||||
&& readSavedAccounting(calls, run.id, { companyId: o.companyId, task: o.state.preflightTask as Entity | undefined, originalRunId: String(o.state.originalRunId ?? ""),
|
||||
citedRunReads: citedRunReads(run), savedRunRecords, runListPosition: runListPosition(o.runs, String(o.state.originalRunId ?? ""), run) })),
|
||||
citedRunReads: citedRunReads(run), savedRunRecords, runListPosition: runListPosition(o.runs, String(o.state.originalRunId ?? ""), run),
|
||||
originalRunWindow: runWindow(o.state.originalRun as HeartbeatRun | undefined), readingRunWindow: runWindow(run as unknown as HeartbeatRun),
|
||||
costEventTimes: (quality?.events ?? []).filter(row => row.runId === o.state.originalRunId).map(row => row.occurredAt) })),
|
||||
"A chat run read the unresolved record's saved accounting through a product cost projection instead of inferring or inventing its cost.");
|
||||
} else if (o.scenarioId === "budgets-costs.repair-cost-recording") {
|
||||
c.add("real-human-saved-cost-retry", quality?.runs.some(row => row.runId === before?.id && row.reason === "retryable") === true && o.state.agentRetryStatus === 403
|
||||
@@ -322,7 +437,7 @@ export const accountingIdentityCases: readonly ChatCatalogCase[] = [
|
||||
}
|
||||
await ctx.input.api.patch(`/api/issues/${ctx.issue()!.id}`, { description: `The requested reporting week is ${weekFrom} through ${weekTo} (UTC). Launch's API charges this week are recorded on tasks ${morganReceiptTask.identifier} (Morgan) and ${rileyReceiptTask.identifier} (Riley). Morgan also finished one work session on Launch (run ${state.originalRunId}) whose usage is saved but not yet priced. Leave out charges from other projects and earlier weeks. Plan subscription fees are separate from API charges.` });
|
||||
return { ...state, riley, morganReceiptTask, rileyReceiptTask, weekFrom, weekTo, importedReceiptIds: receipts, receiptOrigin: "public-imported-synthetic-fixture" };
|
||||
}, gradeAccounting, { authentication: "human-session", oracleVersion: "paperclip.chat-catalog.spend-breakdown.structural.v5", sourceFiles: [...sources, "chat-catalog-domains/api-read-receipts.ts", "run-observations.ts"], expectedRunCount: 2, attemptTimeoutMs: 600_000, observe: observeAccounting, verifyResult: verifyAccountingLink, verifySetup: verifyUnresolvedSetup,
|
||||
}, gradeAccounting, { authentication: "human-session", oracleVersion: "paperclip.chat-catalog.spend-breakdown.structural.v6", sourceFiles: [...sources, "chat-catalog-domains/api-read-receipts.ts", "run-observations.ts"], expectedRunCount: 2, attemptTimeoutMs: 600_000, observe: observeAccounting, verifyResult: verifyAccountingLink, verifySetup: verifyUnresolvedSetup,
|
||||
setupPolicy: { funding: "standard", readiness: "all-ready", invariantCheckIds: ["genuine-unresolved-saved-native-usage"] } }),
|
||||
identityDefinition("budgets-costs.repair-cost-recording", async ctx => {
|
||||
try {
|
||||
@@ -376,6 +491,11 @@ export const accountingIdentityCases: readonly ChatCatalogCase[] = [
|
||||
/** The reply identifies the record whose usage has no settled cost (its task by link or identifier,
|
||||
* or its run id), and no line or sentence that names it states a zero amount for it. */
|
||||
/** The reply points at the unresolved record: a rendered link to its task or run, or its identifier or run id written out. */
|
||||
/** When a saved run started (or was created) and finished, for binding ranged cost reports to it. */
|
||||
export function runWindow(run: Pick<HeartbeatRun, "createdAt" | "startedAt" | "finishedAt"> | undefined) {
|
||||
const startedAt = run?.startedAt ?? run?.createdAt, finishedAt = run?.finishedAt;
|
||||
return startedAt && finishedAt ? { startedAt: new Date(startedAt).toISOString(), finishedAt: new Date(finishedAt).toISOString() } : undefined;
|
||||
}
|
||||
export function unresolvedRecordIdentified(o: { reply: string; links: string[]; origin: string }, record: Entity | undefined, runId: string): boolean {
|
||||
const keys = [record?.identifier, record?.id, runId || undefined, runId ? runId.slice(0, 8) : undefined].filter((key): key is string => typeof key === "string" && key.length > 0);
|
||||
if (!keys.length) return false;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { profileIdentityCases } from "./identity-profile.js";
|
||||
import { profileIdentityCases, settledFieldValue } from "./identity-profile.js";
|
||||
import { companyLifecycleIdentityCases } from "./identity-company-lifecycle.js";
|
||||
import type { IdentityObservation } from "./identity-support.js";
|
||||
function valid(id: string): IdentityObservation {
|
||||
@@ -72,4 +72,12 @@ describe("personal identity and company lifecycle oracles", () => {
|
||||
const o = valid("navigation-preferences.edit-profile"); o.agents[0]!.name = "Alex Chen";
|
||||
expect(profileIdentityCases[0]!.grade(o).passed).toBe(false);
|
||||
});
|
||||
it("reads the reloaded display name once the form fills, not the empty first read (cohort 16)", async () => {
|
||||
// Cohort 16 saved the name correctly, but a one-shot read right after reload saw "" before the form filled.
|
||||
const reads = ["", "", "Alex Chen"]; let calls = 0;
|
||||
const field = { inputValue: async () => reads[Math.min(calls++, reads.length - 1)]! };
|
||||
await expect(settledFieldValue(field, "Alex Chen", 1_000, 1)).resolves.toBe("Alex Chen");
|
||||
// A name that never arrives is reported as what the person sees, so the grade still fails it.
|
||||
await expect(settledFieldValue({ inputValue: async () => "Alex Former" }, "Alex Chen", 20, 1)).resolves.toBe("Alex Former");
|
||||
});
|
||||
});
|
||||
@@ -12,6 +12,20 @@ const observers = new WeakMap<ChatCatalogContext, Person>();
|
||||
/** Unauthenticated (non-session credential) and forbidden are both denials of the human-only profile route. */
|
||||
const AGENT_DENIED: readonly number[] = [401, 403];
|
||||
const PROFILE_EDITOR_PATH = "/company/settings/instance/profile";
|
||||
/**
|
||||
* A reloaded page fills its form after the first frame. Wait until the field reaches the expected value
|
||||
* (or the deadline passes) and return what the person finally sees, so the grade reads the settled value
|
||||
* instead of a one-shot read taken before hydration.
|
||||
*/
|
||||
export async function settledFieldValue(field: { inputValue(): Promise<string> }, expected: string, timeoutMs = 15_000, intervalMs = 250) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
for (;;) {
|
||||
const value = await field.inputValue();
|
||||
if (value === expected || Date.now() >= deadline) return value;
|
||||
await new Promise(resolve => setTimeout(resolve, intervalMs));
|
||||
}
|
||||
}
|
||||
|
||||
export function isProfileEditorLink(href: string, origin: string, prefix: string): boolean {
|
||||
try {
|
||||
const url = new URL(href, origin);
|
||||
@@ -50,7 +64,7 @@ export const profileIdentityCases: readonly ChatCatalogCase[] = [identityDefinit
|
||||
} catch (error) { await observer.dispose(); observers.delete(ctx); throw error; }
|
||||
}, gradeProfile, {
|
||||
authentication: "human-session",
|
||||
oracleVersion: "paperclip.chat-catalog.identity-profile.v3",
|
||||
oracleVersion: "paperclip.chat-catalog.identity-profile.v4",
|
||||
sourceFiles: ["chat-catalog-domains/identity-profile.ts", "chat-catalog-domains/internal-comment-reference.ts", "chat-catalog-domains/identity-auth.ts", "chat-catalog-domains/identity-private-browser.ts", "chat-catalog-domains/identity-private-browser-worker.ts", "chat-catalog-domains/identity-wizard.ts", "chat-catalog-domains/identity-support.ts", "chat-catalog-domains/internal-support.ts", "chat-scenarios/navigation-preferences.yaml"],
|
||||
async act(ctx, state) {
|
||||
await waitForReply(ctx, chatCatalogOriginalPhaseDeadline(ctx));
|
||||
@@ -70,7 +84,7 @@ export const profileIdentityCases: readonly ChatCatalogCase[] = [identityDefinit
|
||||
await ctx.input.page.getByRole("button", { name: "Save profile", exact: true }).click();
|
||||
await expect.poll(async () => (await ctx.input.api.get<Session>("/api/auth/get-session")).user.name).toBe("Alex Chen");
|
||||
await ctx.input.page.reload({ waitUntil: "domcontentloaded" });
|
||||
state.profileAfterReload = await ctx.input.page.getByLabel("Display name", { exact: true }).inputValue();
|
||||
state.profileAfterReload = await settledFieldValue(ctx.input.page.getByLabel("Display name", { exact: true }), "Alex Chen");
|
||||
const account = ctx.input.page.getByRole("button", { name: "Open account menu", exact: true });
|
||||
await expect(account).toBeVisible();
|
||||
state.accountFooterVisible = await account.getByText("Alex Chen", { exact: true }).count() === 1;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { createHash } from "node:crypto";
|
||||
import { gradeProjectDefaults, gradeProjectDefaultsSetup, projectReadCalls } from "./internal-project-defaults.js";
|
||||
import { callApiInputDigest, gradeRoutineAudit, localClock, morningTimezone } from "./internal-routine-audit.js";
|
||||
import { callApiInputDigest, gradeRoutineAudit, localClock, morningTimezone, MORNING_CANDIDATE_TIMEZONES, sameZoneClock } from "./internal-routine-audit.js";
|
||||
import { gradeWorkTimeline } from "./internal-work-timeline.js";
|
||||
import { gradeArchivePartial } from "./internal-archive-partial.js";
|
||||
function base(scenarioId: string) { return { scenarioId, origin: "https://fixture.test", companyId: "company", leadId: "ceo", state: {} as Record<string, unknown>, tasks: [] as any[], projects: [] as any[], goals: [] as any[], comments: [] as any[], activity: [] as any[], documents: [], revisions: [], links: [] as string[], reply: "", humanQueries: [], runs: [] as any[] }; }
|
||||
@@ -101,6 +101,28 @@ it("picks a real timezone where the evaluation clock reads 08:xx in every season
|
||||
const now = new Date(Date.UTC(year, month, day, hour, 17)); expect(localClock(now, morningTimezone(now)).hour).toBe(8);
|
||||
}
|
||||
});
|
||||
// Browsers report a zone by their own canonical name. Chrome reports America/Argentina/Buenos_Aires as
|
||||
// America/Buenos_Aires, which failed every 11:xx UTC dispatch in cohort 16 under a name comparison.
|
||||
const BROWSER_ALIASES: Readonly<Record<string, readonly string[]>> = { "America/Argentina/Buenos_Aires": ["America/Buenos_Aires"], "Pacific/Pago_Pago": ["Pacific/Samoa", "US/Samoa"],
|
||||
"Pacific/Honolulu": ["US/Hawaii"], "America/Phoenix": ["US/Arizona"], "Asia/Dhaka": ["Asia/Dacca"], "Asia/Tokyo": ["Japan"], "Asia/Singapore": ["Singapore"] };
|
||||
it("accepts the browser's report of every candidate zone, at every hour, by its clock rather than its name", () => {
|
||||
for (const zone of MORNING_CANDIDATE_TIMEZONES) {
|
||||
const reported = [zone, new Intl.DateTimeFormat("en-US", { timeZone: zone }).resolvedOptions().timeZone, ...(BROWSER_ALIASES[zone] ?? [])];
|
||||
for (let hour = 0; hour < 24; hour++) for (const month of [0, 6]) {
|
||||
const now = new Date(Date.UTC(2026, month, 15, hour, 52));
|
||||
for (const name of reported) expect(sameZoneClock(name, zone, now), `${name} for ${zone} at ${now.toISOString()}`).toBe(true);
|
||||
}
|
||||
}
|
||||
for (let hour = 0; hour < 24; hour++) {
|
||||
const now = new Date(Date.UTC(2026, 10, 15, hour, 52)); const zone = morningTimezone(now);
|
||||
expect(sameZoneClock(zone === "America/Argentina/Buenos_Aires" ? "America/Buenos_Aires" : zone, zone, now)).toBe(true);
|
||||
}
|
||||
// A different clock, a zone with daylight saving time, or an unknown name is still an override that did not apply.
|
||||
const now = new Date(Date.UTC(2026, 10, 15, 11, 52));
|
||||
expect(sameZoneClock("UTC", "America/Argentina/Buenos_Aires", now)).toBe(false);
|
||||
expect(sameZoneClock("America/Santiago", "America/Argentina/Buenos_Aires", now)).toBe(false);
|
||||
expect(sameZoneClock("Not/AZone", "America/Argentina/Buenos_Aires", now)).toBe(false);
|
||||
});
|
||||
it("accepts a real edit before a failed scheduled morning run that the chat run read", () => expect(gradeRoutineAudit(routine()).passed).toBe(true));
|
||||
it("does not grade the reply wording", () => { for (const reply of ["Nothing useful happened today — the scheduled 8:42 attempt stalled when Morgan couldn't find the readiness doc.", "Short answer: no. Details are on the routine page."]) { const o = routine(); o.reply = reply; expect(gradeRoutineAudit(o).passed).toBe(true); } });
|
||||
it("accepts a redacted call_api read of the routine runs and a link to the blocked execution task", () => {
|
||||
|
||||
@@ -30,6 +30,22 @@ export function morningTimezone(now: Date) {
|
||||
if (!zone) throw new Error("No candidate timezone currently reads 08:xx");
|
||||
return zone;
|
||||
}
|
||||
/** Minutes the zone's wall clock is ahead of UTC at the instant. */
|
||||
export function utcOffsetMinutes(instant: Date, timezone: string) {
|
||||
const parts = Object.fromEntries(new Intl.DateTimeFormat("en-US", { timeZone: timezone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23" })
|
||||
.formatToParts(instant).map(part => [part.type, part.value]));
|
||||
const wall = Date.UTC(Number(parts.year), Number(parts.month) - 1, Number(parts.day), Number(parts.hour), Number(parts.minute));
|
||||
return Math.round((wall - Math.floor(instant.getTime() / 60_000) * 60_000) / 60_000);
|
||||
}
|
||||
/**
|
||||
* Whether the browser's reported zone keeps the same clock as the requested one. Browsers report a zone by
|
||||
* their own canonical name, which may be an alias (Chrome reports America/Argentina/Buenos_Aires as
|
||||
* America/Buenos_Aires), so names are not compared: the UTC offsets must agree now and half a year away.
|
||||
*/
|
||||
export function sameZoneClock(reported: string, requested: string, now: Date) {
|
||||
const later = new Date(now.getTime() + 182 * 86_400_000);
|
||||
try { return [now, later].every(instant => utcOffsetMinutes(instant, reported) === utcOffsetMinutes(instant, requested)); } catch { return false; }
|
||||
}
|
||||
function morning(instant: string | undefined, timezone: string, observedAt: string) {
|
||||
return !!instant && localDay(instant, timezone) === localDay(observedAt, timezone) && localClock(new Date(instant), timezone).hour < 12;
|
||||
}
|
||||
@@ -123,7 +139,7 @@ function routineAudit(): ChatCatalogCase {
|
||||
// The person's browser lives in the routine's timezone, where it is now morning.
|
||||
const cdp = await page.context().newCDPSession(page); await cdp.send("Emulation.setTimezoneOverride", { timezoneId: timezone });
|
||||
const browserTimezone = await page.evaluate(() => Intl.DateTimeFormat().resolvedOptions().timeZone);
|
||||
if (browserTimezone !== timezone) throw new Error(`Browser timezone override did not apply (${browserTimezone})`);
|
||||
if (!sameZoneClock(browserTimezone, timezone, new Date())) throw new Error(`Browser timezone override did not apply (requested ${timezone}, browser reports ${browserTimezone})`);
|
||||
const p = await project(ctx, "Launch"); const worker = await fixtureWorker(ctx);
|
||||
// The harness funds the company and lead before setup; fund the routine's worker the same way so its
|
||||
// unpriced setup turn does not budget-pause it before the query.
|
||||
@@ -154,7 +170,7 @@ function routineAudit(): ChatCatalogCase {
|
||||
await ctx.input.evidence("chat-catalog-routine-audit-setup.json", { companyId: ctx.input.fixtures.company.id, timezone, trigger, edit, runs: outcome.runs, task: outcome.task, now });
|
||||
return { project: p, worker: { id: worker.id }, routine: saved, timezone, editEventId: edit.id, failedRunId: failed.id, executionTaskId: failed.linkedIssueId, routineRunCount: outcome.runs.length, now };
|
||||
}, gradeRoutineAudit);
|
||||
return { ...base, oracleVersion: "paperclip.chat-catalog.internal.routine-audit.v6", authentication: "human-session", expectedRunCount: 2, minimumRunCount: 2, attemptTimeoutMs: 720_000,
|
||||
return { ...base, oracleVersion: "paperclip.chat-catalog.internal.routine-audit.v7", authentication: "human-session", expectedRunCount: 2, minimumRunCount: 2, attemptTimeoutMs: 720_000,
|
||||
sourceFiles: [...base.sourceFiles, "chat-catalog-domains/internal-routine-audit.ts", "run-observations.ts"],
|
||||
async observe(ctx, state): Promise<RoutineAudit> {
|
||||
const id = entity(state, "routine").id; const o = await observeInternal(ctx, state); const leadEvents: RunEvent[] = [];
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { sanitizeAssetNamespace } from "@paperclipai/shared";
|
||||
@@ -94,6 +95,19 @@ describe("ProfileSettings", () => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("shows the saved display name in the first frame when the session is already cached", () => {
|
||||
// A reload restores the session from the saved read cache before any response. The first
|
||||
// committed frame must show the saved name, not an empty field that an effect fills later.
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
|
||||
queryClient.setQueryData(queryKeys.auth.session, {
|
||||
session: { id: "session-1", userId: "user-1" },
|
||||
user: { id: "user-1", name: "Alex Chen", email: "alex@example.com", image: null },
|
||||
});
|
||||
const html = renderToStaticMarkup(<QueryClientProvider client={queryClient}><ProfileSettings /></QueryClientProvider>);
|
||||
const field = new DOMParser().parseFromString(html, "text/html").getElementById("profile-name") as HTMLInputElement | null;
|
||||
expect(field?.getAttribute("value")).toBe("Alex Chen");
|
||||
});
|
||||
|
||||
it("does not render a keyboard shortcuts toggle because shortcuts are always enabled", async () => {
|
||||
const root = createRoot(container);
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
|
||||
@@ -29,14 +29,18 @@ export function ProfileSettings() {
|
||||
const queryClient = useQueryClient();
|
||||
const avatarInputId = useId();
|
||||
const avatarInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const [name, setName] = useState("");
|
||||
const [image, setImage] = useState("");
|
||||
// Unedited fields show the session's saved values from the first frame; a
|
||||
// restored session must not render an empty name until an effect fills it.
|
||||
const [nameDraft, setName] = useState<string | null>(null);
|
||||
const [imageDraft, setImage] = useState<string | null>(null);
|
||||
const [actionError, setActionError] = useState<string | null>(null);
|
||||
const sessionQuery = useQuery({
|
||||
queryKey: queryKeys.auth.session,
|
||||
queryFn: () => authApi.getSession(),
|
||||
});
|
||||
const sessionView = useQueryView(sessionQuery);
|
||||
const name = nameDraft ?? sessionQuery.data?.user.name ?? "";
|
||||
const image = imageDraft ?? sessionQuery.data?.user.image ?? "";
|
||||
|
||||
useEffect(() => {
|
||||
setBreadcrumbs([
|
||||
@@ -46,10 +50,8 @@ export function ProfileSettings() {
|
||||
}, [setBreadcrumbs]);
|
||||
|
||||
useEffect(() => {
|
||||
const session = sessionQuery.data;
|
||||
if (!session) return;
|
||||
setName(session.user.name ?? "");
|
||||
setImage(session.user.image ?? "");
|
||||
setName(null);
|
||||
setImage(null);
|
||||
}, [sessionQuery.data]);
|
||||
|
||||
function syncSessionProfile(profile: CurrentUserProfile) {
|
||||
|
||||
Reference in new issue
Block a user