mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 23:56:43 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Native harness runs end with a result from the agent's finish tool
and a provider terminal
> - A provider can refuse a later request in the same turn after the
finish was accepted (Antigravity 1.5.2 streams its final reply after the
finish)
> - Paperclip counted that run as failed and retried it, so the agent
did the work again and posted the same reply again
> - The product rule is that recovery is automatic and that finished
work is never repeated visibly
> - This pull request makes an accepted done report the run's outcome
when the only later failure is a transient provider refusal (capacity or
rate limit), for every native harness
> - The benefit is one reply per task and no retry for work that is
already done
## Linked Issues or Issue Description
**What happened?**
In a local run of Google Antigravity 1.5.2 (Google sign-in,
`gemini-3.8-flash-low`), Google refused 10 of 17 runs with 503 "No
capacity available". In two runs the agent's finish was already accepted
when the refusal came. Paperclip failed those runs and scheduled the
capacity retry. One task got the same answer three times.
**Expected behavior**
When the agent's done report was accepted and the only later failure is
a transient provider refusal, the run succeeds, the task closes as for
any done report, and no retry starts. A real failure (model not
available, exhausted allowance, rejected sign-in, untyped failure,
cancelled run, no accepted finish) stays a failure.
**Steps to reproduce**
1. Run a native task whose finish tool is accepted.
2. Make the provider fail the same turn afterwards with a typed
`overloaded` or `rate_limit` failure (or Codex `serverOverloaded`).
3. See that the run fails and a capacity retry is scheduled.
**Agent adapter(s) involved**
Not adapter-specific (core bug). Observed with Google Antigravity; the
same path applies to Codex and other native harnesses.
## What Changed
- `native-provider-failure.ts`: the rule
`nativeAcceptedResultOutlivesProviderFailure`. It reads only the
committed terminal and its typed failure. It is true only for a failed
turn with an accepted `done` report and a transient `overloaded` or
`rate_limit` failure (or the classified Codex overload). Other accepted
dispositions keep the bounded capacity retry.
- `native-accepted-outcome.ts` (new): the decision is made once, when
`PaperclipControlPlanePort.completeRun` accepts the result, and saved as
`acceptedOutcome` beside the raw terminal in
`native_run_results.result_json`. The raw terminal does not change,
because it is part of the accepted result's integrity digest. No
migration: the field is optional JSON, and a row saved by an older
release keeps its raw terminal as before.
- Every reader of the run outcome uses that saved value: the executor's
adapter result, the finalizer, the projection repair pass
(`native-run-projection.ts`, also in SQL), accepted-result settlement,
and the run's saved `prpRunTerminalState` (read by the exhausted and
superseded finalization paths).
- The run records a closed diagnostic
`providerFailureAfterAcceptedResult: { provider, category }` and no
provider text. Its warm provider session stays open
(`nativeRetainsWarmSession`): the refusal came from the remote model
service and the turn ended cleanly, so closing it would only cold-start
the next message.
- `doc/plans/2026-11-22-antigravity-qualification.md`: records the first
completed prompts on 1.5.2 and the open decisions below.
## Verification
-
`server/src/services/native-runtime/native-provider-overload.integration.test.ts`
(embedded Postgres, executor and finalizer, replayed twice):
- New: accepted finish, then a typed capacity refusal, a typed rate
limit, or Codex `serverOverloaded`: the run succeeds, the task is done,
no successor run, no failure report. Red before the fix (3 failed),
green after.
- New: after the finalizer commits, a restart that leaves the run
`running` is settled by the projection repair pass as succeeded, with no
failure report; the saved `prpRunTerminalState` is `succeeded`. Red
before the stored outcome (projection flipped the run to failed).
- New: a row saved without the accepted outcome (older release) stays
failed through finalizer and projection.
- New guards: accepted finish, then model unavailable, exhausted
allowance, rejected sign-in or an untyped failure: the run still fails
and the task is not done.
- Existing capacity-retry cases (accepted `needs_review` result) still
retry after one and two minutes, then block.
- `server/src/services/native-runtime/native-provider-failure.test.ts`:
new unit cases with the real Antigravity observation (503 and 429
outlive the finish; model, quota, sign-in, unknown retryability,
timeout, `needs_review` and cancelled do not). 70/70 pass.
- `tsc --noEmit` for `server`: clean.
- 40 neighbouring test files that import the port, projection,
settlement or finalizer: 4,193 passed, 10 failed. The same 10 fail with
the base source (missing local bundled skill file and a runnerd fixture
directory), so they are local-environment failures.
- `pnpm verify` selected 2,980 of 3,857 test files (core native-runtime
modules changed), which is a full-suite run. I stopped it after its
first group (4 files, 85 tests) passed and left the broad suite to
required CI, as AGENTS.md section 7 says.
- Not run live: the fixed behavior has not been re-run against Google.
The evidence came from a local instance before this change. Daytona and
the API-key route were not run.
## Risks
- Behavior change for every native harness: a failed turn with an
accepted done report and a transient refusal now ends as success. A done
report still goes through the same completion policy, deliverable
evidence check and review stages as any done report.
- A run whose result was saved by the previous release and finalized by
this one keeps its raw failed terminal (old behavior), consistently in
the finalizer and the projection (tested).
- Not fixed here, open for an owner decision:
- A capacity refusal before any accepted result takes the saved-work
replacement path (about 30 s, task shown as blocked meanwhile). One
after an accepted result takes the bounded capacity retry. The
Antigravity classifier already types both as `overloaded`/`transient`;
the split is by path. Moving the first kind to the capacity retry skips
the replacement's stop proof and unconfirmed-action check.
- Antigravity 1.5.2 streams the provider's error text as agent text
before it ends the turn, so the live transcript shows it like a reply. A
fix belongs in the runner driver.
- Follow-ups seen in the same evidence, not fixed here: the finish tool
once refused a reply that cited a workspace-only file before the agent
registered a deliverable.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, local test runs).
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
816 lines
42 KiB
TypeScript
816 lines
42 KiB
TypeScript
import { notifyNativeResultCommit } from "../native-result-commit-notifications.js";
|
|
import { applyNativeAcceptedOutcome, deriveNativeAcceptedOutcome, NATIVE_ACCEPTED_OUTCOME_KEY } from "./native-accepted-outcome.js";
|
|
import { readPersistedNativeFailureEvidence } from "./native-provider-failure-evidence.js";
|
|
import { notifyNativeWorkspaceFinalization } from "../native-workspace-finalization-notifications.js";
|
|
import { createAgentIdentityRedactor } from "../agent-identity-redaction.js";
|
|
import { and, asc, eq, gt, or, sql } from "drizzle-orm";
|
|
import type { Db } from "@paperclipai/db";
|
|
import {
|
|
heartbeatRunEvents,
|
|
heartbeatRuns,
|
|
issues,
|
|
nativeRunFinalizations,
|
|
nativeRunResults,
|
|
nativeRunnerCheckpoints,
|
|
toolInvocations,
|
|
} from "@paperclipai/db";
|
|
import type {
|
|
CompleteControlPlaneRunInput,
|
|
ControlPlanePort,
|
|
NativeRunEvent,
|
|
NativeRunResult,
|
|
OpenControlPlaneRunInput,
|
|
PersistedNativeSession,
|
|
PrpEvent,
|
|
PrpTerminalState,
|
|
ReplayControlPlaneEventsInput,
|
|
} from "../../vendor/paperclip-runner/index.js";
|
|
import {
|
|
normalizePrpResultSignals,
|
|
validatePrpEvent,
|
|
validatePrpStructuredRunResult,
|
|
} from "../../vendor/paperclip-runner/index.js";
|
|
import { appendHeartbeatRunEvent, appendHeartbeatRunEventBatch, type AppendHeartbeatRunEventInput,
|
|
type AppendHeartbeatRunEventResult } from "../heartbeat-run-events.js";
|
|
import { publishLiveEvent } from "../live-events.js";
|
|
import { nativeSha256 } from "./canonical.js";
|
|
import { redactRunnerApiEvent, redactRunnerApiPayloads } from "./runner-api-log-redaction.js";
|
|
import { createNativeControllerRecovery, NATIVE_CONTROLLER_RECOVERY_MAX_BYTES, type NativeControllerCompatibility } from "./native-controller-recovery.js";
|
|
import { eligibleNativeTaskSessionPublication, publishNativeTaskSessionInTransaction, NATIVE_TASK_SESSION_PUBLICATION_KEY,
|
|
type NativeTaskSessionPublicationContext, type NativeTaskSessionPublicationIssue } from "./native-task-session-publication.js";
|
|
import { trackRunIntake } from "../run-intake-stall-watch.js";
|
|
import { lockNativeRunnerCheckpointOwner, nativeRunnerCheckpointOwnerLock, validateNativeRunnerCheckpointOwner, inspectNativeRunnerUpgradeHeader, type NativeRunnerCheckpointOwner } from "./native-runner-checkpoint.js";
|
|
import { crashPoint } from "@paperclipai/shared/crash-points";
|
|
import { NATIVE_PROVIDER_DURABLE_EVENT_TYPES } from "./native-retired-backup-source.js";
|
|
import { recordRunEventCommitted } from "../server-metrics.js";
|
|
|
|
export interface PaperclipControlPlaneBinding {
|
|
companyId: string;
|
|
issueId: string;
|
|
runId: string;
|
|
agentId: string;
|
|
sessionId: string;
|
|
completionContractId: string;
|
|
completionContractSha256: string;
|
|
sourceInstanceId: string;
|
|
controlPlaneSourceInstanceId: string;
|
|
}
|
|
|
|
const IDENTITY_DELTA_RETRY_WINDOW = 1_024;
|
|
const IDENTITY_DELTA_RETRY_BYTES = 4 * 1024 * 1024;
|
|
/** Text deltas that follow the first one after another event wait at most this long for their batch. */
|
|
export const STREAMING_EVENT_BATCH_MS = 250;
|
|
/** A batch that reaches this many deltas commits at once. */
|
|
export const STREAMING_EVENT_BATCH_MAX = 100;
|
|
|
|
type AppendReceipt = { cursor: number; highestContiguousSourceSeq: number; disposition: "committed" | "duplicate" };
|
|
type PendingStreamingEvent = {
|
|
event: PrpEvent;
|
|
input: AppendHeartbeatRunEventInput;
|
|
options?: { signal: AbortSignal };
|
|
startedAtMs: number;
|
|
startedClock: number;
|
|
resolve: (receipt: AppendReceipt) => void;
|
|
reject: (error: unknown) => void;
|
|
};
|
|
|
|
function isPrpEvent(value: NativeRunEvent | PrpEvent): value is PrpEvent {
|
|
return "schema" in value && [
|
|
"paperclip.prp.event.v1",
|
|
"paperclip.prp.event.v2",
|
|
"paperclip.prp.event.v3",
|
|
].includes(value.schema);
|
|
}
|
|
|
|
function isCompleteInput(value: NativeRunResult | CompleteControlPlaneRunInput): value is CompleteControlPlaneRunInput {
|
|
return "result" in value && "terminal" in value;
|
|
}
|
|
|
|
function record(value: unknown): Record<string, unknown> {
|
|
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
? value as Record<string, unknown>
|
|
: {};
|
|
}
|
|
|
|
function assertTerminal(value: unknown): asserts value is PrpTerminalState {
|
|
const terminal = value as Partial<PrpTerminalState> | null;
|
|
if (
|
|
terminal?.schema !== "paperclip.prp.terminal.v1"
|
|
|| !["completed", "failed", "interrupted", "cancelled"].includes(String(terminal.turnTerminalState))
|
|
|| !["succeeded", "failed", "cancelled"].includes(String(terminal.runTerminalState))
|
|
|| !["done", "blocked", "needs_review", "yielded"].includes(String(terminal.reportedWorkDisposition))
|
|
) {
|
|
throw new Error("native_terminal_schema_invalid");
|
|
}
|
|
}
|
|
|
|
/** Production implementation of the runner package's deliberately narrow persistence port. */
|
|
export class PaperclipControlPlanePort implements ControlPlanePort {
|
|
readonly #db: Db;
|
|
readonly #identityRedactor: ReturnType<typeof createAgentIdentityRedactor>;
|
|
readonly #redactedDeltas = new Map<string, { event: PrpEvent; originalSha: string; bytes: number }>();
|
|
#redactedDeltaBytes = 0;
|
|
readonly #binding: PaperclipControlPlaneBinding;
|
|
#sessionId: string | null = null;
|
|
readonly #assertControllerActive?: () => void;
|
|
readonly #assertRunAdmissionActive?: () => void;
|
|
readonly #onResultCommitted?: () => Promise<void>;
|
|
readonly #onEventPersistence?: (event: PrpEvent, startedAtMs: number, endedAtMs: number) => Promise<void>;
|
|
readonly #onCommittedEvent?: (event: PrpEvent, cursor: number) => Promise<void>;
|
|
readonly #onDuplicateEvent?: (event: PrpEvent, cursor: number) => Promise<void>;
|
|
readonly #nativeRecovery?: { compatibility: NativeControllerCompatibility; owner: NativeRunnerCheckpointOwner };
|
|
readonly #taskSessionPublication?: NativeTaskSessionPublicationContext;
|
|
readonly #taskSessionPublicationOwner?: NativeRunnerCheckpointOwner;
|
|
readonly #deferredEventObservers = new Map<string, Promise<void>>();
|
|
#deferredObserverFailure: { error: unknown } | null = null;
|
|
/**
|
|
* Text deltas commit in batches. A caller may start the next append before
|
|
* a delta's receipt settles; the receipt settles after its batch commits.
|
|
*/
|
|
readonly pipelinesStreamingEvents = true;
|
|
readonly pipelinedEventTypes: ReadonlySet<PrpEvent["eventType"]> = new Set(["item.delta", "tool.execution.progressed"]);
|
|
readonly #streamingBatchMs: number;
|
|
#streamingBatch: PendingStreamingEvent[] = [];
|
|
#streamingTimer: ReturnType<typeof setTimeout> | null = null;
|
|
#streamingTail: Promise<void> = Promise.resolve();
|
|
#streamingFlushQueued = false;
|
|
/** Deltas queued or committing. Other operations wait only when some are; otherwise they start at once. */
|
|
#streamingEventsPending = 0;
|
|
/**
|
|
* False until a delta with text is appended after the latest other event. Until
|
|
* then each delta commits at once, so the first text of an item, and the
|
|
* time to first token, never wait for the batch timer.
|
|
*/
|
|
#streamedSinceBoundary = false;
|
|
|
|
constructor(
|
|
db: Db,
|
|
binding: PaperclipControlPlaneBinding,
|
|
options: {
|
|
/** Runtime-only secret; never part of the persisted binding. */
|
|
privateKeyPem?: string;
|
|
secrets?: readonly string[];
|
|
/** Synchronous revocation fence for a controller handing off on restart. */
|
|
assertControllerActive?: () => void;
|
|
/** Read-only admission may finish an existing startup solely for restart detachment. */
|
|
assertRunAdmissionActive?: () => void;
|
|
onResultCommitted?: () => Promise<void>;
|
|
onEventPersistence?: (event: PrpEvent, startedAtMs: number, endedAtMs: number) => Promise<void>;
|
|
onCommittedEvent?: (event: PrpEvent, cursor: number) => Promise<void>;
|
|
onDuplicateEvent?: (event: PrpEvent, cursor: number) => Promise<void>;
|
|
nativeRecovery?: { compatibility: NativeControllerCompatibility; owner: NativeRunnerCheckpointOwner };
|
|
taskSessionPublication?: NativeTaskSessionPublicationContext;
|
|
taskSessionPublicationOwner?: NativeRunnerCheckpointOwner;
|
|
/** How long a text delta that is not the first after another event may wait for its batch. */
|
|
streamingBatchMs?: number;
|
|
} = {},
|
|
) {
|
|
this.#streamingBatchMs = options.streamingBatchMs ?? STREAMING_EVENT_BATCH_MS;
|
|
this.#db = db;
|
|
this.#assertControllerActive = options.assertControllerActive;
|
|
this.#assertRunAdmissionActive = options.assertRunAdmissionActive ?? options.assertControllerActive;
|
|
this.#identityRedactor = createAgentIdentityRedactor(options.privateKeyPem, options.secrets, { maskResumedSuffixes: true });
|
|
this.#binding = structuredClone(binding);
|
|
this.#onCommittedEvent = options.onCommittedEvent;
|
|
this.#onEventPersistence = options.onEventPersistence;
|
|
this.#onResultCommitted = options.onResultCommitted;
|
|
this.#onDuplicateEvent = options.onDuplicateEvent;
|
|
this.#nativeRecovery = options.nativeRecovery;
|
|
this.#taskSessionPublication = options.taskSessionPublication ? structuredClone(options.taskSessionPublication) : undefined;
|
|
this.#taskSessionPublicationOwner = options.taskSessionPublicationOwner;
|
|
}
|
|
|
|
#assertActive(options?: { signal: AbortSignal }): void {
|
|
this.#assertControllerActive?.();
|
|
options?.signal.throwIfAborted();
|
|
}
|
|
|
|
async #settleDeferredObservers(options?: { signal: AbortSignal }): Promise<void> {
|
|
const assertActive = () => {
|
|
this.#assertActive(options);
|
|
if (this.#deferredObserverFailure) throw this.#deferredObserverFailure.error;
|
|
};
|
|
assertActive();
|
|
if (this.#deferredEventObservers.size === 0) return;
|
|
const signal = options?.signal;
|
|
let removeAbort = () => {};
|
|
const aborted = new Promise<never>((_resolve, reject) => {
|
|
if (!signal) return;
|
|
const abort = () => reject(signal.reason ?? new Error("native event observation aborted"));
|
|
signal.addEventListener("abort", abort, { once: true });
|
|
removeAbort = () => signal.removeEventListener("abort", abort);
|
|
if (signal.aborted) abort();
|
|
});
|
|
try {
|
|
// Aborting a checkpoint revokes its writes, not already-owned accounting
|
|
// or output observation. Each retained promise remains observed below.
|
|
while (this.#deferredEventObservers.size > 0) {
|
|
await Promise.race([Promise.all([...this.#deferredEventObservers.values()]), aborted]);
|
|
assertActive();
|
|
}
|
|
} finally { removeAbort(); }
|
|
assertActive();
|
|
}
|
|
|
|
#matchesPersistedBinding(run: Pick<typeof heartbeatRuns.$inferSelect,
|
|
"companyId" | "agentId" | "runtimeMode" | "nativeIssueId" | "nativeSessionId" |
|
|
"runnerInstanceId" | "completionContractId" | "completionContractSha256">): boolean {
|
|
return run.companyId === this.#binding.companyId
|
|
&& run.agentId === this.#binding.agentId
|
|
&& run.runtimeMode === "native"
|
|
&& run.nativeIssueId === this.#binding.issueId
|
|
&& run.nativeSessionId === this.#binding.sessionId
|
|
&& run.runnerInstanceId === this.#binding.sourceInstanceId
|
|
&& run.completionContractId === this.#binding.completionContractId
|
|
&& run.completionContractSha256 === this.#binding.completionContractSha256;
|
|
}
|
|
|
|
async openRun(input: OpenControlPlaneRunInput): Promise<void> {
|
|
this.#assertRunAdmissionActive?.();
|
|
const identity = input.identity;
|
|
if (
|
|
identity.companyId !== this.#binding.companyId
|
|
|| identity.issueId !== this.#binding.issueId
|
|
|| identity.runId !== this.#binding.runId
|
|
|| identity.agentId !== this.#binding.agentId
|
|
|| identity.sessionId !== this.#binding.sessionId
|
|
|| input.sourceInstanceId !== this.#binding.sourceInstanceId
|
|
) {
|
|
throw new Error("native_open_run_binding_mismatch");
|
|
}
|
|
const run = await this.#db.select().from(heartbeatRuns)
|
|
.where(and(
|
|
eq(heartbeatRuns.id, this.#binding.runId),
|
|
eq(heartbeatRuns.companyId, this.#binding.companyId),
|
|
eq(heartbeatRuns.agentId, this.#binding.agentId),
|
|
))
|
|
.limit(1)
|
|
.then((rows) => rows[0] ?? null);
|
|
if (!run || !this.#matchesPersistedBinding(run)) {
|
|
throw new Error("native_open_run_not_authorized");
|
|
}
|
|
this.#assertRunAdmissionActive?.();
|
|
this.#sessionId = identity.sessionId;
|
|
}
|
|
|
|
async loadSessionCheckpoint(): Promise<PersistedNativeSession | null> {
|
|
const run = await this.#db.select().from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, this.#binding.runId))
|
|
.limit(1).then((rows) => rows[0] ?? null);
|
|
if (
|
|
!run
|
|
|| !this.#matchesPersistedBinding(run)
|
|
) throw new Error("native_session_checkpoint_binding_mismatch");
|
|
const candidate = record(run.runnerProfileJson).sessionCheckpoint;
|
|
if (candidate === undefined || candidate === null) return null;
|
|
const snapshot = record(candidate) as Partial<PersistedNativeSession>;
|
|
const identity = record(snapshot.identity);
|
|
if (
|
|
typeof snapshot.sessionId !== "string"
|
|
|| identity.companyId !== this.#binding.companyId
|
|
|| identity.issueId !== this.#binding.issueId
|
|
|| identity.runId !== this.#binding.runId
|
|
|| identity.agentId !== this.#binding.agentId
|
|
|| identity.sessionId !== run.nativeSessionId
|
|
) throw new Error("native_session_checkpoint_invalid");
|
|
return structuredClone(snapshot as PersistedNativeSession);
|
|
}
|
|
|
|
normalizeReplayPayload(payload: PrpEvent["payload"]): PrpEvent["payload"] {
|
|
return redactRunnerApiPayloads(this.#identityRedactor.redact(payload));
|
|
}
|
|
|
|
async checkpointSession(snapshot: PersistedNativeSession, options?: { signal: AbortSignal }): Promise<void> {
|
|
this.#assertActive(options);
|
|
if (this.#streamingEventsPending > 0) await this.#flushStreamingEvents();
|
|
if (this.#deferredEventObservers.size > 0 || this.#deferredObserverFailure) await this.#settleDeferredObservers(options);
|
|
snapshot = redactRunnerApiPayloads(this.#identityRedactor.redact(snapshot));
|
|
const identity = snapshot.identity;
|
|
if (
|
|
identity.companyId !== this.#binding.companyId
|
|
|| identity.issueId !== this.#binding.issueId
|
|
|| identity.runId !== this.#binding.runId
|
|
|| identity.agentId !== this.#binding.agentId
|
|
|| this.#sessionId !== identity.sessionId
|
|
) throw new Error("native_session_checkpoint_binding_mismatch");
|
|
const publication = this.#taskSessionPublication && eligibleNativeTaskSessionPublication(snapshot)
|
|
? this.#taskSessionPublication : null;
|
|
if (publication && !this.#taskSessionPublicationOwner) throw new Error("native_task_session_publication_owner_required");
|
|
await this.#db.transaction(async (tx) => {
|
|
const recovery = this.#nativeRecovery;
|
|
const owner = recovery?.owner ?? (publication ? this.#taskSessionPublicationOwner : undefined);
|
|
if (publication && recovery && nativeSha256(recovery.owner) !== nativeSha256(this.#taskSessionPublicationOwner)) {
|
|
throw new Error("native_task_session_publication_owner_mismatch");
|
|
}
|
|
const ownerLock = owner ? nativeRunnerCheckpointOwnerLock(tx, owner) : null;
|
|
// NO KEY UPDATE serializes reset/admission fields while remaining compatible
|
|
// with completeRun's parent KEY SHARE. Keep coordinator → issue → run order.
|
|
const publicationIssue = publication ? tx.$with("publication_issue").as(tx.select({
|
|
id: issues.id, companyId: issues.companyId, executionRunId: issues.executionRunId,
|
|
conversationAgentId: issues.conversationAgentId, conversationSessionGeneration: issues.conversationSessionGeneration,
|
|
}).from(issues).where(and(eq(issues.id, this.#binding.issueId), eq(issues.companyId, this.#binding.companyId),
|
|
ownerLock ? sql`exists (select 1 from ${ownerLock})` : undefined)).for("no key update")) : null;
|
|
const lockedRun = tx.$with("snapshot_run").as(tx.select({
|
|
id: heartbeatRuns.id, status: heartbeatRuns.status,
|
|
contextSnapshot: (publication ? sql<Record<string, unknown>>`jsonb_build_object('conversationSessionGeneration', ${heartbeatRuns.contextSnapshot}->'conversationSessionGeneration')` : sql<null>`null`).as("publication_context"),
|
|
resultJson: (publication ? sql<Record<string, unknown>>`jsonb_build_object('nativeCancellation', ${heartbeatRuns.resultJson}->'nativeCancellation',
|
|
'cancellation', ${heartbeatRuns.resultJson}->'cancellation', 'startupCancellation', ${heartbeatRuns.resultJson}->'startupCancellation')` : sql<null>`null`).as("publication_cancellation"),
|
|
startedAt: heartbeatRuns.startedAt, createdAt: heartbeatRuns.createdAt,
|
|
companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId,
|
|
runtimeMode: heartbeatRuns.runtimeMode, nativeIssueId: heartbeatRuns.nativeIssueId,
|
|
nativeSessionId: heartbeatRuns.nativeSessionId, runnerInstanceId: heartbeatRuns.runnerInstanceId,
|
|
completionContractId: heartbeatRuns.completionContractId,
|
|
completionContractSha256: heartbeatRuns.completionContractSha256,
|
|
runnerProfileJson: heartbeatRuns.runnerProfileJson,
|
|
}).from(heartbeatRuns)
|
|
.where(and(eq(heartbeatRuns.id, this.#binding.runId), ownerLock
|
|
? sql`exists (select 1 from ${ownerLock})` : undefined,
|
|
publicationIssue ? sql`exists (select 1 from ${publicationIssue})` : undefined)).for("update"));
|
|
// Project the locking CTE's tuples, including any update committed while
|
|
// the lock waited. A second scan of heartbeat_runs could see an old MVCC tuple.
|
|
// The run CTE depends on the coordinator CTE: both locks precede the
|
|
// outer clock sample, including when either lock waits.
|
|
const selected = await tx.with(...(ownerLock ? [ownerLock] : []), ...(publicationIssue ? [publicationIssue] : []), lockedRun).select({ run: {
|
|
id: lockedRun.id, status: lockedRun.status, contextSnapshot: lockedRun.contextSnapshot, resultJson: lockedRun.resultJson,
|
|
startedAt: lockedRun.startedAt, createdAt: lockedRun.createdAt,
|
|
companyId: lockedRun.companyId, agentId: lockedRun.agentId,
|
|
runtimeMode: lockedRun.runtimeMode, nativeIssueId: lockedRun.nativeIssueId,
|
|
nativeSessionId: lockedRun.nativeSessionId, runnerInstanceId: lockedRun.runnerInstanceId,
|
|
completionContractId: lockedRun.completionContractId,
|
|
completionContractSha256: lockedRun.completionContractSha256,
|
|
runnerProfileJson: lockedRun.runnerProfileJson,
|
|
}, now: sql<Date>`clock_timestamp()`, ...(ownerLock ? {
|
|
leaseOwner: sql<string | null>`(select ${ownerLock.leaseOwner} from ${ownerLock})`,
|
|
leaseExpiresAt: sql<Date | null>`(select ${ownerLock.leaseExpiresAt} from ${ownerLock})`.mapWith(nativeRunFinalizations.leaseExpiresAt),
|
|
resultId: sql<string | null>`(select ${ownerLock.resultId} from ${ownerLock})`,
|
|
} : {}), ...(recovery ? {
|
|
checkpointHeader: sql<Record<string, unknown> | null>`(select material from ${nativeRunnerCheckpoints}
|
|
where ${nativeRunnerCheckpoints.runId} = ${this.#binding.runId}
|
|
and ${nativeRunnerCheckpoints.companyId} = ${this.#binding.companyId}
|
|
and ${nativeRunnerCheckpoints.issueId} = ${this.#binding.issueId}
|
|
and ${nativeRunnerCheckpoints.part} = 'header')`,
|
|
} : {}), ...(publicationIssue ? { publicationIssue: sql<NativeTaskSessionPublicationIssue>`(select jsonb_build_object(
|
|
'id', ${publicationIssue.id}, 'companyId', ${publicationIssue.companyId}, 'executionRunId', ${publicationIssue.executionRunId},
|
|
'conversationAgentId', ${publicationIssue.conversationAgentId}, 'conversationSessionGeneration', ${publicationIssue.conversationSessionGeneration}) from ${publicationIssue})` } : {}),
|
|
}).from(lockedRun).limit(1)
|
|
.then((rows) => rows[0] ?? null);
|
|
const run = selected?.run;
|
|
this.#assertActive(options);
|
|
if (owner && !selected) throw new Error("native_runner_checkpoint_owner_lost");
|
|
if (!run || !this.#matchesPersistedBinding(run)) {
|
|
throw new Error("native_session_checkpoint_binding_mismatch");
|
|
}
|
|
// The run row lock may have waited beyond our lease. Generation cannot
|
|
// change while we hold the coordinator, but wall-clock expiry still can.
|
|
if (owner && selected) await validateNativeRunnerCheckpointOwner(tx, owner,
|
|
{ leaseOwner: selected.leaseOwner ?? null, leaseExpiresAt: selected.leaseExpiresAt ?? null,
|
|
resultId: selected.resultId ?? null, now: selected.now }, !snapshot.semanticResult);
|
|
const header = recovery && selected?.checkpointHeader
|
|
? inspectNativeRunnerUpgradeHeader(this.#binding, selected.checkpointHeader) : null;
|
|
if (header && (header.normalizedSessionId !== identity.sessionId || header.runnerInstanceId !== this.#binding.sourceInstanceId)) {
|
|
throw new Error("native_session_checkpoint_prp_binding_mismatch");
|
|
}
|
|
const profile: Record<string, unknown> = {
|
|
...record(run.runnerProfileJson),
|
|
sessionCheckpoint: structuredClone(snapshot) as unknown as Record<string, unknown>,
|
|
...(recovery ? { nativeControllerRecovery: createNativeControllerRecovery(snapshot, recovery.compatibility,
|
|
header ? { runId: this.#binding.runId, runnerInstanceId: header.runnerInstanceId,
|
|
normalizedSessionId: header.normalizedSessionId } : null) } : {}),
|
|
};
|
|
// Driver/live snapshots may already describe a terminal result before
|
|
// completeRun accepts it. Persist that observation without a handled
|
|
// receipt; the existing post-acceptance checkpoint publishes the pointer.
|
|
if (publication && selected?.resultId) {
|
|
const receipt = await publishNativeTaskSessionInTransaction(tx, { binding: this.#binding, context: publication,
|
|
snapshot, run, issue: selected.publicationIssue ?? null, resultId: selected.resultId ?? null,
|
|
recoveryReady: !recovery || header !== null });
|
|
profile[NATIVE_TASK_SESSION_PUBLICATION_KEY] = receipt;
|
|
if (Buffer.byteLength(JSON.stringify({ nativeControllerRecovery: profile.nativeControllerRecovery,
|
|
[NATIVE_TASK_SESSION_PUBLICATION_KEY]: receipt })) > NATIVE_CONTROLLER_RECOVERY_MAX_BYTES) {
|
|
throw new Error("native_task_session_publication_metadata_too_large");
|
|
}
|
|
}
|
|
await tx.update(heartbeatRuns).set({
|
|
runnerProfileJson: profile,
|
|
sessionIdAfter: snapshot.providerSessionId ?? snapshot.sessionId,
|
|
nativePhase: snapshot.semanticResult ? "workspace_finalizing" : "observed",
|
|
nativePhaseUpdatedAt: new Date(),
|
|
updatedAt: new Date(),
|
|
}).where(eq(heartbeatRuns.id, this.#binding.runId));
|
|
this.#assertActive(options);
|
|
});
|
|
}
|
|
|
|
async appendEvent(value: NativeRunEvent | PrpEvent, options?: { signal: AbortSignal; deferPostCommitObservers?: true; streaming?: true }) {
|
|
const eventType = (value as { eventType?: unknown }).eventType;
|
|
return trackRunIntake(this.#binding.runId, "received", typeof eventType === "string" ? eventType : "unknown",
|
|
() => this.#appendEvent(value, options));
|
|
}
|
|
|
|
async #appendEvent(value: NativeRunEvent | PrpEvent, options?: { signal: AbortSignal; deferPostCommitObservers?: true; streaming?: true }) {
|
|
const persistenceStartedAt = Date.now(), persistenceClock = performance.now();
|
|
this.#assertActive(options);
|
|
if (!isPrpEvent(value)) throw new Error("native_legacy_event_not_supported");
|
|
const validated = validatePrpEvent(value);
|
|
if (!validated.ok) throw new Error(`native_event_schema_invalid:${validated.issues[0]?.message ?? "unknown"}`);
|
|
let event = this.#identityRedactor.redact(validated.event);
|
|
if (event.runId !== this.#binding.runId || (this.#sessionId && event.normalizedSessionId !== this.#sessionId)) {
|
|
throw new Error("native_event_binding_mismatch");
|
|
}
|
|
const expectedSourceInstanceId = event.sourceKind === "control_plane"
|
|
? this.#binding.controlPlaneSourceInstanceId
|
|
: this.#binding.sourceInstanceId;
|
|
if (event.sourceInstanceId !== expectedSourceInstanceId) {
|
|
throw new Error("native_event_source_binding_mismatch");
|
|
}
|
|
if (options?.deferPostCommitObservers && (
|
|
!["turn.completed", "turn.interrupted", "turn.cancelled"].includes(event.eventType)
|
|
|| !event.turnId || event.payload.providerTerminalObserved === false
|
|
)) throw new Error("native_deferred_observer_terminal_required");
|
|
const terminalItem = /^item\.(completed|failed|cancelled)$/.test(event.eventType);
|
|
const terminalTurn = /^(turn|session)\.(completed|failed|cancelled|interrupted|closed)$/.test(event.eventType);
|
|
if ((event.eventType === "item.delta" || terminalItem || terminalTurn) && (this.#identityRedactor.values.length > 0 || this.#identityRedactor.secretValues.length > 0)) {
|
|
const key = `${event.sourceInstanceId}:${event.sourceEventId}`;
|
|
const cached = this.#redactedDeltas.get(key);
|
|
const originalSha = nativeSha256(validated.event);
|
|
if (cached) {
|
|
if (cached.originalSha !== originalSha) throw new Error("native_event_source_payload_conflict");
|
|
event = cached.event;
|
|
} else {
|
|
const stream = `${event.sourceInstanceId}:${event.turnId}:${event.itemId}`;
|
|
event = { ...event, payload: event.eventType === "item.delta"
|
|
? this.#identityRedactor.delta(stream, validated.event.payload, event.itemId)
|
|
: this.#identityRedactor.settleDeltas(
|
|
terminalTurn ? (event.eventType.startsWith("session.") ? `${event.sourceInstanceId}:` : `${event.sourceInstanceId}:${event.turnId}:`) : stream,
|
|
event.payload, terminalTurn,
|
|
),
|
|
};
|
|
// Retries must use the same redacted payload without consuming a delta twice.
|
|
const bytes = Buffer.byteLength(JSON.stringify(event));
|
|
this.#redactedDeltas.set(key, { event, originalSha, bytes });
|
|
this.#redactedDeltaBytes += bytes;
|
|
// Match the bounded runner transcript retry window; large tool output
|
|
// also has a byte cap so long runs cannot retain another full transcript.
|
|
while (this.#redactedDeltas.size > IDENTITY_DELTA_RETRY_WINDOW || this.#redactedDeltaBytes > IDENTITY_DELTA_RETRY_BYTES) {
|
|
const oldest = this.#redactedDeltas.keys().next().value!;
|
|
this.#redactedDeltaBytes -= this.#redactedDeltas.get(oldest)!.bytes;
|
|
this.#redactedDeltas.delete(oldest);
|
|
}
|
|
}
|
|
}
|
|
event = redactRunnerApiEvent(event);
|
|
const observerKey = JSON.stringify([event.sourceInstanceId, event.sourceEventId]);
|
|
const input: AppendHeartbeatRunEventInput = {
|
|
companyId: this.#binding.companyId,
|
|
runId: this.#binding.runId,
|
|
agentId: this.#binding.agentId,
|
|
eventType: event.eventType,
|
|
stream: "system",
|
|
level: event.eventType.includes("failed") ? "error" : "info",
|
|
payload: { prpEvent: event as unknown as Record<string, unknown> },
|
|
nativeSource: {
|
|
sourceInstanceId: event.sourceInstanceId,
|
|
sourceEventId: event.sourceEventId,
|
|
sourceSeq: event.sourceSeq,
|
|
protocolSchemaVersion: event.schemaVersion,
|
|
canonicalPayload: event as unknown as Record<string, unknown>,
|
|
},
|
|
assertWritable: () => this.#assertActive(options),
|
|
};
|
|
if (this.pipelinedEventTypes.has(event.eventType) && !options?.deferPostCommitObservers) {
|
|
return this.#appendStreamingEvent({ event, input, options, startedAtMs: persistenceStartedAt, startedClock: persistenceClock },
|
|
options?.streaming === true);
|
|
}
|
|
// Every other event commits after each delta appended before it.
|
|
if (this.#streamingEventsPending > 0) await this.#flushStreamingEvents();
|
|
this.#streamedSinceBoundary = false;
|
|
this.#assertActive(options);
|
|
const pendingObservation = this.#deferredEventObservers.get(observerKey);
|
|
const persisted = await appendHeartbeatRunEvent(this.#db, input);
|
|
const committedAtMs = Date.now();
|
|
this.#assertActive(options);
|
|
const persistenceEndedAt = persistenceStartedAt + performance.now() - persistenceClock;
|
|
let observation = pendingObservation ?? this.#deferredEventObservers.get(observerKey);
|
|
if (!observation) observation = this.#observePersistedEvent(event, persisted, persistenceStartedAt, persistenceEndedAt, committedAtMs);
|
|
if (options?.deferPostCommitObservers) {
|
|
this.#deferredEventObservers.set(observerKey, observation);
|
|
void observation.then(() => {
|
|
if (this.#deferredEventObservers.get(observerKey) === observation) this.#deferredEventObservers.delete(observerKey);
|
|
}, error => {
|
|
this.#deferredObserverFailure ??= { error };
|
|
if (this.#deferredEventObservers.get(observerKey) === observation) this.#deferredEventObservers.delete(observerKey);
|
|
});
|
|
} else {
|
|
await observation;
|
|
}
|
|
return {
|
|
cursor: persisted.row.seq,
|
|
highestContiguousSourceSeq: persisted.highestContiguousSourceSeq,
|
|
disposition: persisted.disposition,
|
|
};
|
|
}
|
|
|
|
async #observePersistedEvent(
|
|
event: PrpEvent,
|
|
persisted: AppendHeartbeatRunEventResult,
|
|
persistenceStartedAt: number,
|
|
persistenceEndedAt: number,
|
|
committedAtMs: number,
|
|
): Promise<void> {
|
|
try { await this.#onEventPersistence?.(event, persistenceStartedAt, persistenceEndedAt); } catch {}
|
|
if (persisted.disposition === "committed") {
|
|
recordRunEventCommitted(event.emittedAt, committedAtMs);
|
|
try {
|
|
publishLiveEvent({
|
|
companyId: this.#binding.companyId,
|
|
type: "heartbeat.run.event",
|
|
payload: {
|
|
runId: this.#binding.runId,
|
|
agentId: this.#binding.agentId,
|
|
issueId: this.#binding.issueId,
|
|
seq: persisted.row.seq,
|
|
eventType: persisted.row.eventType,
|
|
stream: persisted.row.stream,
|
|
level: persisted.row.level,
|
|
payload: persisted.row.payload,
|
|
},
|
|
});
|
|
} catch {
|
|
}
|
|
await this.#onCommittedEvent?.(event, persisted.row.seq);
|
|
} else {
|
|
// A recovered runner may replay the event whose durable side effects
|
|
// parked the prior attempt. Do not repeat those effects, but let the
|
|
// embedding runtime refresh observational state before appendEvent
|
|
// returns to its synchronous governed-wait boundary.
|
|
await this.#onDuplicateEvent?.(event, persisted.row.seq);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Queues a text delta for the next batch. A caller that waits for each
|
|
* receipt (no `streaming`) commits at once. Deltas up to the first one with
|
|
* text after any other event also commit at once.
|
|
* Later streaming deltas wait at most the batch time, or until the batch is full.
|
|
*/
|
|
#appendStreamingEvent(pending: Omit<PendingStreamingEvent, "resolve" | "reject">, streaming: boolean): Promise<AppendReceipt> {
|
|
return new Promise<AppendReceipt>((resolve, reject) => {
|
|
this.#streamingBatch.push({ ...pending, resolve, reject });
|
|
this.#streamingEventsPending += 1;
|
|
if (pending.event.eventType !== "item.delta") this.#streamedSinceBoundary = false;
|
|
const flushNow = !streaming || !this.#streamedSinceBoundary || this.#streamingBatch.length >= STREAMING_EVENT_BATCH_MAX;
|
|
if (typeof pending.event.payload.text === "string" && pending.event.payload.text.length > 0) {
|
|
this.#streamedSinceBoundary = true;
|
|
}
|
|
if (flushNow) {
|
|
void this.#flushStreamingEvents();
|
|
} else {
|
|
this.#streamingTimer ??= setTimeout(() => { void this.#flushStreamingEvents(); }, this.#streamingBatchMs);
|
|
}
|
|
});
|
|
}
|
|
|
|
flushStreamingEvents(): void {
|
|
void this.#flushStreamingEvents();
|
|
}
|
|
|
|
/** Commits the queued deltas. Resolves after every earlier batch has settled, and never rejects. */
|
|
#flushStreamingEvents(): Promise<void> {
|
|
if (this.#streamingTimer !== null) clearTimeout(this.#streamingTimer);
|
|
this.#streamingTimer = null;
|
|
if (this.#streamingBatch.length > 0 && !this.#streamingFlushQueued) {
|
|
this.#streamingFlushQueued = true;
|
|
this.#streamingTail = this.#streamingTail.then(async () => {
|
|
this.#streamingFlushQueued = false;
|
|
const batch = this.#streamingBatch;
|
|
this.#streamingBatch = [];
|
|
try { await this.#commitStreamingEvents(batch); }
|
|
finally { this.#streamingEventsPending -= batch.length; }
|
|
});
|
|
}
|
|
return this.#streamingTail;
|
|
}
|
|
|
|
/**
|
|
* One transaction for the batch. Each committed row is then observed in
|
|
* order; an observer failure rejects only that delta's receipt, and the
|
|
* later rows are still observed.
|
|
*/
|
|
async #commitStreamingEvents(batch: PendingStreamingEvent[]): Promise<void> {
|
|
let receipts: AppendHeartbeatRunEventResult[];
|
|
try {
|
|
const assertWritable = () => { for (const pending of batch) this.#assertActive(pending.options); };
|
|
receipts = await appendHeartbeatRunEventBatch(this.#db, batch.map(pending => pending.input), assertWritable);
|
|
assertWritable();
|
|
} catch (error) {
|
|
for (const pending of batch) pending.reject(error);
|
|
return;
|
|
}
|
|
const committedAtMs = Date.now();
|
|
for (const [index, pending] of batch.entries()) {
|
|
const persisted = receipts[index]!;
|
|
const endedAt = pending.startedAtMs + performance.now() - pending.startedClock;
|
|
try {
|
|
await this.#observePersistedEvent(pending.event, persisted, pending.startedAtMs, endedAt, committedAtMs);
|
|
} catch (error) {
|
|
pending.reject(error);
|
|
continue;
|
|
}
|
|
pending.resolve({ cursor: persisted.row.seq, highestContiguousSourceSeq: persisted.highestContiguousSourceSeq,
|
|
disposition: persisted.disposition });
|
|
}
|
|
}
|
|
|
|
async replayEvents(input: ReplayControlPlaneEventsInput) {
|
|
if (
|
|
input.runId !== this.#binding.runId
|
|
|| ![this.#binding.sourceInstanceId, this.#binding.controlPlaneSourceInstanceId].includes(input.sourceInstanceId)
|
|
) {
|
|
throw new Error("native_replay_binding_mismatch");
|
|
}
|
|
if (this.#streamingEventsPending > 0) await this.#flushStreamingEvents();
|
|
const rows = await this.#db
|
|
.select({ payload: heartbeatRunEvents.payload, sourceSeq: heartbeatRunEvents.sourceSeq })
|
|
.from(heartbeatRunEvents)
|
|
.where(and(
|
|
eq(heartbeatRunEvents.runId, this.#binding.runId),
|
|
eq(heartbeatRunEvents.sourceInstanceId, input.sourceInstanceId),
|
|
gt(heartbeatRunEvents.sourceSeq, input.afterSourceSeq),
|
|
))
|
|
.orderBy(asc(heartbeatRunEvents.sourceSeq))
|
|
.limit(Math.max(1, Math.min(input.limit, 1_000)));
|
|
const events = rows.flatMap((row) => {
|
|
const candidate = row.payload?.prpEvent;
|
|
const parsed = validatePrpEvent(candidate);
|
|
return parsed.ok ? [parsed.event] : [];
|
|
});
|
|
let cursor = input.afterSourceSeq;
|
|
for (const event of events) {
|
|
if (event.sourceSeq === cursor + 1) cursor += 1;
|
|
else if (event.sourceSeq > cursor + 1) break;
|
|
}
|
|
return { events, highestContiguousSourceSeq: cursor };
|
|
}
|
|
|
|
/**
|
|
* Proves from durable rows, across every runner instance, that this run has
|
|
* no provider event, source-sequenced runner event, tool invocation, or
|
|
* accepted result. Any such row, or a read failure, denies the proof.
|
|
*/
|
|
async provesNoRunProviderWork(options: { signal: AbortSignal }): Promise<boolean> {
|
|
options.signal.throwIfAborted();
|
|
if (this.#streamingEventsPending > 0) await this.#flushStreamingEvents();
|
|
const { companyId, runId } = this.#binding;
|
|
const providerEvents = sql.join([...NATIVE_PROVIDER_DURABLE_EVENT_TYPES].map(value => sql`${value}`), sql`, `);
|
|
const result = await this.#db.execute(sql`select
|
|
exists (select 1 from ${heartbeatRunEvents} event where event.company_id = ${companyId} and event.run_id = ${runId}
|
|
and (event.source_event_id is not null or event.source_instance_id is not null
|
|
or event.event_type in (${providerEvents})
|
|
or event.event_type ~ '^(turn|item|tool|semantic_tool|run[.]result)[.]')) as "providerEvent",
|
|
exists (select 1 from ${toolInvocations} invocation where invocation.company_id = ${companyId}
|
|
and invocation.run_id = ${runId}) as "toolInvocation",
|
|
exists (select 1 from ${nativeRunResults} result where result.company_id = ${companyId}
|
|
and result.run_id = ${runId}) as "acceptedResult",
|
|
exists (select 1 from ${nativeRunFinalizations} coordinator where coordinator.run_id = ${runId}
|
|
and coordinator.result_id is not null) as "finalizedResult"`);
|
|
options.signal.throwIfAborted();
|
|
const rows = (Array.isArray(result) ? result : (result as { rows?: unknown[] }).rows ?? []) as Array<Record<string, unknown>>;
|
|
const row = rows[0];
|
|
if (!row) return false;
|
|
return row.providerEvent === false && row.toolInvocation === false
|
|
&& row.acceptedResult === false && row.finalizedResult === false;
|
|
}
|
|
|
|
async completeRun(value: NativeRunResult | CompleteControlPlaneRunInput, options?: { signal: AbortSignal }): Promise<void> {
|
|
this.#assertActive(options);
|
|
if (this.#streamingEventsPending > 0) await this.#flushStreamingEvents();
|
|
if (this.#deferredEventObservers.size > 0 || this.#deferredObserverFailure) await this.#settleDeferredObservers(options);
|
|
value = redactRunnerApiPayloads(this.#identityRedactor.redact(value));
|
|
if (!isCompleteInput(value)) throw new Error("native_structured_result_required");
|
|
// Capture compatibility diagnostics before canonical validation removes
|
|
// legacy/non-actionable attention payloads. They are operator evidence,
|
|
// not part of the authoritative semantic result.
|
|
const normalizationDiagnostics = normalizePrpResultSignals(value.result);
|
|
const validated = validatePrpStructuredRunResult(value.result);
|
|
if (!validated.ok) throw new Error(`native_result_schema_invalid:${validated.issues[0]?.message ?? "unknown"}`);
|
|
assertTerminal(value.terminal);
|
|
if (validated.result.reportedWorkDisposition !== value.terminal.reportedWorkDisposition) {
|
|
throw new Error("native_result_terminal_disposition_mismatch");
|
|
}
|
|
const canonical = {
|
|
binding: this.#binding,
|
|
result: validated.result,
|
|
terminal: value.terminal,
|
|
turnId: value.turnId ?? null,
|
|
};
|
|
const canonicalSha256 = nativeSha256(canonical);
|
|
const serverFingerprint = nativeSha256({
|
|
runId: this.#binding.runId,
|
|
completionContractSha256: this.#binding.completionContractSha256,
|
|
canonicalSha256,
|
|
});
|
|
|
|
const insertedResult = await this.#db.transaction(async (tx) => {
|
|
// Status commit and snapshot publication lock coordinator → issue → run.
|
|
// A replay must follow that order too: holding the issue while waiting
|
|
// for the coordinator deadlocks a status commit's issue UPDATE lock.
|
|
const recovery = this.#nativeRecovery;
|
|
const owner = recovery ? await lockNativeRunnerCheckpointOwner(tx, recovery.owner) : null;
|
|
// Result insertion checks the task FK. Keep its parent lock before run.
|
|
await tx.select({ id: issues.id }).from(issues)
|
|
.where(and(eq(issues.id, this.#binding.issueId), eq(issues.companyId, this.#binding.companyId)))
|
|
.for("key share");
|
|
const run = await tx.select().from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, this.#binding.runId)).for("update").limit(1)
|
|
.then((rows) => rows[0] ?? null);
|
|
this.#assertActive(options);
|
|
if (!run || !this.#matchesPersistedBinding(run)) {
|
|
throw new Error("native_result_binding_mismatch");
|
|
}
|
|
if (recovery && owner) {
|
|
const [clock] = await tx.execute<{ now: Date }>(sql`select clock_timestamp() as now`);
|
|
await validateNativeRunnerCheckpointOwner(tx, recovery.owner, { ...owner, now: clock.now }, false);
|
|
}
|
|
|
|
const callerConditions = [eq(nativeRunResults.serverFingerprint, serverFingerprint)];
|
|
if (value.callerResultId) callerConditions.push(eq(nativeRunResults.callerResultId, value.callerResultId));
|
|
if (value.callerDedupeKey) callerConditions.push(eq(nativeRunResults.callerDedupeKey, value.callerDedupeKey));
|
|
const existing = await tx.select().from(nativeRunResults)
|
|
.where(and(eq(nativeRunResults.runId, this.#binding.runId), or(...callerConditions)))
|
|
.limit(1).then((rows) => rows[0] ?? null);
|
|
if (existing) {
|
|
this.#assertActive(options);
|
|
if (existing.canonicalSha256 !== canonicalSha256) throw new Error("structured_result_replay_conflict");
|
|
return false;
|
|
}
|
|
if (owner?.resultId) throw new Error("structured_result_replay_conflict");
|
|
const acceptedOutcome = value.terminal.runTerminalState === "failed" && value.terminal.reportedWorkDisposition === "done"
|
|
? deriveNativeAcceptedOutcome({ terminal: value.terminal,
|
|
...await readPersistedNativeFailureEvidence(tx as unknown as Db, run, value.turnId ?? null, value.terminal) })
|
|
: null;
|
|
const effectiveTerminal = applyNativeAcceptedOutcome(acceptedOutcome, value.terminal);
|
|
const resultJson = {
|
|
result: validated.result,
|
|
terminal: value.terminal,
|
|
...(acceptedOutcome ? { [NATIVE_ACCEPTED_OUTCOME_KEY]: acceptedOutcome } : {}),
|
|
normalizationDiagnostics: {
|
|
ignoredAttentionRequests: normalizationDiagnostics.ignoredAttentionRequests,
|
|
},
|
|
} as unknown as Record<string, unknown>;
|
|
await notifyNativeResultCommit(tx, this.#binding);
|
|
await notifyNativeWorkspaceFinalization(tx, this.#binding);
|
|
const inserted = await tx.insert(nativeRunResults).values({
|
|
companyId: this.#binding.companyId,
|
|
issueId: this.#binding.issueId,
|
|
runId: this.#binding.runId,
|
|
turnId: value.turnId ?? null,
|
|
completionContractId: this.#binding.completionContractId,
|
|
callerResultId: value.callerResultId ?? null,
|
|
callerDedupeKey: value.callerDedupeKey ?? null,
|
|
serverFingerprint,
|
|
schemaStatus: "accepted",
|
|
resultJson,
|
|
canonicalSha256,
|
|
}).returning().then((rows) => rows[0]);
|
|
if (!inserted) throw new Error("native_result_not_persisted");
|
|
await tx.insert(nativeRunFinalizations).values({
|
|
runId: this.#binding.runId,
|
|
companyId: this.#binding.companyId,
|
|
issueId: this.#binding.issueId,
|
|
phase: "workspace_finalizing",
|
|
resultId: inserted.id,
|
|
}).onConflictDoUpdate({
|
|
target: nativeRunFinalizations.runId,
|
|
set: {
|
|
phase: "workspace_finalizing",
|
|
resultId: inserted.id,
|
|
recoveryState: null,
|
|
recoveryRequestId: null,
|
|
failureCode: null,
|
|
failureDetail: null,
|
|
nextAttemptAt: null,
|
|
updatedAt: new Date(),
|
|
},
|
|
});
|
|
await tx.update(heartbeatRuns).set({
|
|
nativePhase: "workspace_finalizing",
|
|
nativePhaseUpdatedAt: new Date(),
|
|
resultJson: {
|
|
...record(run.resultJson),
|
|
// Publish the accepted contract with its durable receipt. Recovery
|
|
// may settle this run without the original adapter ever returning.
|
|
nativeTerminal: value.terminal,
|
|
prpTurnTerminalState: effectiveTerminal.turnTerminalState,
|
|
prpRunTerminalState: effectiveTerminal.runTerminalState,
|
|
prpReportedWorkDisposition: value.terminal.reportedWorkDisposition,
|
|
},
|
|
updatedAt: new Date(),
|
|
}).where(eq(heartbeatRuns.id, this.#binding.runId));
|
|
this.#assertActive(options);
|
|
return true;
|
|
});
|
|
if (insertedResult) crashPoint("native.result.after_accept_before_finalize");
|
|
if (insertedResult) { try { await this.#onResultCommitted?.(); } catch {} }
|
|
}
|
|
}
|