mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-02 16:58:52 +01:00
## Thinking Path > - Paperclip manages agents and their work. > - A provider integration must work through ordinary agent setup and task controls. > - The recorded Antigravity walkthrough exposed setup, delivery, and continuation failures. > - A repeatable check must verify real work and retain failed attempts. > - This pull request converts all 47 recorded steps into one fixed Product E2E journey. > - Maintainers can rerun the case and inspect independent delivery, cleanup, and accounting evidence. ## Linked Issues or Issue Description Builds on merged #18187, #18188, and #18189, and consumes the shared repairs from merged #18230 and the equivalent manual-policy declaration from #18222. Refs #18214 for the CI task wrapper. Refs #12503 and #14938 for related legacy adapter work. **Agent or provider** Google Antigravity native Runner with a saved managed Google subscription and the exact Low model. **Why this adapter is useful** A user must be able to add an agent, connect its account, and receive real task results across a follow-up. Picker visibility alone is insufficient. **How the agent is invoked** A fixed Playwright driver uses ordinary product controls. The agent runs through native ACP. Independent checks use public APIs, actual downloads, owned process observations, and native lifetime fences. ## What Changed - Register one explicit-only case: `antigravity-agent-journey.runner-antigravity.local.saved-subscription-two-turn`. - Map all 47 source steps and declare saved-account prerequisites, finite limits, and same-host macOS ARM64 scope. - Create an agent through the ordinary picker, connect the saved account, select Low, run Test, and wait for readiness. Save an instruction marker, deliver a file, and update it through an ordinary follow-up. - Require each run's visible completed file activity, exact downloaded bytes, committed Done result, same tagged conversation, distinct physical owner birth, released lease, and free native fences. Verify reload persistence. - Stop failed native runs that still own a retry. Replay an existing Stop with its durable request identity and wait for the matching audited acknowledgement. A terminal reservation without a native intent remains unconfirmed. - Keep private evidence in the existing result, report, dashboard, and accounting pipeline. Retain the paused QA agent and financial history while preserving the shared account and budget policies. - Journal only the ordinary wizard's future ID, target, name, intended harness and expected creator before forwarding its POST unchanged. Bind the response and interrupted recovery to exact identity reads; a pending 404 stays unconfirmed. - Serialize private resource snapshots through temporary-file fsync, atomic rename and directory fsync. Abort forwarding on storage failure and preserve legacy receipts. If later journal or diagnostic writes fail, retain the primary error, always close the browser, and attempt the ordinary failed report. - Add production-component browser controls and harden task-menu readiness, alias selection, scroll restoration, failure packaging, and one hermetic auth-test budget. - Wait for the existing GitHub recovery fixture to register its next deadline before asserting the original range; preserve its nested-transaction and zero-request checks. In the decision-expiry fixture, verify the exact saved expiry separately from the earlier global wake of another queue. ## Verification - Fresh registered acceptance passed on eval source `9060f3cd01b7c3445ecdf703d72e9cf30fe42b59` and merged serving product `61bd4ac6919c2309f766a25e62273b074cee3261`. It completed ordinary setup and two turns with native `.5` and `gemini-3.8-flash-low`. All 16 matchers, 14 checkpoints, and cleanup passed in **165,613 ms**. Actual downloads were **61 bytes** and **119 bytes**. Both turns passed their own run-bound browser activity checks and reload persistence. - Independent read-back confirms Done, a paused retained agent, the same connected saved default account, and no active owned run. Both accepted results have the same full tagged conversation and distinct primary process births. All 21 observed processes retired; both leases released and all three native fences were free after each turn. The selected `.5` checkpoints also showed equal agent/backend session IDs; this is an observed case requirement, not a generic ACP invariant. - Receipts report 339,273 input tokens, 7,224 output tokens, and 202,846 cached input tokens. Subscription prices are unavailable. Billing coverage remains incomplete, not free. - The normal report CLI passed. All 310 files from nine original attempts and two separate recoveries retained their hashes. The twelve current screenshots are byte-identical, and 194 local report links are contained and valid. The eight earlier reports were copied without regeneration. - Delivery source `1bf4fb04df04710b82844b3c9355767f46b5f68f` branches from `d3f2a60e795fc60d64c8b19d1eed4d48657d5492` and merges cleanly with current master `1d571de5f9f886d66e520800baec8fc2f67d0948`. All 41 prior `c8b332` authored file blobs remain identical; the 42nd path is the decision-expiry fixture contract correction. Creation ownership, the strict durable writer, and the ordinary successful workflow remain unchanged. Of 43 measured file blobs, 30 remain identical. The Antigravity oracle, artifact, billing and report gates and its suite-specific validation block remain unchanged. The actual retained agent matches its original creator; its original request `setupId` was not captured and is not reconstructed. - Later master changes include model-visible workspace guidance and rejected-terminal-report handling. Their bounded source assessment is separate: the first actual finish failed, then a same-turn replacement was accepted and committed. Later read-only results match both original native-result hashes, and the complete event catalogs have no `session.failed` event. Master #18228 also expands detection of explicit JSON file requests. The measured create/update-and-attach `.txt` task already required publication under both parsers; the publication validation gate itself is unchanged. Master #18240 changes remote workspace cache staging and adds an OpenCode index refresh. The selected local lane returns before those paths. Master #18213 adds optional numeric turn timing and trace boundaries. Its selected Antigravity model, text, IDs, result and retirement semantics remain unchanged in the bounded source review. Local diagnostic rows and awaits can change event ordinals and latency; the oracle checks relative semantic order. Collector coverage and latency improvement remain outside this proof. This does not claim that the whole current runtime is byte-identical to serving `61bd`, or relabel the measured result as a new run. - The adopted upstream cache controls passed 3/3 with pinned real Turbo. Forced work disables local and remote reads and writes; ordinary work reuses local results. The original genuine-pnpm/Turbo controls remain historical to `9060`'s earlier write-only policy. The duplicate cache patch is superseded by #18230. Its qualification-only pnpm addition is removed because the adopted upstream controls do not require it. - The E2E typecheck, map checks and 277-control replay are carried from the unchanged eval source paths. That replay passed, including the 183 Antigravity controls, catalog/connection checks and the separate product-journey validator. The carried creation controls include 91 config/recovery cases. The final launcher suite passed 19/19, including five real campaign finalization fault cases; the report suite passed 7/7. These final checks did not rerun the earlier 277-control group. The canonical production-component browser spec passed in 27.4 s under its unchanged 60 s limit before the replay. Four paused-composer cases and the product base's build/typecheck plus 376 focused regressions were verified earlier. - The shipped wizard and actual API client cover persistence before forwarding, lost response JSON, foreign/malformed requests, wrong response identity/creator and cleanup-error preservation. Real filesystem controls failed 5/5 before the writer repair and passed 5/5 afterward, preserving the old journal on partial-write, temporary-file sync and rename faults. Three persistent-sync campaign controls failed before the finalization repair and passed afterward. All five final campaign fault cases preserve the primary failure, cleanup failure, usage and failed report while attempting browser closure. The strict journal still blocks the next mutation. These are provider-free ownership controls; the Google task proof remains the original `9060` → `61bd` acceptance. - The decision restart check passed in the local 20-case fixture run. A current-source real-PostgreSQL rollback control reproduced the exact 90,000 ms earlier global wake: the old equality rejected it, while the exact durable expiry and new future-wake bound passed. The original 60 s open-state, exact-timestamp, continuation and quiet checks remain. The broader local run was **FAILED: 19 passed / 1 failed**, with a 15 s timeout and a 30 s cleanup timeout in an unchanged timestamp-pagination case. That case passed in canonical `c8b332` CI; the local timeout cause remains inconclusive. An extra local server typecheck failed against stale cached Runner declarations; it did not check this excluded test file. Both limits remain recorded for fresh canonical CI. - A broader local GitHub recovery group passed 21/22. Its unchanged pagination case observed an unexpected config request; the log does not establish the cause. That result remains retained, and fresh current-head CI is the final broader gate. - Exact delivery-head CI completed with 55 successes, two skips, and one optional neutral review. Required `ci / verify` and `ci / e2e`, build, typecheck, and Runner checks passed. Fresh Greptile is 5/5 with zero unresolved threads. Optional Paperclip is neutral 4/5; its carried recommendations are dispositioned against the public Stop contract and selected live identity evidence. Seven earlier converted attempts retain their failed grades and partial evidence. Historical Paid8 and its later read-only per-run UI observation remain separate from the fresh acceptance above. Unknown prices and the older partial startup accounting remain explicit. Full lineage and raw evidence remain private in the normal report bundle. ## Risks - This case requires an authorized saved personal default Google subscription and finite operator candidate admission. It does not test fresh OAuth or establish global qualification. - The physical observer supports a same-host loopback macOS ARM64 target. Cloud, Linux, and other models remain outside this case. - A known-cost stop cannot cap missing prices or in-flight subscription charges. Existing operator policies remain unchanged. - Raw account/native identities stay private. Missing retirement proof keeps resources retained. The selected cleanup mode does not test agent purge. ## Model Used OpenAI Codex (GPT-6). The host did not expose the exact model revision or context limit. The model used tools for code edits, tests, browser automation, and review. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
345 lines
22 KiB
TypeScript
345 lines
22 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { eq, sql } from "drizzle-orm";
|
|
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { activityLog, agents, companies, createDb, subscribeDatabaseWork, decisionBundles, decisionEffectExecutions, decisions,
|
|
decisionTargetIssues, heartbeatRuns, issues } from "@paperclipai/db";
|
|
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
|
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
|
|
import { decisionService } from "../services/decisions.js";
|
|
import { registerDecisionExpiryWork } from "../services/decision-expiry-work.js";
|
|
import { registerDecisionContinuationWork } from "../services/decision-continuation-work.js";
|
|
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
|
|
import { idleWorkSnapshot } from "../services/task-admission.js";
|
|
import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
|
|
|
|
const externalUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_DECISION_EXPIRY_TEST_DATABASE_URL");
|
|
const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTestSupport();
|
|
(support.supported ? describe : describe.skip)("decision expiry worker", () => {
|
|
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
|
|
let db: ReturnType<typeof createDb>;
|
|
let companyId: string, agentId: string, issueId: string, runId: string;
|
|
let coordinator: ReturnType<typeof createDeliveryWorkCoordinator> | undefined;
|
|
let draining: boolean;
|
|
const errors: unknown[] = [];
|
|
const wake = vi.fn(async () => {});
|
|
const service = () => decisionService(db, { wakeOriginAgent: wake });
|
|
|
|
beforeAll(async () => {
|
|
if (!externalUrl) temporary = await startEmbeddedPostgresTestDatabase("decision-expiry-");
|
|
db = createDb(externalUrl ?? temporary!.connectionString, { maxConnections: 6, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 });
|
|
}, 30_000);
|
|
beforeEach(async () => {
|
|
process.env.PAPERCLIP_DECISION_SIGNING_SECRET = "0123456789abcdef0123456789abcdef";
|
|
companyId = randomUUID(); agentId = randomUUID(); issueId = randomUUID(); runId = randomUUID();
|
|
await db.insert(companies).values({ id: companyId, name: "Expiry", issuePrefix: `E${companyId.slice(0, 6)}`, requireBoardApprovalForNewAgents: false });
|
|
await db.insert(agents).values({ id: agentId, companyId, name: "Proposer", role: "engineer", status: "active", adapterType: "codex_local", adapterConfig: {}, runtimeConfig: {}, permissions: {} });
|
|
await db.insert(issues).values({ id: issueId, companyId, title: "Origin", status: "in_progress", priority: "medium", assigneeAgentId: agentId });
|
|
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", contextSnapshot: { issueId } });
|
|
await Promise.all(Array.from({ length: 6 }, () => db.execute(sql`select pg_sleep(0.01)`)));
|
|
draining = false; errors.length = 0; wake.mockReset();
|
|
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"], shouldAdvanceTime: true });
|
|
});
|
|
afterEach(async () => {
|
|
await coordinator?.stop(); coordinator = undefined;
|
|
vi.useRealTimers(); vi.restoreAllMocks(); vi.unstubAllEnvs();
|
|
await db.execute(sql`drop trigger if exists decision_expiry_fail on decisions`);
|
|
await db.execute(sql`drop function if exists decision_expiry_fail()`);
|
|
await db.execute(sql`drop trigger if exists decision_expiry_audit_fail on activity_log`);
|
|
await db.execute(sql`drop function if exists decision_expiry_audit_fail()`);
|
|
await db.delete(decisionEffectExecutions); await db.delete(decisionTargetIssues); await db.delete(decisions);
|
|
await db.delete(decisionBundles); await db.delete(activityLog); await db.delete(heartbeatRuns);
|
|
await db.delete(issues); await db.delete(agents); await db.delete(companies);
|
|
expect(errors).toEqual([]);
|
|
});
|
|
afterAll(async () => { await db?.$client.end({ timeout: 1 }); await temporary?.cleanup(); });
|
|
|
|
const actor = () => ({ type: "agent" as const, companyId, agentId, runId, source: "agent_jwt" as const });
|
|
function input(expiresAt: Date) {
|
|
return { companyId, agentId, runId, actor: actor(), title: "Decision", body: "Body", expiresAt,
|
|
continuationPolicy: "wake_origin_agent" as const, options: [{ id: "yes", label: "Yes", effects: [] }] };
|
|
}
|
|
const create = (at = new Date(Date.now() + 120_000)) => service().create(input(at));
|
|
async function start() {
|
|
coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => !draining,
|
|
canReconcile: () => true, onError: error => errors.push(error) });
|
|
const continuation = service(), expiry = service();
|
|
await registerDecisionContinuationWork(coordinator, continuation, () => !draining).ready;
|
|
await registerDecisionExpiryWork(coordinator, expiry, () => !draining).ready;
|
|
return { continuation, expiry };
|
|
}
|
|
async function quiet() {
|
|
await vi.waitFor(async () => {
|
|
await vi.advanceTimersByTimeAsync(30_000);
|
|
expect(idleWorkSnapshot().active).toBe(0); expect(coordinator!.nextWakeAt()).toBeNull();
|
|
}, { timeout: 5000 });
|
|
const reads = vi.spyOn(db, "select"), writes = vi.spyOn(db, "update"), executes = vi.spyOn(db, "execute");
|
|
await vi.advanceTimersByTimeAsync(60 * 60_000);
|
|
expect(reads).not.toHaveBeenCalled(); expect(writes).not.toHaveBeenCalled(); expect(executes).not.toHaveBeenCalled();
|
|
reads.mockRestore(); writes.mockRestore(); executes.mockRestore();
|
|
}
|
|
async function expired(id: string) {
|
|
await vi.waitFor(async () => {
|
|
await vi.advanceTimersByTimeAsync(30_000);
|
|
expect(await service().get(id)).toMatchObject({ status: "expired", metadata: { expiredReason: "ttl", continuationPending: false } });
|
|
}, { timeout: 5000 });
|
|
}
|
|
|
|
it("is quiet when empty, arms the real producer deadline, and leaves expired history quiet", async () => {
|
|
await start(); await quiet();
|
|
const deadline = new Date(Date.now() + 120_000);
|
|
const row = await create(deadline);
|
|
await vi.waitFor(async () => {
|
|
await vi.advanceTimersByTimeAsync(30_000);
|
|
expect(coordinator!.nextWakeAt()).toBe(deadline.getTime());
|
|
});
|
|
const reads = vi.spyOn(db, "select");
|
|
await vi.advanceTimersByTimeAsync(Math.max(0, deadline.getTime() - Date.now() - 1000));
|
|
expect(reads).not.toHaveBeenCalled(); reads.mockRestore(); expect(wake).not.toHaveBeenCalled();
|
|
await expired(row.id); await quiet(); expect(wake).toHaveBeenCalledTimes(1);
|
|
expect(await db.select().from(activityLog).where(eq(activityLog.action, "decision.expired"))).toHaveLength(1);
|
|
});
|
|
|
|
it.each(["single", "bundle"] as const)("arms expiry without waking continuation recovery for %s creation", async mode => {
|
|
await start(); await quiet();
|
|
const events: string[] = [];
|
|
const unsubscribe = subscribeDatabaseWork(db, DELIVERY_QUEUES.decisionContinuation, event => { events.push(event); });
|
|
try {
|
|
const deadline = new Date(Date.now() + 120_000);
|
|
const row = mode === "single" ? await create(deadline) : (await service().createBundle({
|
|
companyId, actor: actor(), agentId, runId, title: "Bundle", summary: "Summary", decisions: [input(deadline)],
|
|
})).decisions[0];
|
|
expect(events).toEqual([]);
|
|
await vi.waitFor(async () => {
|
|
await vi.advanceTimersByTimeAsync(1);
|
|
expect(coordinator!.nextWakeAt()).toBe(deadline.getTime());
|
|
});
|
|
expect(wake).not.toHaveBeenCalled();
|
|
await service().cancel(row.id, { actorType: "agent", actorId: agentId });
|
|
await quiet();
|
|
expect(events).toEqual(["intent", "settled"]);
|
|
expect(wake).toHaveBeenCalledTimes(1);
|
|
} finally { unsubscribe(); }
|
|
});
|
|
|
|
it("honors the configured expiry batch size", async () => {
|
|
vi.stubEnv("PAPERCLIP_DECISIONS_SWEEP_BATCH_SIZE", "2");
|
|
const seed = await create(); await db.delete(decisions).where(eq(decisions.id, seed.id));
|
|
await db.insert(decisions).values(Array.from({ length: 5 }, () => ({ ...seed, id: randomUUID(), expiresAt: new Date(Date.now() - 1000) })));
|
|
const recovery = service();
|
|
expect(await recovery.sweepTtlExpiry()).toEqual({ expired: 2 });
|
|
expect(await recovery.sweepTtlExpiry()).toEqual({ expired: 2 });
|
|
expect(await recovery.sweepTtlExpiry()).toEqual({ expired: 1 });
|
|
expect(wake).toHaveBeenCalledTimes(5);
|
|
});
|
|
|
|
it("continues a successful overdue backlog within one second instead of waiting for error retry", async () => {
|
|
const seed = await create(); await db.delete(decisions).where(eq(decisions.id, seed.id));
|
|
await db.insert(decisions).values(Array.from({ length: 101 }, () => ({ ...seed, id: randomUUID(), expiresAt: new Date(Date.now() - 1000) })));
|
|
await start();
|
|
expect(wake).toHaveBeenCalledTimes(100);
|
|
const next = coordinator!.nextWakeAt();
|
|
expect(next).not.toBeNull();
|
|
expect(next! - Date.now()).toBeLessThanOrEqual(1000);
|
|
await vi.advanceTimersByTimeAsync(2000);
|
|
await vi.waitFor(() => expect(wake).toHaveBeenCalledTimes(101));
|
|
await quiet();
|
|
});
|
|
|
|
it("rolls expiry back if its durable activity cannot be recorded", async () => {
|
|
const row = await create();
|
|
await db.update(decisions).set({ expiresAt: new Date(Date.now() - 1000), metadata: { ...row.metadata, retained: "unchanged" } }).where(eq(decisions.id, row.id));
|
|
await db.execute(sql`create function decision_expiry_audit_fail() returns trigger language plpgsql as $$ begin
|
|
raise exception 'expiry audit unavailable'; end $$`);
|
|
await db.execute(sql`create trigger decision_expiry_audit_fail before insert on activity_log
|
|
for each row when (NEW.action = 'decision.expired') execute function decision_expiry_audit_fail()`);
|
|
await expect(service().sweepTtlExpiry()).rejects.toMatchObject({ cause: { message: "expiry audit unavailable" } });
|
|
expect(await service().get(row.id)).toMatchObject({ status: "open", metadata: { retained: "unchanged" } });
|
|
expect(wake).not.toHaveBeenCalled();
|
|
expect(await db.select().from(activityLog).where(eq(activityLog.action, "decision.expired"))).toEqual([]);
|
|
await db.execute(sql`drop trigger decision_expiry_audit_fail on activity_log`);
|
|
expect(await service().sweepTtlExpiry()).toEqual({ expired: 1 });
|
|
expect(await service().get(row.id)).toMatchObject({ status: "expired", metadata: { retained: "unchanged" } });
|
|
expect(wake).toHaveBeenCalledTimes(1);
|
|
expect(await db.select().from(activityLog).where(eq(activityLog.action, "decision.expired"))).toHaveLength(1);
|
|
});
|
|
|
|
it("reconstructs a future expiry on restart and does not expire it early", async () => {
|
|
const row = await create(); const { expiry } = await start();
|
|
await vi.waitFor(async () => {
|
|
expect(await expiry.nextExpiryAt()).toBe(row.expiresAt.getTime());
|
|
// Another queue may reconcile sooner than this decision's expiry.
|
|
const next = coordinator!.nextWakeAt();
|
|
expect(next).not.toBeNull();
|
|
expect(next!).toBeGreaterThan(Date.now());
|
|
expect(next!).toBeLessThanOrEqual(row.expiresAt.getTime());
|
|
});
|
|
await vi.advanceTimersByTimeAsync(60_000);
|
|
expect((await service().get(row.id))?.status).toBe("open");
|
|
await expired(row.id); await quiet(); expect(wake).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("expires at the exact saved timestamp", async () => {
|
|
const row = await create();
|
|
expect(await service().sweepTtlExpiry(new Date(row.expiresAt.getTime() - 1))).toEqual({ expired: 0 });
|
|
expect(await service().sweepTtlExpiry(row.expiresAt)).toEqual({ expired: 1 });
|
|
expect((await service().get(row.id))?.status).toBe("expired"); expect(wake).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("replaces a later deadline when another decision is created and removes it after cancellation", async () => {
|
|
const later = await create(new Date(Date.now() + 600_000)); await start();
|
|
const earlier = await create();
|
|
await vi.waitFor(async () => { await vi.advanceTimersByTimeAsync(30_000); expect(coordinator!.nextWakeAt()).toBe(earlier.expiresAt.getTime()); });
|
|
await service().cancel(earlier.id, { actorType: "agent", actorId: agentId });
|
|
await vi.waitFor(async () => { await vi.advanceTimersByTimeAsync(30_000); expect(coordinator!.nextWakeAt()).toBe(later.expiresAt.getTime()); });
|
|
await service().cancel(later.id, { actorType: "agent", actorId: agentId });
|
|
await quiet(); expect(wake).toHaveBeenCalledTimes(2);
|
|
});
|
|
|
|
it("registers bundle creation inside its existing transaction", async () => {
|
|
await start(); await quiet(); const at = new Date(Date.now() + 120_000);
|
|
const bundle = await service().createBundle({ companyId, actor: actor(), agentId, runId, title: "Bundle", summary: "Summary",
|
|
decisions: [input(at), input(at)] });
|
|
await expired(bundle.decisions[0].id); await expired(bundle.decisions[1].id); await quiet();
|
|
expect(wake).toHaveBeenCalledTimes(2);
|
|
});
|
|
|
|
it("does not publish an outer rollback and learns an outer commit", async () => {
|
|
await start(); await quiet();
|
|
await expect(db.transaction(async tx => {
|
|
await service().create(input(new Date(Date.now() + 30_000)), tx as unknown as typeof db);
|
|
await vi.advanceTimersByTimeAsync(60_000); expect(wake).not.toHaveBeenCalled(); throw new Error("rollback");
|
|
})).rejects.toThrow("rollback");
|
|
await quiet(); expect(await db.select().from(decisions)).toHaveLength(0);
|
|
let id = "";
|
|
await db.transaction(async tx => {
|
|
id = (await service().create(input(new Date(Date.now() + 30_000)), tx as unknown as typeof db)).id;
|
|
await vi.advanceTimersByTimeAsync(60_000); expect(wake).not.toHaveBeenCalled();
|
|
});
|
|
await expired(id); await quiet(); expect(wake).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("retains first creation during drain without SQL until resume", async () => {
|
|
await start(); await quiet(); draining = true;
|
|
const row = await create(new Date(Date.now() + 30_000));
|
|
const reads = vi.spyOn(db, "select"); await vi.advanceTimersByTimeAsync(60_000);
|
|
expect(reads).not.toHaveBeenCalled(); reads.mockRestore(); expect(wake).not.toHaveBeenCalled();
|
|
draining = false; await expired(row.id); await quiet(); expect(wake).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("keeps a failed expiry retry through drain and preserves pending state", async () => {
|
|
const row = await create(new Date(Date.now() + 30_000)); const workers = await start();
|
|
const sweeps = [vi.spyOn(workers.expiry, "sweepTtlExpiry"), vi.spyOn(workers.continuation, "sweepContinuations")];
|
|
await db.execute(sql`create function decision_expiry_fail() returns trigger language plpgsql as $$ begin
|
|
if NEW.status = 'expired' then raise exception 'expiry unavailable'; end if; return NEW; end $$`);
|
|
await db.execute(sql`create trigger decision_expiry_fail before update on decisions for each row execute function decision_expiry_fail()`);
|
|
await vi.waitFor(async () => { await vi.advanceTimersByTimeAsync(30_000); expect(errors.length).toBeGreaterThan(0); });
|
|
draining = true; expect((await service().get(row.id))?.status).toBe("open");
|
|
await Promise.allSettled(sweeps.flatMap(sweep => sweep.mock.results.filter(result => result.type === "return").map(result => result.value)));
|
|
const reads = vi.spyOn(db, "select"); await vi.advanceTimersByTimeAsync(60_000);
|
|
expect(reads).not.toHaveBeenCalled(); reads.mockRestore();
|
|
await db.execute(sql`drop trigger decision_expiry_fail on decisions`);
|
|
draining = false; await expired(row.id); await quiet(); expect(wake).toHaveBeenCalledTimes(1);
|
|
for (const error of errors) expect(error).toMatchObject({ cause: { message: "expiry unavailable" } }); errors.length = 0;
|
|
});
|
|
|
|
it("leaves failed continuation delivery to its separate retry owner", async () => {
|
|
const row = await create(new Date(Date.now() + 30_000)); await start();
|
|
wake.mockRejectedValueOnce(new Error("wake unavailable"));
|
|
await expired(row.id); await quiet(); expect(wake).toHaveBeenCalledTimes(2);
|
|
expect(errors.every(error => String(error).includes("wake unavailable"))).toBe(true); errors.length = 0;
|
|
expect(await db.select().from(activityLog).where(eq(activityLog.action, "decision.expired"))).toHaveLength(1);
|
|
});
|
|
|
|
it("does not deliver terminal continuation debt from the TTL-only pass", async () => {
|
|
const row = await create();
|
|
await db.update(issues).set({ status: "cancelled" }).where(eq(issues.id, issueId));
|
|
await db.update(decisions).set({ status: "cancelled", metadata: { continuationPending: true } }).where(eq(decisions.id, row.id));
|
|
expect(await service().sweepTtlExpiry()).toEqual({ expired: 0 });
|
|
expect(wake).not.toHaveBeenCalled(); expect(await service().nextExpiryAt()).toBeNull();
|
|
});
|
|
|
|
it("does not recover stale running effects during TTL expiry", async () => {
|
|
const row = await create();
|
|
await db.update(decisions).set({ status: "decided", executionStatus: "running", chosenOptionId: "yes",
|
|
decidedByUserId: null, updatedAt: new Date(Date.now() - 120_000), expiresAt: new Date(Date.now() - 1000) })
|
|
.where(eq(decisions.id, row.id));
|
|
expect(await service().sweepTtlExpiry()).toEqual({ expired: 0 });
|
|
expect(await service().get(row.id)).toMatchObject({ status: "decided", executionStatus: "running" });
|
|
expect(wake).not.toHaveBeenCalled();
|
|
expect(await service().nextExpiryAt()).toBeNull();
|
|
});
|
|
|
|
it("pages past a failed candidate and retries it without repeating completed expirations", async () => {
|
|
const seed = await create(); await db.delete(decisions).where(eq(decisions.id, seed.id));
|
|
const ids = Array.from({ length: 101 }, (_, i) => `10000000-0000-4000-8000-${String(i).padStart(12, "0")}`);
|
|
await db.insert(decisions).values(ids.map(id => ({ ...seed, id, expiresAt: new Date(Date.now() - 1000) })));
|
|
await db.execute(sql`create function decision_expiry_fail() returns trigger language plpgsql as $$ begin
|
|
if NEW.id = '10000000-0000-4000-8000-000000000000' and NEW.status = 'expired' then raise exception 'expiry unavailable'; end if;
|
|
return NEW; end $$`);
|
|
await db.execute(sql`create trigger decision_expiry_fail before update on decisions for each row execute function decision_expiry_fail()`);
|
|
const recovery = service();
|
|
await expect(recovery.sweepTtlExpiry()).rejects.toMatchObject({ cause: { message: "expiry unavailable" } });
|
|
expect(wake).toHaveBeenCalledTimes(99);
|
|
expect((await service().get(ids.at(-1)!))?.status).toBe("open");
|
|
expect(await recovery.sweepTtlExpiry()).toEqual({ expired: 1 });
|
|
expect((await service().get(ids.at(-1)!))?.status).toBe("expired");
|
|
expect((await service().get(ids[0]))?.status).toBe("open"); expect(wake).toHaveBeenCalledTimes(100);
|
|
await db.execute(sql`drop trigger decision_expiry_fail on decisions`);
|
|
await start(); await quiet(); expect((await service().get(ids[0]))?.status).toBe("expired");
|
|
expect(wake).toHaveBeenCalledTimes(101);
|
|
expect(await db.select().from(activityLog).where(eq(activityLog.action, "decision.expired"))).toHaveLength(101);
|
|
});
|
|
|
|
it("learns another expiry created during delivery", async () => {
|
|
const first = await create(new Date(Date.now() + 30_000));
|
|
let secondId = "";
|
|
wake.mockImplementationOnce(async () => { secondId = (await create(new Date(Date.now() + 90_000))).id; });
|
|
await start(); await expired(first.id);
|
|
await vi.waitFor(() => expect(secondId).not.toBe(""));
|
|
await expired(secondId); await quiet(); expect(wake).toHaveBeenCalledTimes(2);
|
|
});
|
|
|
|
|
|
it("finishes an admitted expiry but leaves the next candidate for restart during shutdown", async () => {
|
|
const first = await create(), second = await create();
|
|
await db.update(decisions).set({ expiresAt: new Date(Date.now() - 1000) });
|
|
let release!: () => void;
|
|
const gate = new Promise<void>(resolve => { release = resolve; });
|
|
wake.mockImplementationOnce(async () => gate);
|
|
const starting = start();
|
|
let stopped = false;
|
|
let stopping: Promise<void>;
|
|
try {
|
|
await vi.waitFor(() => expect(wake).toHaveBeenCalledTimes(1));
|
|
stopping = coordinator!.stop().then(() => { stopped = true; });
|
|
await vi.advanceTimersByTimeAsync(60_000); expect(stopped).toBe(false);
|
|
} finally { release(); }
|
|
await starting; await stopping!; coordinator = undefined;
|
|
expect(wake).toHaveBeenCalledTimes(1); expect(stopped).toBe(true);
|
|
const states = await Promise.all([service().get(first.id), service().get(second.id)]);
|
|
expect(states.map(row => row!.status).sort()).toEqual(["expired", "open"]);
|
|
await start(); await quiet(); expect(wake).toHaveBeenCalledTimes(2);
|
|
});
|
|
|
|
|
|
it("pages past a full failed batch using database timestamp precision", async () => {
|
|
const seed = await create(); await db.delete(decisions).where(eq(decisions.id, seed.id));
|
|
const ids = Array.from({ length: 101 }, (_, i) => `20000000-0000-4000-8000-${String(i).padStart(12, "0")}`);
|
|
await db.insert(decisions).values(ids.map(id => ({ ...seed, id })));
|
|
await db.execute(sql`update decisions set expires_at = date_trunc('milliseconds', now() - interval '1 minute') + interval '456 microseconds'`);
|
|
await db.execute(sql`create function decision_expiry_fail() returns trigger language plpgsql as $$ begin
|
|
if NEW.id <> '20000000-0000-4000-8000-000000000100' and NEW.status = 'expired' then raise exception 'expiry unavailable'; end if;
|
|
return NEW; end $$`);
|
|
await db.execute(sql`create trigger decision_expiry_fail before update on decisions for each row execute function decision_expiry_fail()`);
|
|
const recovery = service();
|
|
await expect(recovery.sweepTtlExpiry()).rejects.toThrow("Decision expiry failed");
|
|
expect(await recovery.sweepTtlExpiry()).toEqual({ expired: 1 });
|
|
expect((await service().get(ids.at(-1)!))?.status).toBe("expired");
|
|
await db.execute(sql`drop trigger decision_expiry_fail on decisions`);
|
|
expect(await recovery.sweepTtlExpiry()).toEqual({ expired: 100 });
|
|
expect(await recovery.sweepTtlExpiry()).toEqual({ expired: 0 });
|
|
expect(wake).toHaveBeenCalledTimes(101);
|
|
});
|
|
|
|
});
|