fix(server): certify background deadlines for idle tenants (#19001)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Background services own future checks, retries, and recovery work.
> - An idle tenant can stop only when a durable wake covers its
remaining duties.
> - The current alarm catalog covers several domains but leaves these
owners blocked.
> - A saved future timestamp alone cannot prove that reconstruction or
admitted work has settled.
> - This pull request binds durable domain snapshots to the actual
registered worker revisions.
> - The tenant can hand off supported future duties and retain all
checks for uncertain or active work.

## Linked Issues or Issue Description

No matching public issue was found. Related work: [domain deadline
handoff #18656](https://github.com/paperclipai/paperclip/pull/18656),
[owned blocker diagnostics
#18632](https://github.com/paperclipai/paperclip/pull/18632), and
[completed history proof
#18646](https://github.com/paperclipai/paperclip/pull/18646). The
separate [native idle-session change
#18988](https://github.com/paperclipai/paperclip/pull/18988) covers
runtime retirement. [Far-future retry re-probes
#13534](https://github.com/paperclipai/paperclip/pull/13534) changes
recovery responsiveness after an upstream success; this change preserves
existing retry decisions.

**What happened?**

Future status-card, external-object, skill-sync, watchdog, retry, and
quota duties lacked complete owner-bound coverage in the idle deadline
proof. A completed quota task could also retain its monitor policy and
timestamp and remain blocked after the scheduler had disarmed it.

**Expected behavior**

A settled registered owner can hand off its exact supported future
deadline. Active work, dirty reconstruction, transaction uncertainty,
changed revisions, claims, unknown state, and unsupported duties keep
the tenant awake. Completed history retains its data and stops recurring
work when the owner has no remaining duty.

**Steps to reproduce**

1. Produce a supported future duty through its normal service.
2. Let the registered worker finish reconstruction and admitted work.
3. Request an owned idle report with the negotiated domain deadline
catalog.
4. Check the saved earliest deadline and generation before durable alarm
registration.
5. Stop and reconstruct the worker. Check that ordinary admission and
claims resume useful work once due.
6. Complete a quota task. Keep its saved policy and timestamp. Check
that linked unfinished work still blocks sleep and that settled history
does not.

**Paperclip version or commit**

The owned patch was qualified at
`699c8569fa34338dd75cdc5731381ec1e2efdb45`. Publication head
`491fac368ee72eaac8ae105d53e6bf6b305d8a6a` normally merges actual master
`039e0dad2c51c80251e1302a19c5566e039c357a`. All 43 owned files are
byte-identical. All 29 new upstream paths are preserved. The later
normal current-master integration is
`8c912e1ba4fc66397a7341ade59373af8075068f`, described separately below.

**Deployment mode**

Source checkout with real PostgreSQL 17 and a controlled local Node
process. No deployed alarm, tenant suspension, database suspension, or
fleet result is claimed.

## What Changed

- Add registered-worker reconciliation revisions and invalidate them on
stop.
- Keep status-card, external-object, and skill deadline interpretation
with their owners.
- Reuse the watchdog classifier against the supplied database snapshot.
- Validate the exact saved retry run and paired queued wake.
- Validate legacy quota source bindings and the current assignee or
reviewer policy.
- Preserve common issue scope, dependency, sibling, and state checks for
covered waits.
- Compose normalized owner snapshots within the existing bounded
deadline proof and recheck revisions after inspection.
- Bind actual service and worker instances from server startup. Missing
bindings preserve existing blockers.
- Retain completed quota policy and timestamps while independently
rejecting linked unfinished runs or wakes.
- Block unconsumed budget evaluation inputs through the owning queue
predicate. Accounting policy and settlement stay unchanged.
- Bind completed quota history through fixed-size UUID-array parameters,
preserve exact company/task/source associations, and guard external
references before the run-ID join.
- Batch watchdog subtrees and shared classifier facts without changing
the 64-query or two-second proof budget; preserve exact company pairing
for first-run evidence.
- Extend production-path regression controls and document supported
coverage and limits.

## Verification

Current integration head: `688abc6cac6016b9fb50e5832f81e2975ed5d49f`.
Fresh exact-head checks completed with **58 successes, three intentional
skips and one neutral review**, including aggregate `ci / verify`. The
complete current Greptile review is **5/5**. The complete current
Ponytail verdict is **Ship (4/5)**, with only optional cleanup of an
unused MCP proof input; both prior correctness findings are resolved.
All review threads and nested pages were inspected. The normal master
merges preserve the registered retry deadline owner and current startup
completion log after the same readiness await. The earlier focused
evidence below remains tied to its tested source revisions.


Current-master integration `8c912e1ba4fc66397a7341ade59373af8075068f`:

- Normally merge actual master
`46fb933b0155d183ce64a8bdc4950d1b58c926f6`. Every nonoverlapping tree
blob retains its owning parent across 14,044 paths. All 42 owner-only
files and 15 critical binding/proof/readiness files remain
byte-identical. Three automatic overlaps preserve the existing watchdog
binding, conservative unavailable-reader fallback and optional actual
owner arguments. The two scoped-deadline conflicts retain the entire
upstream resource-reservation/mid-pass admission/abort algorithm inside
the existing reconciliation revision/running/failure fence, with both
parent test sets.
- Actual TypeScript 7.0.2 server noEmit passed in 9.434 seconds, normal
source declaration layers in 12.102 seconds, and four selected
test/helper/config layers extending the actual CI configuration in 3.167
seconds. No compiler option weakening, heap override, donor declarations
or SDK replacement stub.
- Focused PG0 controls passed: 102 scheduler/proof/owner controls in
16.451 seconds, including all 21 scoped-deadline cases; 121 startup
controls; and all 107 unchanged instance-settings route cases in 6.456
seconds. The latter first hit a local prewire-guard
listener-registration race. Only the ignored guard was corrected to
register the same actual OS-bound server port immediately after native
listen returns. Closed, unknown, foreign, offhost and PG destinations
remain blocked. Original failure evidence is retained; product code and
assertions were unchanged.
- The exact current UI policy command now reports zero findings (0.362
seconds); its seven scanner controls pass. The earlier dependent PR used
an old scanner/source baseline under a newly enforcing trusted workflow
and reported 397 findings. Carrying the genuine current master resolves
that mismatch without editing unrelated UI sites or relaxing the gate.
- Every meaningful worker checked its executing PID/thread/preload hash
and matching receipt. PG0 controls opened no PostgreSQL sockets; all
owned processes exited. Original dependency-cache/DNS, ignored-harness
syntax/type and guard failures remain separate from product results.
- This is fresh semantic and focused runtime qualification, not a local
whole-repository or current-head PostgreSQL acceptance rerun. The
upstream workspace-busy parked-retry/terminal-holder notification path
remains unchanged by this merge and needs its separate current-graph
producer check. Historical six-case/scale results below stay tied to
their measured sources. A matching controlled default-cadence follow-up
is in #19191; no fresh current-head two-cycle or deployed suspension
claim follows from this merge.
- All 59 exact-head check contexts now pass (55 success, one neutral,
three intentional skips), plus the legacy security status. The complete
edited Greptile review is 5/5 for this exact commit, with all
root/nested pages inspected and no unresolved threads. Ponytail stopped
without completing its new turn; it supplied no new verdict or finding.
Prior actual findings remain addressed. Earlier scores/checks below
belong to their explicit earlier commits.


On frozen clean merged source `699c8569fa`:

- Real PostgreSQL acceptance: **6/6 passed**,83.483 seconds wall. Actual
retry producer creates the exact saved run/wake; stopped and
reconstructed owner resumes through current admission, one durable
start, real local process output and normal task completion. Includes
cancellation, drain arrival, retained quota history with queued-run/wake
negatives, watchdog review settlement and budget-input
empty/pending/consumed control using the actual owner.
- Affected coordinator, deadline, scoped-deadline, recovery and
composed-proof controls: **78/78 in five files passed**,32.114 seconds
wall, worker 1/no file parallelism.
- `pnpm exec tsc --noEmit -p server/tsconfig.json`: **passed**,17.467
seconds. Native TypeScript 7.0.2 and Node 24.22.2.
- PostgreSQL tests use one dedicated test database, matching
fixture/admin URLs, pool limit four, one worker, and no embedded
fallback. Every run recorded unchanged source hashes and a clean
checkout.
- The eight-second real-clock retry is a domain execution check. It is
below the Cloud minimum wake lead and is not a positive accepted hosted
sleep cycle.
- The completed quota-history product failure and original
fixture/protocol failures were preserved; the owning-reader fix passed a
real PostgreSQL red/green regression before the fresh merged six-case
pass.
- After runtime completion, the dedicated database had zero other
clients and no owned runtime processes. All three qualification process
PIDs exited. The coordinator independently audits and drops the
database.
- Comment-only cleanup has equal strict TypeScript parser ASTs across 15
files. The final lexical audit finds no added comments relative to
actual master. `git diff --check` passed.
- Earlier retry fixtures omitted responsible-user membership, advanced
JavaScript time past the real PostgreSQL lease clock, or produced stdout
without normal task completion. Corrected fixtures use real membership,
an eight-second real deadline, and ordinary task comment/completion. The
last case exposed legitimate disposition repair rather than duplicate
retry promotion.
- The quota and watchdog controls first ran before admitted work or the
existing 30-second reconstruction duty settled. The stronger tests
require an interim blocked report and then exact settled-owner proof.
Production deadlines were not changed. The separate
completed-quota-history defect was fixed in its reader and verified with
linked unfinished-run and wake controls.
- The status/object and skill owners reviewed the actual final startup,
route and post-backup bindings. Their domain source evidence carries
where token-equivalent. The master coordinator coalescing change was
reviewed separately. Historical domain PostgreSQL results are not
presented as fresh full-suite results on this head.

The later master merge adds retry predecessor cleanup checks under the
existing issue claim lock. The source audit confirms unchanged saved
deadlines and run/wake identities. The three actual retry
lifecycle/cancellation/drain cases passed on the batched candidate with
this parent (31.817 seconds). Those local dependency controls preceded
the current exact-head remote run. Native backup preservation and
TestOps changes from master are retained. No pass is inferred for
changed dependency behavior solely from unchanged owned files.

Review repair published as `643f1e7400`:

- The original reader returned `unknown` after seven actual watchdog
reviews settled across seven companies. The unchanged composed-report
regression passed after batching; the final reader passed in 61.841
seconds, including active queued-work and stopped-owner rejection.
- A separate two-company red/green control rejects terminal-run context
from another company as first-run grace evidence. Shared facts are
serialized once, with per-root IDs and review summaries.
- The affected recovery, proof and diagnostic unit controls passed 47/47
(14.575 seconds). Startup owner-contract fixtures passed 121/121 (10.589
seconds).
- Diagnostic PostgreSQL controls passed7/7 (12.406 seconds), including
the normal budget-input producer and its exact blocker reason. Initial
empty-state setup uses the same cleanup as per-case teardown when a
dedicated test database is reused.
- Actual repository `pnpm exec tsc --noEmit -p server/tsconfig.json`
passed 12.710 seconds with no heap override. Final source has no added
code comments; whitespace checks pass.
- The original query-budget failure, two-company discriminator, initial
cross-suite fixture failure and an interrupted incorrect local-driver
selector are retained separately. The interrupted run is not a pass.
Independent cleanup found zero owned clients or runtime processes.

Quota-scale repair published as `6696a37f8a`:

- The exact 10,000-row completed-history case reproduced
`MAX_PARAMETERS_EXCEEDED`:90,002 bound parameters exceeded the driver's
65,534 limit, and the composed report returned `unknown` despite settled
owners. Original failure and actual driver diagnostics are retained.
- Fixed pending-work queries use three typed UUID-array parameters plus
the result limit, keeping exact company/issue/source tuple bindings. The
primary run-ID column stays uncast; a guarded CASE validates the raw
external reference before conversion. The 10,000-row cap and
64-query/two-second proof budget are unchanged.
- The same 10,000-row composed-report case passed 18.860 seconds, with
unfinished run/wake rejection, malformed-reference safety and
conservative 10,001-row overflow. Its fixture derives retained history
from the actual quota producer and normal task completion, expands valid
persisted issue/source pairs, then starts the actual registered owners.
- The existing actual quota producer case passed 14.187 seconds,
including exact future deadline, retained completion history, unfinished
work, real foreign-company source references and noncanonical/malformed
references.
- Affected owner/proof controls passed 22/22 (26.444 seconds).
Production server noEmit passed 16.039 seconds.
- CI on 643 identified TS7034/TS7005 in the settled-watchdog fixture's
initially untyped collection. It is now explicitly typed. A separate
affected-entry semantic check extending the repository's actual
`server/src/__tests__/tsconfig.json` passed 15.093 seconds: six affected
tests, two owner files, ambient declarations and current imported
source, with unchanged strict/module/lib/path settings. The production
server config excludes that test directory and is not presented as
test-layer proof. No custom suppression or replacement SDK stub was
added.
- All runs were sequential with pool max 4, worker 1,
source/config/command hashes and cleared inherited
provider/LIVE/other-database variables. Cleanup found zero owned
database clients or local runtime processes. At prior head
`6696a37f8a5718cd0f79054969a0084462d41d47`, all required CI gates pass.
The exact-head inventory has 55 successes, one neutral review and three
intentional skips. Greptile is 5/5. The complete latest Ponytail verdict
confirms the quota finding is fixed; its only remaining note is optional
unused MCP proof state, not a behavior defect. All three review threads
are resolved. The earlier 643 result remains historical.

The repository-wide typecheck, tests, build and browser gates passed in
the prior `6696a37f8a5718cd0f79054969a0084462d41d47` CI run. The new
`8c912e1ba4fc66397a7341ade59373af8075068f` full CI also passes. They
were not run as a full local workspace command in the focused PostgreSQL
lease. Local evidence above uses bounded external databases and does not
claim embedded-cluster, live-provider or deployed-alarm qualification.

## Risks

- An unsupported or uncertain owner state must remain blocked. An
optimistic exemption could lose work while compute is stopped.
- Changes during reconstruction or inspection must invalidate the proof.
A memory-only timer is not durable alarm coverage.
- Current authorization, budgets, cancellation, accounting, and resource
ownership still apply on dispatch. The proof does not grant execution
authority.
- The supported writer model uses in-process transaction signals and
startup/resume reconstruction. Independent SQL writers and other
replicas need an explicit wake contract.
- Native, review, coalesced, and taskless retry variants remain
conservative until their owner cases qualify. Reviewer quota and hosted
alarm qualification remain open.
- The shared catalog remains opt-in. Legacy callers and missing owner
bindings retain their old blockers.

## Model Used

OpenAI `gpt-6.1-sol` was the configured model for the delegated service
implementations and reviews. OpenAI Codex, based on GPT-6, performed
managing review and integration. Both used repository tools and code
execution. The exact served backend snapshots and context-window limits
were not exposed.

## 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 and contains no internal
Paperclip ticket id
- [x] I have run tests locally and they pass on the final merged head
- [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 — exact current-head run passes
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups —
complete current-head review and all paginated threads inspected
- [ ] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-11-06 13:48:55 -06:00
1 parent 694076245f
commit 124b2cd0ad
47 files changed
+2120 -327

No files matched your search

@@ -169,3 +169,54 @@ it("retains a prompt paused wake when a new request preempts a far-future deadli
paused = false; await vi.advanceTimersByTimeAsync(30_000);
expect(run).toHaveBeenCalledTimes(2); expect(coordinator.nextWakeAt()).toBeNull();
});
it("fences a null-deadline source hint through drain until owner reconciliation succeeds", async () => {
vi.useFakeTimers();
let draining = false;
const owner = installDatabaseWorkSignals({
execute: vi.fn(async () => [{ status: "committed" }]),
transaction: async (callback: (tx: object) => Promise<unknown>) => callback({ execute: async () => [{ xid: "1" }] }),
});
coordinator = createDeliveryWorkCoordinator({ owner, canRun: () => !draining, canReconcile: () => true, onError: vi.fn() });
const run = vi.fn(async () => {});
const worker = registerDeadlineWork(coordinator, DELIVERY_QUEUES.statusCardEvaluation,
{ run, next: async () => null, canRun: () => !draining, retryMs: 30_000 });
expect(worker.reconciliationSnapshot().reconciled).toBe(false);
await worker.ready;
const settled = worker.reconciliationSnapshot();
expect(settled.reconciled).toBe(true);
draining = true;
expect(worker.reconciliationSnapshot()).toEqual(settled);
await owner.transaction(async tx => { await signalDatabaseWork(tx, DELIVERY_QUEUES.statusCardEvaluation); });
await vi.advanceTimersByTimeAsync(0);
expect(worker.reconciliationSnapshot().reconciled).toBe(false);
expect(worker.reconciliationSnapshot().revision).not.toBe(settled.revision);
await vi.advanceTimersByTimeAsync(90_000);
expect(run).toHaveBeenCalledOnce();
expect(worker.reconciliationSnapshot().reconciled).toBe(false);
draining = false;
await vi.advanceTimersByTimeAsync(30_000);
expect(worker.reconciliationSnapshot().reconciled).toBe(true);
expect(coordinator.nextWakeAt()).toBeNull();
await coordinator.stop();
expect(worker.reconciliationSnapshot().reconciled).toBe(false);
});
it("does not certify a source hint arriving during a successful evaluation", async () => {
vi.useFakeTimers();
const owner = installDatabaseWorkSignals({ execute: vi.fn(async () => []), transaction: vi.fn() });
coordinator = createDeliveryWorkCoordinator({ owner, canRun: () => true, onError: vi.fn() });
let release!: () => void;
const run = vi.fn(() => new Promise<void>(resolve => { release = resolve; }));
const worker = registerDeadlineWork(coordinator, DELIVERY_QUEUES.statusCardEvaluation,
{ run, next: async () => Date.now() + 60_000, canRun: () => true, retryMs: 30_000 });
await Promise.resolve(); await Promise.resolve(); await Promise.resolve(); await Promise.resolve();
await vi.waitFor(() => expect(run).toHaveBeenCalledOnce());
expect(worker.reconciliationSnapshot().reconciled).toBe(false);
worker.wake();
release(); await worker.ready;
expect(worker.reconciliationSnapshot().reconciled).toBe(false);
await vi.advanceTimersByTimeAsync(0);
release(); await vi.advanceTimersByTimeAsync(0);
expect(worker.reconciliationSnapshot().reconciled).toBe(true);
});
@@ -382,3 +382,20 @@ describe("delivery work coordinator", () => {
expect(vi.getTimerCount()).toBe(0);
});
});
it("invalidates owner reconciliation synchronously before awaiting an active stop", async () => {
const s = setup();
let finish!: () => void;
const onStop = vi.fn();
const worker = s.coordinator.register(DELIVERY_QUEUES.feedback, {
...task(), onStop,
run: async () => { await new Promise<void>(resolve => { finish = resolve; }); },
});
await vi.waitFor(() => expect(finish).toBeTypeOf("function"));
let stopped = false;
const stopping = s.coordinator.stop().then(() => { stopped = true; });
expect(onStop).toHaveBeenCalledOnce();
expect(stopped).toBe(false);
finish(); await worker.ready; await stopping;
expect(stopped).toBe(true);
});
@@ -0,0 +1,31 @@
import { expect, it } from "vitest";
import { projectIdleExternalObjectSchedule, type IdleExternalObjectRow } from "../services/external-object-idle-schedule.js";
const now = Date.UTC(2099, 0, 1);
function object(patch: Partial<IdleExternalObjectRow> = {}): IdleExternalObjectRow {
return { id: "object", companyId: "company", companyStatus: "active", revision: "row:1", eligible: true,
nextRefreshAt: new Date(now + 60_000), refreshStartedAt: null, refreshToken: null, ...patch };
}
it("retains the exact owner-eligible future deadline and leaves passive history alone", () => {
const row = object();
expect(projectIdleExternalObjectSchedule([row, object({ eligible: false, nextRefreshAt: new Date(now - 1) })], now, true))
.toMatchObject({ blocked: false, deadlines: [now + 60_000] });
expect(row.nextRefreshAt!.getTime()).toBe(now + 60_000);
expect(projectIdleExternalObjectSchedule([row], now, false)).toMatchObject({ blocked: false, deadlines: [] });
});
it.each([{ nextRefreshAt: null }, { nextRefreshAt: new Date(now) }, { nextRefreshAt: new Date(Number.NaN) }])(
"blocks due or invalid eligible obligations %j", patch => {
expect(projectIdleExternalObjectSchedule([object(patch)], now, true).blocked).toBe(true);
});
it.each([{ refreshToken: "token" }, { refreshStartedAt: new Date(now - 600_000) }])(
"never exempts active or ambiguous claims after eligibility removal %j", patch => {
expect(projectIdleExternalObjectSchedule([object({ ...patch, eligible: false })], now, false).blocked).toBe(true);
});
it("blocks an uninitialized owner and a bounded inspection overflow", () => {
expect(projectIdleExternalObjectSchedule([], now, null).blocked).toBe(true);
expect(projectIdleExternalObjectSchedule(Array.from({ length: 10_001 }, () => object({ eligible: false })), now, true).blocked).toBe(true);
});
@@ -42,7 +42,7 @@ const active: ExternalObjectResolveResult = { ok: true, snapshot: {
beforeAll(async () => {
if (url) await applyPendingMigrations(url);
if (!url) temp = await startEmbeddedPostgresTestDatabase("external-refresh-work-");
db = createDb(url ?? temp!.connectionString, { maxConnections: 6 });
db = createDb(url ?? temp!.connectionString, { maxConnections: 4 });
await db.execute(sql`truncate table ${companies} cascade`);
}, 90_000);
afterEach(async () => {
@@ -120,13 +120,17 @@ const active: ExternalObjectResolveResult = { ok: true, snapshot: {
it("settles empty, configured-idle and retained terminal history without recurring SQL or provider calls", async () => {
clock();
const svc = service(); await start(svc); await quiet();
const svc = service(); const worker = await start(svc); await quiet();
expect(await db.transaction(tx => svc.readIdleSchedule(tx, Date.now(), worker.reconciliationSnapshot)))
.toMatchObject({ blocked: false, deadlines: [] });
const selects = vi.spyOn(db, "select");
await vi.advanceTimersByTimeAsync(15 * 60_000);
expect(selects).not.toHaveBeenCalled(); expect(provider).not.toHaveBeenCalled();
const f = await fixture(); await svc.syncIssue(f.issueId);
await settle(async () => (await row(f.companyId))?.isTerminal === true); await quiet();
expect((await row(f.companyId)).statusKey).toBe("done");
expect(await db.transaction(tx => svc.readIdleSchedule(tx, Date.now(), worker.reconciliationSnapshot)))
.toMatchObject({ blocked: false, deadlines: [] });
selects.mockClear(); provider.mockClear();
await vi.advanceTimersByTimeAsync(15 * 60_000);
expect(selects).not.toHaveBeenCalled(); expect(provider).not.toHaveBeenCalled();
@@ -135,12 +139,15 @@ const active: ExternalObjectResolveResult = { ok: true, snapshot: {
it("registers exact future deadlines, preempts them on earlier writes and cancels terminal work", async () => {
clock(); provider.mockResolvedValue(active);
const svc = service(); await start(svc);
const svc = service(); const worker = await start(svc);
const f = await fixture(); await svc.syncIssue(f.issueId);
await settle(() => provider.mock.calls.length === 1);
await settle(async () => (await row(f.companyId)).lastResolvedAt !== null);
const saved = await row(f.companyId);
await settle(() => coordinator!.nextWakeAt() === saved.nextRefreshAt!.getTime());
await settle(() => worker.reconciliationSnapshot().reconciled);
expect(await db.transaction(tx => svc.readIdleSchedule(tx, Date.now(), worker.reconciliationSnapshot)))
.toMatchObject({ blocked: false, deadlines: [saved.nextRefreshAt!.getTime()] });
const earlier = new Date(Date.now() + 1000); await change(f.companyId, { nextRefreshAt: earlier });
await settle(() => coordinator!.nextWakeAt() === earlier.getTime());
await vi.advanceTimersByTimeAsync(999); expect(provider).toHaveBeenCalledTimes(1);
@@ -4,6 +4,7 @@ import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import { agentApiKeys, agents, budgetPolicies, chatDeliveries, chatEndpoints, companies,
companyTransferRuns, connectionEventDeliveries, createDb, heartbeatRuns, issues,
routineTriggers, routines, toolApplications, toolConnections, type Db } from "@paperclipai/db";
import { queueBudgetEvaluation } from "../services/budget-evaluation-work.js";
import { readIdleSleepSafety } from "../services/idle-sleep-safety.js";
import { EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
@@ -23,6 +24,7 @@ if (!support.supported) console.warn(`Skipping idle sleep diagnostics Postgres t
beforeAll(async () => {
if (!externalDatabaseUrl) temporary = await startEmbeddedPostgresTestDatabase("idle-sleep-diagnostics-");
db = createDb(externalDatabaseUrl ?? temporary!.connectionString, { maxConnections: 4 });
await db.execute(sql`TRUNCATE companies, plugins, environments CASCADE`);
}, 60_000);
afterEach(async () => { await db.execute(sql`TRUNCATE companies, plugins, environments CASCADE`); });
afterAll(async () => { await db?.$client.end({ timeout: 1 }); await temporary?.cleanup(); }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
@@ -59,10 +61,15 @@ if (!support.supported) console.warn(`Skipping idle sleep diagnostics Postgres t
expect(report.backgroundWork).toBe("none");
expect(report.diagnostics?.complete).toBe(true);
expect(blockers(report)).toEqual([]);
expect(report.diagnostics?.checks).toContainEqual({ reason: "budget_evaluation_work", state: "none" });
expect(report.diagnostics?.checks.filter(check => !check.reason.includes(".") ||
["agents.execution_or_timer", "agents.lifecycle", "agents.company_hold", "heartbeat_runs.budget_cancellation"].includes(check.reason)))
.toHaveLength(72);
.toHaveLength(73);
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId))).toHaveLength(1);
await db.transaction(tx => queueBudgetEvaluation(tx as unknown as Db, { companyId: f.companyId, agentId: f.agentId }));
const pending = await read();
expect(pending.backgroundWork).toBe("present");
expect(blockers(pending)).toEqual(["budget_evaluation_work"]);
});
it("reports history, credentials, debt, running work and future configuration simultaneously", async () => {
@@ -33,14 +33,14 @@ function database(present: string[] = [], change?: (row: Record<string, unknown>
describe("owned idle sleep diagnostics", () => {
it("reports simultaneous blockers from every predicate in one safe snapshot", async () => {
const f = database(["agent_api_keys", "heartbeat_runs", "chat_deliveries", "muse_mailbox_items"]);
const f = database(["agent_api_keys", "heartbeat_runs", "chat_deliveries", "muse_mailbox_items", "budget_evaluation_work"]);
const result = await readIdleSleepSafety(f.db, hold, () => now, ownerId, localNone,
undefined, undefined, false, false, collect);
expect(result.backgroundWork).toBe("present");
expect(result.diagnostics?.complete).toBe(true);
expect(result.diagnostics?.checks.filter(check => check.state === "present").map(check => check.reason))
.toEqual(["agent_api_keys", "chat_deliveries", "heartbeat_runs", "muse_mailbox_items"]);
expect(f.keys()).toHaveLength(72);
.toEqual(["agent_api_keys", "budget_evaluation_work", "chat_deliveries", "heartbeat_runs", "muse_mailbox_items"]);
expect(f.keys()).toHaveLength(73);
expect(new Set(f.keys()).size).toBe(f.keys().length);
const inventory = readFileSync(new URL("../../../doc/plans/2026-11-02-sleep-blocker-inventory.md", import.meta.url), "utf8");
const documented = [...inventory.matchAll(/^\| `([a-z0-9_.]+)` \|/gm)].map(match => match[1]);
@@ -43,7 +43,7 @@ describe.skipIf(!support.supported)('automatic project skill sources', () => {
beforeAll(async () => {
if (externalUrl) await applyPendingMigrations(externalUrl);
else testDb = await startEmbeddedPostgresTestDatabase('paperclip-project-skills-');
db = createDb(externalUrl ?? testDb.connectionString);
db = createDb(externalUrl ?? testDb.connectionString, { maxConnections: 4 });
home = await fs.mkdtemp(path.join(os.tmpdir(), 'paperclip-project-skills-home-'));
process.env.PAPERCLIP_HOME = home;
await db.insert(companies).values({ id: companyId, name: 'Project skills', issuePrefix: 'PSK' });
@@ -0,0 +1,478 @@
import { registerBudgetEnforcementWork } from "../services/budget-enforcement-worker.js";
import { hasPendingBudgetEvaluation, queueBudgetEvaluation } from "../services/budget-evaluation-work.js";
import { PROVIDER_QUOTA_MONITOR_SERVICE_NAME } from "@paperclipai/shared";
import { readIdleQuotaSchedule } from "../services/heartbeat/idle-quota-schedule.js";
import { registerDeadlineWork } from "../services/deadline-work.js";
import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
import { taskWatchdogService } from "../services/task-watchdogs.js";
import { processAdapter } from "../adapters/process/index.js";
import { registerServerAdapter, unregisterServerAdapter } from "../adapters/index.js";
import { issueService } from "../services/issues.js";
import { randomUUID } from "node:crypto";
import { and, eq, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { agents, agentWakeupRequests, applyPendingMigrations, authUsers, companies, companyMemberships, createDb, heartbeatRunEvents, heartbeatRuns, issues, type Db } from "@paperclipai/db";
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
import { heartbeatService } from "../services/heartbeat.js";
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
import { bindIdleDeadlineOwner } from "../services/idle-deadline-owner.js";
import { readIdleRetrySchedule } from "../services/heartbeat/idle-retry-schedule.js";
import { readIdleSleepSafety } from "../services/idle-sleep-safety.js";
import { idleWorkSnapshot } from "../services/task-admission.js";
import { idleDeadlineRowLimit, type IdleDeadlineOwners } from "../services/idle-deadline-types.js";
import type { VerifiedIdleCapabilities } from "../services/idle-incoming-wake-capability.js";
const fixtureUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_RECOVERY_DEADLINES_TEST_DATABASE_URL");
const adminUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_RECOVERY_DEADLINES_TEST_ADMIN_DATABASE_URL");
const connectionFields = ["hostname", "port", "pathname"] as const;
if (fixtureUrl && (!adminUrl || connectionFields.some(key =>
new URL(fixtureUrl)[key] !== new URL(adminUrl)[key]))) {
throw new Error("Recovery deadline acceptance requires explicit admin and fixture URLs for the same dedicated test database");
}
describe.skipIf(!fixtureUrl)("recovery deadline producer, proof and resumed execution (real PostgreSQL/local process)", () => {
let db: ReturnType<typeof createDb>;
let heartbeat: ReturnType<typeof heartbeatService>;
let coordinator: ReturnType<typeof createDeliveryWorkCoordinator> | undefined;
let worker: ReturnType<ReturnType<typeof heartbeatService>["registerRunDispatchWork"]> | undefined;
let owners: IdleDeadlineOwners;
let budgetWorker: ReturnType<typeof registerBudgetEnforcementWork> | undefined;
let monitorWorker: ReturnType<typeof registerDeadlineWork> | undefined;
let recoveryWorker: ReturnType<ReturnType<typeof heartbeatService>["registerIssueStateRecoveryWork"]> | undefined;
let draining = false;
let holdStartedAt: Date;
let holdExpiresAt: Date;
const ownerId = randomUUID();
const errors: unknown[] = [];
beforeAll(async () => {
await applyPendingMigrations(adminUrl!);
db = createDb(fixtureUrl!, { maxConnections: 4, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 });
registerServerAdapter({ ...processAdapter, type: "recovery_deadline_process", execute: async context => {
const result = await processAdapter.execute(context);
if (result.exitCode === 0 && !result.timedOut && !result.errorCode) {
const [current] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, context.runId));
if (!current?.issueId) throw new Error("Controlled agent requires its admitted task");
const tasks = issueService(db);
await tasks.addComment(current.issueId, "The controlled local process produced recovery-deadline-result; task completed.",
{ agentId: context.agent.id, runId: context.runId });
await tasks.update(current.issueId, { status: "done", companyGuard: current.companyId,
actorAgentId: context.agent.id, actorRunId: context.runId });
}
return result;
} });
}, 90_000);
beforeEach(async () => {
await db.execute(sql`TRUNCATE companies CASCADE`);
heartbeat = heartbeatService(db);
owners = {}; draining = false; errors.length = 0;
holdStartedAt = new Date(Date.now() - 1000); holdExpiresAt = new Date(Date.now() + 300_000);
});
afterEach(async () => {
await monitorWorker?.stop(); await recoveryWorker?.stop(); await budgetWorker?.stop();
await worker?.stop(); await coordinator?.stop();
await heartbeat.drainActiveRunExecutions();
const auditRuns = await db.select({ id: heartbeatRuns.id, status: heartbeatRuns.status, retryOfRunId: heartbeatRuns.retryOfRunId,
reason: heartbeatRuns.scheduledRetryReason, dueAt: heartbeatRuns.scheduledRetryAt, errorCode: heartbeatRuns.errorCode,
startedAt: heartbeatRuns.startedAt, finishedAt: heartbeatRuns.finishedAt,
source: sql<unknown>`${heartbeatRuns.contextSnapshot}->'source'`, wakeReason: sql<unknown>`${heartbeatRuns.contextSnapshot}->'wakeReason'`,
retryContext: sql<unknown>`${heartbeatRuns.contextSnapshot}->'retryOfRunId'` }).from(heartbeatRuns);
const auditWakes = await db.select({ id: agentWakeupRequests.id, runId: agentWakeupRequests.runId,
reason: agentWakeupRequests.reason, source: agentWakeupRequests.source, status: agentWakeupRequests.status }).from(agentWakeupRequests);
process.stderr.write(`recovery teardown causal audit ${JSON.stringify({ runs: auditRuns, wakes: auditWakes })}\n`);
worker = undefined; coordinator = undefined; monitorWorker = undefined; recoveryWorker = undefined; budgetWorker = undefined;
vi.useRealTimers();
expect(errors).toEqual([]);
});
afterAll(async () => { unregisterServerAdapter("recovery_deadline_process"); await db?.$client.end({ timeout: 1 }); });
async function start(options: { budgets?: boolean } = {}) {
coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => !draining,
canReconcile: () => true, onError: error => errors.push(error) });
worker = heartbeat.registerRunDispatchWork(coordinator, () => !draining);
owners.retries = bindIdleDeadlineOwner(worker.retries.reconciliationSnapshot, readIdleRetrySchedule,
snapshot => ({ coverage: { kind: "scheduled_retries", runIds: snapshot.runIds, wakeIds: snapshot.wakeIds }, issueWaits: snapshot.issueWaits }));
if (options.budgets !== false) {
budgetWorker = registerBudgetEnforcementWork(db, coordinator, { cancelWorkForScope: heartbeat.cancelBudgetScopeWork });
await budgetWorker.ready;
}
await worker.ready;
}
async function settled() {
await vi.waitFor(() => {
expect(worker!.retries.reconciliationSnapshot().reconciled).toBe(true);
expect(idleWorkSnapshot().active).toBe(0);
}, { timeout: 5_000 });
}
async function fixture(options: { retainedSourceLock?: boolean; quotaResetAt?: Date } = {}) {
const companyId = randomUUID();
await db.insert(authUsers).values({ id: "recovery-test-user", name: "Recovery test owner", email: "recovery-owner@example.test",
createdAt: new Date(), updatedAt: new Date() }).onConflictDoNothing();
await db.insert(companies).values({ id: companyId, name: "Recovery deadline acceptance",
issuePrefix: `R${companyId.slice(0, 7)}`, requireBoardApprovalForNewAgents: false,
defaultResponsibleUserId: "recovery-test-user" });
const [agent] = await db.insert(agents).values({ companyId, name: "Controlled process", role: "engineer", status: "idle",
adapterType: "recovery_deadline_process", adapterConfig: { command: process.execPath, args: ["-e", "console.log('recovery-deadline-result')"], cwd: process.cwd() },
runtimeConfig: { heartbeat: { enabled: true, intervalSec: 0, wakeOnDemand: true } },
}).returning();
await db.insert(companyMemberships).values([
{ companyId, principalId: "recovery-test-user", principalType: "user", status: "active", membershipRole: "owner" },
{ companyId, principalId: agent.id, principalType: "agent", status: "active", membershipRole: "member" },
]);
const [issue] = await db.insert(issues).values({ companyId, title: "Retry producer acceptance", status: "in_progress", assigneeAgentId: agent.id }).returning();
const [source] = await db.insert(heartbeatRuns).values({ companyId, agentId: agent.id, scopeKind: "issue", issueId: issue.id,
status: "failed", responsibleUserId: "recovery-test-user", errorCode: options.quotaResetAt ? "provider_quota" : "codex_transient_upstream", finishedAt: new Date(),
resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false }, ...(options.quotaResetAt ? {
errorFamily: "provider_quota", retryNotBefore: options.quotaResetAt.toISOString(), providerQuotaRetryNotBefore: options.quotaResetAt.toISOString(),
} : {}) }, contextSnapshot: { issueId: issue.id },
}).returning();
if (options.retainedSourceLock !== false)
await db.update(issues).set({ executionRunId: source.id, checkoutRunId: source.id }).where(eq(issues.id, issue.id));
return { companyId, agent, issue, source };
}
async function schedule(sourceId: string, delayMs = 600_000) {
const result = await heartbeat.scheduleBoundedRetry(sourceId, { delayMs, random: () => 0 });
if (result.outcome !== "scheduled") throw new Error(`Retry producer failed: ${result.outcome}`);
return result;
}
const run = (id: string) => db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, id)).then(rows => rows[0]);
async function proof() {
const at = Date.now();
const before = { local: idleWorkSnapshot(), retry: worker?.retries.reconciliationSnapshot(),
monitor: monitorWorker?.reconciliationSnapshot(), watchdog: recoveryWorker?.watchdogs.reconciliationSnapshot(), next: coordinator?.nextWakeAt() };
const report = await readIdleSleepSafety(db, () => ({ ownerId, draining: true, startedAt: holdStartedAt,
expiresAt: holdExpiresAt, activeRuns: 0, pendingWakes: 0 }), () => at, ownerId,
async () => "none", undefined, undefined, true, true,
{ deadlineCapability: { deadlineCatalog: "domain_deadlines_v1" } as VerifiedIdleCapabilities, deadlineOwners: owners,
collectDiagnostics: true });
const after = { local: idleWorkSnapshot(), retry: worker?.retries.reconciliationSnapshot(),
monitor: monitorWorker?.reconciliationSnapshot(), watchdog: recoveryWorker?.watchdogs.reconciliationSnapshot(), next: coordinator?.nextWakeAt() };
process.stderr.write(`proof revision audit ${JSON.stringify({ at, before, after, result: report.backgroundWork })}\n`);
return report;
}
async function finish(id: string) {
await vi.waitFor(async () => expect(["running", "succeeded"]).toContain((await run(id))?.status), { timeout: 15_000 });
await heartbeat.drainActiveRunExecutions();
const saved = await run(id);
expect(saved.status, JSON.stringify({ errorCode: saved.errorCode, error: saved.error, result: saved.resultJson })).toBe("succeeded");
expect(saved.stdoutExcerpt).toContain("recovery-deadline-result");
return saved;
}
it("hands off the real paired successor and cold-reconstructs one admitted useful execution", async () => {
const f = await fixture(); await start(); await settled();
const scheduled = await schedule(f.source.id, 8_000); await settled();
const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, scheduled.run.wakeupRequestId!));
expect(wake).toMatchObject({ runId: scheduled.run.id, agentId: f.agent.id, companyId: f.companyId, status: "queued" });
const report = await proof();
expect(report.backgroundWork, JSON.stringify(report.diagnostics)).toBe("none");
expect(report.scheduledWake?.nextWakeAt).toBe(scheduled.dueAt.toISOString());
await worker!.stop(); await coordinator!.stop();
expect(worker!.retries.reconciliationSnapshot().reconciled).toBe(false);
expect((await proof()).backgroundWork).not.toBe("none");
heartbeat = heartbeatService(db);
await start(); await settled();
expect(coordinator!.nextWakeAt()).toBe(scheduled.dueAt.getTime());
expect(Date.now()).toBeLessThan(scheduled.dueAt.getTime());
await finish(scheduled.run.id);
const successors = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId), eq(heartbeatRuns.retryOfRunId, f.source.id)));
expect(successors).toHaveLength(1);
const starts = await db.select({ id: heartbeatRunEvents.id }).from(heartbeatRunEvents).where(and(
eq(heartbeatRunEvents.runId, scheduled.run.id), eq(heartbeatRunEvents.message, "run started")));
expect(starts).toHaveLength(1);
await vi.waitFor(() => {
expect(coordinator!.nextWakeAt()).toBeNull();
expect(idleWorkSnapshot().active).toBe(0);
}, { timeout: 5_000 });
await heartbeat.drainActiveRunExecutions();
const executions = await db.select({ id: heartbeatRuns.id, status: heartbeatRuns.status,
retryOfRunId: heartbeatRuns.retryOfRunId, wakeupRequestId: heartbeatRuns.wakeupRequestId, context: heartbeatRuns.contextSnapshot }).from(heartbeatRuns)
.where(eq(heartbeatRuns.companyId, f.companyId));
const [completedTask] = await db.select({ status: issues.status }).from(issues).where(eq(issues.id, f.issue.id));
expect(completedTask.status).toBe("done");
const additional = executions.filter(row => ![f.source.id, scheduled.run.id].includes(row.id));
const audit = additional.map(row => ({ id: row.id, status: row.status, retryOfRunId: row.retryOfRunId,
retryContext: row.context?.retryOfRunId, source: row.context?.source, wakeReason: row.context?.wakeReason }));
const wakes = await db.select({ id: agentWakeupRequests.id, runId: agentWakeupRequests.runId,
status: agentWakeupRequests.status, source: agentWakeupRequests.source, reason: agentWakeupRequests.reason })
.from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId));
process.stderr.write(`retry execution lineage audit ${JSON.stringify({ sourceRunId: f.source.id, scheduledRunId: scheduled.run.id,
starts: starts.length, additional: audit, wakes })}\n`);
expect(additional, JSON.stringify(audit)).toHaveLength(0);
expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.runId, scheduled.run.id)))).toHaveLength(1);
expect(await heartbeat.promoteDueScheduledRetries()).toEqual({ promoted: 0, runIds: [] });
}, 30_000);
it("cancellation before the deadline invalidates its alarm and prevents resumed execution", async () => {
const f = await fixture(); await start(); await settled();
const scheduled = await schedule(f.source.id); await settled();
const before = await proof(); expect(before.backgroundWork).toBe("none");
await heartbeat.cancelRun(scheduled.run.id, "operator stop", { suppressImmediateRecovery: true });
await settled();
const after = await proof();
expect(after.deadlineProof?.generation).not.toBe(before.deadlineProof?.generation);
expect(after.scheduledWake).toBeUndefined();
await worker!.stop(); await coordinator!.stop(); heartbeat = heartbeatService(db);
await start();
expect(await heartbeat.promoteDueScheduledRetries(new Date(scheduled.dueAt.getTime() + 1))).toEqual({ promoted: 0, runIds: [] });
expect(await run(scheduled.run.id)).toMatchObject({ status: "cancelled", startedAt: null });
}, 20_000);
it("retains the first real producer during drain until successful resume reconstruction", async () => {
const f = await fixture(); await start(); await settled();
const old = await owners.retries!(db, Date.now(), () => {});
draining = true;
const scheduled = await schedule(f.source.id);
await vi.waitFor(() => expect(idleWorkSnapshot().active).toBe(0), { timeout: 5_000 });
expect(old.current()).toBe(false);
expect(worker!.retries.reconciliationSnapshot().reconciled).toBe(false);
expect((await proof()).backgroundWork).not.toBe("none");
expect((await run(scheduled.run.id)).status).toBe("scheduled_retry");
draining = false; worker!.wake(); await settled();
const resumed = await proof();
expect(resumed.backgroundWork, JSON.stringify(resumed.diagnostics)).toBe("none");
expect(resumed.scheduledWake?.nextWakeAt).toBe(scheduled.dueAt.toISOString());
await heartbeat.cancelRun(scheduled.run.id, "fixture cleanup", { suppressImmediateRecovery: true });
}, 20_000);
it("the quota recovery producer saves an exact future monitor inspected by its registered owner", async () => {
const reset = new Date(Date.now() + 600_000);
const f = await fixture({ retainedSourceLock: false, quotaResetAt: reset });
await start(); await settled();
monitorWorker = registerDeadlineWork(coordinator!, DELIVERY_QUEUES.issueMonitors, {
retryMs: 1000, canRun: () => !draining,
run: signal => heartbeat.tickIssueMonitors(new Date(), () => !signal.aborted && !draining),
next: () => heartbeat.nextIssueMonitorAt(),
});
owners.quota = bindIdleDeadlineOwner(monitorWorker.reconciliationSnapshot, readIdleQuotaSchedule,
snapshot => ({ issueWaits: snapshot.issueWaits }));
await monitorWorker.ready;
const result = await heartbeat.reconcileStrandedAssignedIssues({ companyId: f.companyId, issueId: f.issue.id });
expect(result.providerQuotaMonitored).toBe(1);
await vi.waitFor(() => expect(monitorWorker!.reconciliationSnapshot().reconciled).toBe(true));
const [saved] = await db.select({ policy: issues.executionPolicy, at: issues.monitorNextCheckAt }).from(issues).where(eq(issues.id, f.issue.id));
expect(saved.at).toEqual(reset);
expect(saved.policy?.monitor).toMatchObject({ serviceName: PROVIDER_QUOTA_MONITOR_SERVICE_NAME, externalRef: f.source.id });
await settled();
const report = await proof();
expect(report.backgroundWork, JSON.stringify(report.diagnostics)).toBe("none");
expect(report.scheduledWake?.nextWakeAt).toBe(reset.toISOString());
await issueService(db).update(f.issue.id, { status: "done", actorUserId: "recovery-test-user", companyGuard: f.companyId });
await vi.waitFor(() => expect(monitorWorker!.reconciliationSnapshot().reconciled).toBe(true));
await settled();
const [completed] = await db.select({ status: issues.status, policy: issues.executionPolicy, at: issues.monitorNextCheckAt,
claim: issues.monitorWakeRequestedAt, execution: issues.executionRunId, checkout: issues.checkoutRunId, state: issues.executionState })
.from(issues).where(eq(issues.id, f.issue.id));
process.stderr.write(`quota completed history audit ${JSON.stringify(completed)}\n`);
expect(completed).toMatchObject({ status: "done", at: reset, claim: null, execution: null, checkout: null, state: { status: "idle" } });
expect(completed.policy?.monitor).toMatchObject({ serviceName: PROVIDER_QUOTA_MONITOR_SERVICE_NAME, externalRef: f.source.id });
const final = await proof();
expect(final.backgroundWork, JSON.stringify(final.diagnostics)).toBe("none");
expect(final.scheduledWake).toBeUndefined();
const afterReset = await readIdleQuotaSchedule(db, reset.getTime() + 1, monitorWorker!.reconciliationSnapshot);
expect(afterReset).toMatchObject({ blocked: false, deadlines: [] });
for (const kind of ["run", "wake"] as const) {
const rollback = new Error(`terminal quota ${kind} rollback`);
await expect(db.transaction(async tx => {
if (kind === "run") await tx.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agent.id,
scopeKind: "issue", issueId: f.issue.id, status: "queued", contextSnapshot: { issueId: f.issue.id } });
else await tx.insert(agentWakeupRequests).values({ companyId: f.companyId, agentId: f.agent.id,
source: "automation", status: "queued", payload: { issueId: f.issue.id } });
expect((await readIdleQuotaSchedule(tx, Date.now(), monitorWorker!.reconciliationSnapshot)).blocked).toBe(true);
throw rollback;
})).rejects.toThrow(rollback.message);
}
const foreign = await fixture({ retainedSourceLock: false });
for (const reference of [foreign.source.id, `{${f.source.id}}`, "not-a-uuid"]) {
const rollback = new Error("terminal quota foreign or malformed reference rollback");
await expect(db.transaction(async tx => {
await tx.execute(sql`UPDATE issues SET execution_policy = jsonb_set(execution_policy,
'{monitor,externalRef}', to_jsonb(${reference}::text)) WHERE id = ${f.issue.id}::uuid`);
expect((await readIdleQuotaSchedule(tx, Date.now(), monitorWorker!.reconciliationSnapshot)).blocked).toBe(true);
throw rollback;
})).rejects.toThrow(rollback.message);
}
}, 20_000);
it("reconciles a configured watchdog through real review completion and retains quiet reviewed history", async () => {
const f = await fixture({ retainedSourceLock: false });
await issueService(db).update(f.issue.id, { status: "done", actorUserId: "recovery-test-user", companyGuard: f.companyId });
await start(); await settled();
const configuration = await taskWatchdogService(db).upsertForIssue(f.companyId, f.issue.id, { agentId: f.agent.id });
const registeredAt = Date.now();
recoveryWorker = heartbeat.registerIssueStateRecoveryWork(coordinator!, () => !draining);
owners.watchdogs = bindIdleDeadlineOwner(recoveryWorker.watchdogs.reconciliationSnapshot, heartbeat.readIdleWatchdogSchedule,
() => ({ coverage: { kind: "watchdogs" } }));
await recoveryWorker.ready;
await vi.waitFor(async () => {
await heartbeat.drainActiveRunExecutions();
const current = await taskWatchdogService(db).getActiveForIssue(f.companyId, f.issue.id);
expect(current?.watchdogIssueId).toBeTruthy();
const [review] = await db.select({ status: issues.status }).from(issues).where(eq(issues.id, current!.watchdogIssueId!));
expect(review.status).toBe("done");
}, { timeout: 15_000 });
const pending = recoveryWorker.watchdogs.reconciliationSnapshot();
process.stderr.write(`watchdog review settlement audit ${JSON.stringify({ registeredAt, now: Date.now(), pending,
next: coordinator!.nextWakeAt(), local: idleWorkSnapshot() })}\n`);
if (!pending.reconciled) expect((await proof()).backgroundWork).not.toBe("none");
await vi.waitFor(() => {
expect(recoveryWorker!.watchdogs.reconciliationSnapshot().reconciled).toBe(true);
expect(idleWorkSnapshot().active).toBe(0);
}, { timeout: Math.max(0, registeredAt + 35_000 - Date.now()) + 5_000 });
const report = await proof();
expect(report.backgroundWork, JSON.stringify(report.diagnostics)).toBe("none");
const retained = await taskWatchdogService(db).getActiveForIssue(f.companyId, f.issue.id);
expect(retained?.id).toBe(configuration.watchdog.id);
expect(retained?.lastReviewedFingerprint).toBeTruthy();
expect((await proof()).scheduledWake).toBeUndefined();
}, 50_000);
it("batches seven settled watchdogs within the composed proof budget and rejects live or changed owners", async () => {
const fixtures: Awaited<ReturnType<typeof fixture>>[] = [];
for (let index = 0; index < 7; index++) {
const f = await fixture({ retainedSourceLock: false });
await issueService(db).update(f.issue.id, { status: "done", actorUserId: "recovery-test-user", companyGuard: f.companyId });
await taskWatchdogService(db).upsertForIssue(f.companyId, f.issue.id, { agentId: f.agent.id });
fixtures.push(f);
}
await start(); await settled();
recoveryWorker = heartbeat.registerIssueStateRecoveryWork(coordinator!, () => !draining);
const readWatchdogs = bindIdleDeadlineOwner(recoveryWorker.watchdogs.reconciliationSnapshot, heartbeat.readIdleWatchdogSchedule,
() => ({ coverage: { kind: "watchdogs" } }));
owners.watchdogs = readWatchdogs;
await recoveryWorker.ready;
await vi.waitFor(async () => {
await heartbeat.drainActiveRunExecutions();
for (const f of fixtures) {
const current = await taskWatchdogService(db).getActiveForIssue(f.companyId, f.issue.id);
expect(current?.lastReviewedFingerprint).toBeTruthy();
expect(current?.watchdogIssueId).toBeTruthy();
const [review] = await db.select({ status: issues.status }).from(issues).where(eq(issues.id, current!.watchdogIssueId!));
expect(review.status).toBe("done");
}
expect(recoveryWorker!.watchdogs.reconciliationSnapshot().reconciled).toBe(true);
expect(idleWorkSnapshot().active).toBe(0);
}, { timeout: 65_000 });
const report = await proof();
expect(report.backgroundWork, JSON.stringify(report.diagnostics)).toBe("none");
expect(report.scheduledWake).toBeUndefined();
draining = true;
const f = fixtures[0];
const [pending] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agent.id,
issueId: f.issue.id, status: "queued", contextSnapshot: { issueId: f.issue.id } }).returning();
expect((await proof()).backgroundWork).not.toBe("none");
await db.delete(heartbeatRuns).where(eq(heartbeatRuns.id, pending.id));
expect((await proof()).backgroundWork).toBe("none");
owners.watchdogs = async (...args) => {
const snapshot = await readWatchdogs(...args);
await recoveryWorker!.watchdogs.stop();
return snapshot;
};
expect((await proof()).backgroundWork).not.toBe("none");
}, 80_000);
it("retains ten thousand completed quota histories within bounded proof and rejects overflow or unfinished work", async () => {
expect(idleDeadlineRowLimit).toBe(10_000);
const reset = new Date(Date.now() + 600_000);
const f = await fixture({ retainedSourceLock: false, quotaResetAt: reset });
const produced = await heartbeat.reconcileStrandedAssignedIssues({ companyId: f.companyId, issueId: f.issue.id });
expect(produced.providerQuotaMonitored).toBe(1);
await issueService(db).update(f.issue.id, { status: "done", actorUserId: "recovery-test-user", companyGuard: f.companyId });
const growHistory = async (count: number) => {
await db.execute(sql`
WITH bindings AS MATERIALIZED (
SELECT gen_random_uuid() AS issue_id, gen_random_uuid() AS source_id FROM generate_series(1, ${count})
), written_issues AS (
INSERT INTO issues (id, company_id, title, status, assignee_agent_id,
execution_policy, execution_state, monitor_next_check_at, monitor_attempt_count)
SELECT b.issue_id, template.company_id, 'Completed quota history', template.status, template.assignee_agent_id,
jsonb_set(template.execution_policy, '{monitor,externalRef}', to_jsonb(b.source_id::text)),
jsonb_set(template.execution_state, '{monitor,externalRef}', to_jsonb(b.source_id::text)),
template.monitor_next_check_at, template.monitor_attempt_count
FROM bindings b CROSS JOIN issues template WHERE template.id = ${f.issue.id}::uuid
RETURNING id, company_id, execution_policy
)
INSERT INTO heartbeat_runs (id, company_id, agent_id, issue_id, status, finished_at,
runtime_mode, error_code, result_json, context_snapshot, responsible_user_id)
SELECT (written.execution_policy#>>'{monitor,externalRef}')::uuid, written.company_id, source.agent_id,
written.id, source.status, source.finished_at, source.runtime_mode, source.error_code, source.result_json,
jsonb_build_object('issueId', written.id), source.responsible_user_id
FROM written_issues written CROSS JOIN heartbeat_runs source WHERE source.id = ${f.source.id}::uuid
`);
};
const [template] = await db.select({ status: issues.status, policy: issues.executionPolicy,
state: issues.executionState, at: issues.monitorNextCheckAt }).from(issues).where(eq(issues.id, f.issue.id));
expect(template).toMatchObject({ status: "done", at: reset, state: { status: "idle" } });
expect(template.policy?.monitor).toMatchObject({ serviceName: PROVIDER_QUOTA_MONITOR_SERVICE_NAME, externalRef: f.source.id });
await growHistory(9_999);
const [count] = await db.execute<{ count: number }>(sql`SELECT count(*)::integer AS count FROM issues WHERE company_id = ${f.companyId}::uuid`);
expect(count.count).toBe(10_000);
const [sources] = await db.execute<{ count: number }>(sql`SELECT count(*)::integer AS count FROM heartbeat_runs WHERE company_id = ${f.companyId}::uuid`);
expect(sources.count).toBe(10_000);
await start(); await settled();
monitorWorker = registerDeadlineWork(coordinator!, DELIVERY_QUEUES.issueMonitors, {
retryMs: 1000, canRun: () => !draining,
run: signal => heartbeat.tickIssueMonitors(new Date(), () => !signal.aborted && !draining),
next: () => heartbeat.nextIssueMonitorAt(),
});
const recordScaleFailure = (error: unknown, phase: string) => {
const failure = error as { name?: string; code?: string; params?: unknown[];
cause?: { name?: string; code?: string; message?: string } };
process.stderr.write(`quota scale owner failure ${JSON.stringify({ phase, name: failure.name, code: failure.code,
parameters: failure.params?.length, cause: failure.cause?.name, causeCode: failure.cause?.code,
causeMessage: failure.cause?.message?.slice(0, 240) })}\n`);
};
owners.quota = bindIdleDeadlineOwner(monitorWorker.reconciliationSnapshot, async (tx, at, owner) => {
try { return await readIdleQuotaSchedule(tx, at, owner); }
catch (error) { recordScaleFailure(error, "composed"); throw error; }
}, snapshot => ({ issueWaits: snapshot.issueWaits }));
await monitorWorker.ready; await settled();
const report = await proof();
if (report.backgroundWork !== "none") {
try { await readIdleQuotaSchedule(db, Date.now(), monitorWorker.reconciliationSnapshot); }
catch (error) { recordScaleFailure(error, "direct-owner-diagnostic"); }
}
expect(report.backgroundWork, JSON.stringify(report.diagnostics)).toBe("none");
expect(report.scheduledWake).toBeUndefined();
for (const kind of ["run", "wake"] as const) {
const rollback = new Error(`large terminal quota ${kind} rollback`);
await expect(db.transaction(async tx => {
if (kind === "run") await tx.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agent.id,
issueId: f.issue.id, status: "queued", contextSnapshot: { issueId: f.issue.id } });
else await tx.insert(agentWakeupRequests).values({ companyId: f.companyId, agentId: f.agent.id,
source: "automation", status: "queued", payload: { issueId: f.issue.id } });
expect((await readIdleQuotaSchedule(tx, Date.now(), monitorWorker!.reconciliationSnapshot)).blocked).toBe(true);
throw rollback;
})).rejects.toThrow(rollback.message);
}
const rollback = new Error("large terminal quota malformed reference rollback");
await expect(db.transaction(async tx => {
await tx.execute(sql`UPDATE issues SET execution_policy = jsonb_set(execution_policy,
'{monitor,externalRef}', to_jsonb('not-a-uuid'::text)) WHERE id = ${f.issue.id}::uuid`);
expect((await readIdleQuotaSchedule(tx, Date.now(), monitorWorker!.reconciliationSnapshot)).blocked).toBe(true);
throw rollback;
})).rejects.toThrow(rollback.message);
await growHistory(1);
expect((await readIdleQuotaSchedule(db, Date.now(), monitorWorker.reconciliationSnapshot)).blocked).toBe(true);
}, 40_000);
it("blocks unconsumed budget inputs without a live owner and permits sleep only after normal settlement", async () => {
const f = await fixture({ retainedSourceLock: false });
await issueService(db).update(f.issue.id, { status: "done", actorUserId: "recovery-test-user", companyGuard: f.companyId });
await start({ budgets: false }); await settled();
expect(await hasPendingBudgetEvaluation(db)).toBe(false);
expect((await proof()).backgroundWork).toBe("none");
await db.transaction(tx => queueBudgetEvaluation(tx as unknown as Db, { companyId: f.companyId, agentId: f.agent.id }));
expect(await hasPendingBudgetEvaluation(db)).toBe(true);
const pending = await proof();
expect(pending.backgroundWork).toBe("present");
expect(pending.diagnostics?.checks).toContainEqual({ reason: "budget_evaluation_work", state: "present" });
budgetWorker = registerBudgetEnforcementWork(db, coordinator!, { cancelWorkForScope: heartbeat.cancelBudgetScopeWork });
await budgetWorker.ready; await settled();
expect(await hasPendingBudgetEvaluation(db)).toBe(false);
const consumed = await proof();
expect(consumed.backgroundWork, JSON.stringify(consumed.diagnostics)).toBe("none");
}, 15_000);
});
@@ -578,3 +578,49 @@ it("wakes an idle admission slot during shutdown and starts nothing new", async
expect(started).toEqual(["slow"]);
await worker.ready;
});
it("certifies settled future entries during drain but fences dirty reconstruction and stop", async () => {
vi.useFakeTimers();
let draining = false;
const owner = installDatabaseWorkSignals({ execute: vi.fn(async () => []), transaction: vi.fn() });
coordinator = createDeliveryWorkCoordinator({ owner, canRun: () => !draining, canReconcile: () => true, onError: vi.fn() });
const load = vi.fn(async () => [{ id: "object", companyId: "company", dueAt: Date.now() + 600_000 }]);
const worker = registerScopedDeadlineWork(coordinator, {
queue: DELIVERY_QUEUES.externalObjectRefresh, minimumPassIntervalMs: 0,
decodeScope: () => undefined, matches: () => true, load, check: async () => null,
}, () => !draining);
expect(worker.reconciliationSnapshot().reconciled).toBe(false);
await worker.ready;
const settled = worker.reconciliationSnapshot();
expect(settled.reconciled).toBe(true);
draining = true;
expect(worker.reconciliationSnapshot()).toEqual(settled);
worker.invalidate(); await vi.advanceTimersByTimeAsync(0);
expect(worker.reconciliationSnapshot().reconciled).toBe(false);
await vi.advanceTimersByTimeAsync(60_000);
expect(load).toHaveBeenCalledOnce();
draining = false; await vi.advanceTimersByTimeAsync(30_000);
expect(worker.reconciliationSnapshot().reconciled).toBe(true);
await coordinator.stop();
expect(worker.reconciliationSnapshot().reconciled).toBe(false);
});
it("keeps partial reconstruction and failed checks uncertified until they finish", async () => {
vi.useFakeTimers();
const owner = installDatabaseWorkSignals({ execute: vi.fn(async () => []), transaction: vi.fn() });
coordinator = createDeliveryWorkCoordinator({ owner, canRun: () => true, onError: vi.fn() });
const entry = { id: "object", companyId: "company", dueAt: Date.now() };
let complete = false, fail = true;
const worker = registerScopedDeadlineWork(coordinator, {
queue: DELIVERY_QUEUES.externalObjectRefresh, minimumPassIntervalMs: 1_000,
decodeScope: () => undefined, matches: () => true,
load: async () => ({ rows: [entry], complete }),
check: async () => { if (fail) throw new Error("provider unavailable"); return null; },
}, () => true);
await worker.ready;
expect(worker.reconciliationSnapshot().reconciled).toBe(false);
complete = true; await vi.advanceTimersByTimeAsync(1_000);
expect(worker.reconciliationSnapshot().reconciled).toBe(false);
fail = false; await vi.advanceTimersByTimeAsync(30_000);
expect(worker.reconciliationSnapshot().reconciled).toBe(true);
});
@@ -100,7 +100,8 @@ const {
nextRunAt?: () => number | null;
run: (signal?: AbortSignal) => Promise<unknown>;
hasPending?: () => Promise<boolean>;
}) => ({ ready: task.run(new AbortController().signal).catch(error => { deliveryWorkErrors.push({ queue, error }); }), wake: vi.fn(), stop: vi.fn(async () => {}) }));
}) => ({ ready: task.run(new AbortController().signal).catch(error => { deliveryWorkErrors.push({ queue, error }); }), wake: vi.fn(), stop: vi.fn(async () => {}),
reconciliationSnapshot: () => ({ revision: "startup-coordinator:1", reconciled: true }) }));
const createAppMock = vi.fn(async (_db: unknown, _options: unknown) => Object.assign((_: unknown, __: unknown) => {}, {
locals: {
fastResponses: { hasPending: vi.fn(async () => false), sweepPending: vi.fn(async () => undefined) },
@@ -153,9 +154,11 @@ const {
reapOrphanedRuns: vi.fn(async () => ({ reaped: 0, runIds: [] })),
registerResidualRecoveryWork: vi.fn((_coordinator: unknown, _canRun: () => boolean) => ({ ready: Promise.resolve() })),
registerActiveRunSilenceWork: vi.fn((_coordinator: unknown, _canRun: () => boolean) => ({ ready: Promise.resolve() })),
registerIssueStateRecoveryWork: vi.fn((_coordinator: unknown, _canRun: () => boolean) => ({ ready: Promise.resolve() })),
registerIssueStateRecoveryWork: vi.fn((_coordinator: unknown, _canRun: () => boolean) => ({ ready: Promise.resolve(),
watchdogs: { reconciliationSnapshot: () => ({ revision: "startup-watchdogs:1", reconciled: true }), stop: vi.fn(async () => {}) } })),
registerDeferredReceiptWork: vi.fn((_coordinator: unknown, _canRun: () => boolean) => ({ ready: Promise.resolve() })),
registerRunDispatchWork: vi.fn((_coordinator: unknown, _canRun: () => boolean) => ({ ready: Promise.resolve() })),
registerRunDispatchWork: vi.fn((_coordinator: unknown, _canRun: () => boolean) => ({ ready: Promise.resolve(),
retries: { reconciliationSnapshot: () => ({ revision: "startup-retries:1", reconciled: true }), stop: vi.fn(async () => {}) } })),
registerScheduledRetryCancellationWork: vi.fn((_coordinator: unknown, _canRun: () => boolean) => ({ ready: Promise.resolve() })),
registerStoppedInstructionCollectionWork: vi.fn((_coordinator: unknown, _canRun: () => boolean) => ({ ready: Promise.resolve() })),
registerRetainedNativeSessionCleanupWork: vi.fn((_coordinator: unknown, _canRun: () => boolean) => ({ ready: Promise.resolve(), stop: vi.fn() })),
@@ -394,7 +397,8 @@ vi.mock("../services/run-cost-accounting.js", () => ({
// This suite exercises startup coordination; source persistence and authority
// are covered by the database-backed source worker tests.
vi.mock("../services/skill-source-sync.js", () => ({
skillSourceSyncService: () => ({ start: vi.fn(), stop: vi.fn(async () => {}) }),
skillSourceSyncService: () => ({ start: vi.fn(), stop: vi.fn(async () => {}),
reconciliationSnapshot: () => ({ revision: "startup-skills:1", reconciled: true }) }),
}));
vi.mock("../services/native-runtime/native-session-executor.js", () => ({
@@ -596,6 +600,7 @@ vi.mock("../services/status-card-evaluation.js", () => ({
statusCardEvaluationService: vi.fn(() => ({ run: vi.fn(async () => {}), next: vi.fn(async () => null), changed: vi.fn() })),
registerStatusCardEvaluationWork: vi.fn((_coordinator, service, canRun) => ({
ready: canRun() ? service.run(new AbortController().signal) : Promise.resolve(), wake: vi.fn(), stop: vi.fn(async () => {}),
reconciliationSnapshot: () => ({ revision: "startup-status:1", reconciled: true }),
})),
}));
@@ -1614,6 +1619,7 @@ describe("startServer feedback export wiring", () => {
loadConfigMock.mockReturnValue(buildTestConfig({ heartbeatSchedulerEnabled: enabled }));
externalObjectsServiceMock.registerRefreshWork.mockReturnValueOnce({
ready: new Promise<void>(() => {}), wake: vi.fn(), stop: vi.fn(async () => {}),
reconciliationSnapshot: () => ({ revision: "startup-external:1", reconciled: false }),
});
await startServer();
expect(externalObjectsServiceMock.registerRefreshWork).toHaveBeenCalledOnce();
+1 -1
View File
@@ -39,7 +39,7 @@ describe.skipIf(!support.supported)('skill source persistence', () => {
process.env.PAPERCLIP_SKILL_PACKAGE_STORAGE_ENABLED = "true";
if (externalUrl) await applyPendingMigrations(externalUrl);
else testDb = await startEmbeddedPostgresTestDatabase('paperclip-skill-sources-');
db = createDb(externalUrl ?? testDb.connectionString);
db = createDb(externalUrl ?? testDb.connectionString, { maxConnections: 4 });
home = await fs.mkdtemp(path.join(os.tmpdir(), 'paperclip-source-test-')); process.env.PAPERCLIP_HOME = home;
await db.insert(companies).values({ id: companyId, name: 'Skills', issuePrefix: 'SKL' });
}, 30000);
@@ -24,6 +24,8 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
let db: ReturnType<typeof createDb>;
let coordinator: ReturnType<typeof createDeliveryWorkCoordinator> | undefined;
let cardWorker: ReturnType<typeof registerStatusCardEvaluationWork>;
let evaluation: ReturnType<typeof statusCardEvaluationService>;
let draining = false;
let companyId: string, agentId: string;
const errors: unknown[] = [];
@@ -43,7 +45,7 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
beforeAll(async () => {
if (!external) temporary = await startEmbeddedPostgresTestDatabase("status-card-evaluation-");
db = createDb(external ?? temporary!.connectionString, { maxConnections: 6, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 });
db = createDb(external ?? temporary!.connectionString, { maxConnections: 4, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 });
}, 30_000);
beforeEach(async () => {
companyId = randomUUID(); agentId = randomUUID(); draining = false; errors.length = 0; wakeup.mockReset();
@@ -51,7 +53,7 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
await db.insert(companies).values({ id: companyId, name: "Status", issuePrefix: `S${companyId.slice(0, 6)}` });
await db.insert(agents).values({ id: agentId, companyId, name: "Summarizer", role: "general", status: "idle", adapterType: "process", adapterConfig: {} });
await instanceSettingsService(db).updateExperimental({ enableStatusCards: true });
await Promise.all(Array.from({ length: 6 }, () => db.execute(sql`select pg_sleep(0.01)`)));
await Promise.all(Array.from({ length: 4 }, () => db.execute(sql`select pg_sleep(0.01)`)));
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true });
});
afterEach(async () => {
@@ -67,12 +69,17 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
async function start(service = statusCardEvaluationService(db, { wakeup })) {
coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => !draining, canReconcile: () => true,
onError: error => errors.push(error) });
await registerStatusCardEvaluationWork(coordinator, { ...service, run: signal => {
evaluation = service;
cardWorker = registerStatusCardEvaluationWork(coordinator, { ...service, run: signal => {
const work = service.run(signal);
evaluations.add(work);
void work.then(() => evaluations.delete(work), () => evaluations.delete(work));
return work;
} }, () => !draining).ready;
} }, () => !draining);
await cardWorker.ready;
}
async function idleSchedule() {
return db.transaction(tx => evaluation.readIdleSchedule(tx, Date.now(), cardWorker.reconciliationSnapshot));
}
async function settled() {
// Do not leap across PostgreSQL connect timers while real I/O is pending.
@@ -120,6 +127,7 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
it("settles empty, disabled, configured manual and unchanged reactive history without recurring SQL", async () => {
await start(); await quiet();
await card("manual"); await card("reactive"); await quiet();
expect(await idleSchedule()).toMatchObject({ blocked: false, deadlines: [] });
await instanceSettingsService(db).updateExperimental({ enableStatusCards: false }); await quiet();
expect(errors).toEqual([]);
});
@@ -729,12 +737,15 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
const service = statusCardEvaluationService(db, { wakeup });
service.changed(new Set([`changes:${companyId}`]));
try {
await service.run(new AbortController().signal);
await start(service);
expect(cardWorker.reconciliationSnapshot().reconciled).toBe(true);
expect(await service.next()).toBeGreaterThan(Date.now());
expect((await statusCardService(db).getById(created.id))!.nextEvalAt).toBeNull();
draining = true;
expect((await idleSchedule()).blocked).toBe(true);
expect(wakeup).not.toHaveBeenCalled();
} finally { release.resolve(); await holder; }
await vi.advanceTimersByTimeAsync(30_000); await service.run(new AbortController().signal);
} finally { release.resolve(); await holder; draining = false; }
await vi.advanceTimersByTimeAsync(30_000); await settled();
const pending = (await statusCardService(db).getById(created.id))!;
expect(pending.pendingChangeCount).toBeGreaterThan(0);
vi.setSystemTime(pending.nextEvalAt!); await service.run(new AbortController().signal);
@@ -881,6 +892,28 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
await vi.advanceTimersByTimeAsync(60_000); await settled(); expect(wakeup).toHaveBeenCalledOnce();
});
it("blocks sleep for a committed source hint with a null card deadline during drain", async () => {
await start(); const created = await card("reactive"); await quiet();
expect((await statusCardService(db).getById(created.id))!.nextEvalAt).toBeNull();
expect((await idleSchedule()).blocked).toBe(false);
draining = true;
await issueService(db).create(companyId, { title: "New blocker during drain", status: "blocked", priority: "medium" });
await settled();
expect((await statusCardService(db).getById(created.id))!.nextEvalAt).toBeNull();
expect((await idleSchedule()).blocked).toBe(true);
expect(wakeup).not.toHaveBeenCalled();
draining = false; await vi.advanceTimersByTimeAsync(30_000); await settled();
const pending = (await statusCardService(db).getById(created.id))!;
expect(pending.nextEvalAt).not.toBeNull();
expect(await idleSchedule()).toMatchObject({ blocked: false, deadlines: [pending.nextEvalAt!.getTime()] });
await vi.advanceTimersByTimeAsync(pending.nextEvalAt!.getTime() - Date.now()); await settled();
const generating = (await statusCardService(db).getById(created.id))!;
expect(wakeup).toHaveBeenCalledOnce();
expect((await idleSchedule()).blocked).toBe(true);
await writeback(created.id, generating.generatingIssueId!); await quiet();
expect(await idleSchedule()).toMatchObject({ blocked: false, deadlines: [] });
});
it("preserves the first write during drain until resume", async () => {
await start(); const created = await card("manual"); await quiet();
draining = true;
@@ -0,0 +1,97 @@
import { expect, it, vi } from "vitest";
import { instanceExperimentalSettingsSchema } from "@paperclipai/shared";
import type { Db } from "@paperclipai/db";
import { projectIdleStatusCardSchedule, readIdleStatusCardSchedule, type IdleStatusCardRow } from "../services/status-card-idle-schedule.js";
vi.mock("../services/status-cards.js", () => ({ statusCardService: vi.fn(() => ({ tickDueStatusCards: vi.fn() })) }));
vi.mock("../services/issues.js", () => ({ issueService: vi.fn(() => ({ update: vi.fn() })) }));
vi.mock("../services/instance-settings.js", () => ({ instanceSettingsService: vi.fn(() => ({
getExperimental: async () => ({ enableStatusCards: true }),
})) }));
const now = Date.UTC(2099, 0, 1);
function card(patch: Partial<IdleStatusCardRow> = {}): IdleStatusCardRow {
return { id: "card", companyId: "company", companyStatus: "active", revision: "row:1",
archivedAt: null, generatingIssueId: null, unfinishedUpdate: false,
state: "active", refreshPolicy: { mode: "reactive", debounceSeconds: 60 },
nextEvalAt: null, nextEvalReason: null, pendingChangeCount: 0, compiled: true, ...patch };
}
it("retains manual, unchanged reactive, archived and repaired-error history without deadlines", () => {
const rows = [card(), card({ refreshPolicy: { mode: "manual" } }), card({ archivedAt: new Date(now) }), card({ state: "error" })];
expect(projectIdleStatusCardSchedule(rows, now, true)).toMatchObject({ blocked: false, deadlines: [] });
});
it.each(["refresh", "membership", "policy", "retry", null])("keeps the exact future %s deadline", reason => {
const at = new Date(now + 60_000);
const row = card({ nextEvalAt: at, nextEvalReason: reason });
expect(projectIdleStatusCardSchedule([row], now, true)).toMatchObject({ blocked: false, deadlines: [at.getTime()] });
expect(row.nextEvalAt).toBe(at);
});
it.each([
{ nextEvalAt: new Date(now), nextEvalReason: "retry" },
{ nextEvalAt: new Date(Number.NaN) },
{ generatingIssueId: "task" }, { unfinishedUpdate: true },
{ pendingChangeCount: 1 }, { state: "compiling" }, { compiled: false },
{ refreshPolicy: { mode: "interval", intervalMinutes: 15 } },
{ refreshPolicy: { mode: "unknown" } }, { nextEvalReason: "unknown" }, { companyStatus: "unknown" },
])("blocks unfinished or unsupported card state %j", patch => {
expect(projectIdleStatusCardSchedule([card(patch)], now, true).blocked).toBe(true);
});
it("does not erase a generation claim when disabled, inactive or archived", () => {
for (const patch of [{}, { companyStatus: "paused" }, { archivedAt: new Date(now) }]) {
expect(projectIdleStatusCardSchedule([card({ ...patch, generatingIssueId: "task" })], now, false).blocked).toBe(true);
}
expect(projectIdleStatusCardSchedule([card({ nextEvalAt: new Date(now - 1) })], now, false).blocked).toBe(false);
expect(projectIdleStatusCardSchedule([], now, null).blocked).toBe(true);
});
it("refuses a dirty null-deadline card before querying and rejects an owner changed during the read", async () => {
const select = vi.fn();
const dirty = () => ({ revision: "owner:1", reconciled: false });
expect((await readIdleStatusCardSchedule({ select } as unknown as Pick<Db, "select">, now, true, dirty)).blocked).toBe(true);
expect(select).not.toHaveBeenCalled();
let revision = "owner:1";
const query = { from: () => query, innerJoin: () => query, orderBy: () => query,
limit: async () => { revision = "owner:2"; return [card()]; } };
select.mockReturnValue(query);
const owner = () => ({ revision, reconciled: true });
expect((await readIdleStatusCardSchedule({ select } as unknown as Pick<Db, "select">, now, true, owner)).blocked).toBe(true);
query.limit = async () => [card()];
expect((await readIdleStatusCardSchedule({ select } as unknown as Pick<Db, "select">, now, true, owner)).blocked).toBe(false);
});
it("blocks a deferred company's null card deadline even after the helper considers its sweep successful", async () => {
const { statusCardEvaluationService } = await import("../services/status-card-evaluation.js");
const { statusCardService } = await import("../services/status-cards.js");
const { instanceSettingsService } = await import("../services/instance-settings.js");
const tick = vi.fn().mockResolvedValueOnce({ evaluated: 0, enqueued: [], deferredCompanyIds: new Set(["company"]) })
.mockResolvedValue({ evaluated: 1, enqueued: [], deferredCompanyIds: new Set() });
const query = { from: () => query, innerJoin: () => query, orderBy: () => query, limit: async () => [card()] };
const select = vi.fn(() => query);
const service = statusCardEvaluationService({ select } as unknown as Db, { wakeup: vi.fn() });
expect(statusCardService).toHaveBeenCalled();
expect(instanceSettingsService).toHaveBeenCalled();
vi.mocked(statusCardService).mock.results.at(-1)!.value.tickDueStatusCards = tick;
await service.run(new AbortController().signal);
const owner = () => ({ revision: "helper:success", reconciled: true });
expect((await service.readIdleSchedule({ select } as unknown as Pick<Db, "select">, now, owner)).blocked).toBe(true);
expect(select).not.toHaveBeenCalled();
await service.run(new AbortController().signal);
expect((await service.readIdleSchedule({ select } as unknown as Pick<Db, "select">, now, owner)).blocked).toBe(false);
});
it("keeps disabled reconstruction passive after the actual owner settles its feature gate", async () => {
const { statusCardEvaluationService } = await import("../services/status-card-evaluation.js");
const { instanceSettingsService } = await import("../services/instance-settings.js");
const query = { from: () => query, innerJoin: () => query, orderBy: () => query, limit: async () => [card()] };
const select = vi.fn(() => query);
const service = statusCardEvaluationService({ select } as unknown as Db, { wakeup: vi.fn() });
vi.mocked(instanceSettingsService).mock.results.at(-1)!.value.getExperimental = async () =>
instanceExperimentalSettingsSchema.parse({ enableStatusCards: false });
await service.run(new AbortController().signal);
expect(await service.readIdleSchedule({ select } as unknown as Pick<Db, "select">, now,
() => ({ revision: "disabled:settled", reconciled: true }))).toMatchObject({ blocked: false, deadlines: [] });
});