mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-06 07:38:47 +01:00
Preserve bounded and atomic decision expiry with prompt backlog continuation
Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
2319a778ba
commit
9096786b1b
6 files changed
+120
-23
No files matched your search
@@ -38,9 +38,11 @@ retained terminal history does not enlarge the deadline lookup. Expiry is due
|
||||
when `expiresAt <= now`, including equality. The old combined path skipped the
|
||||
exact equality despite selecting that row; this migration fixes that boundary.
|
||||
|
||||
Each worker pass attempts at most 100 candidates ordered by expiry and ID.
|
||||
Each worker pass honors `PAPERCLIP_DECISIONS_SWEEP_BATCH_SIZE` (default 100),
|
||||
ordered by expiry and ID.
|
||||
Its in-memory cursor advances across failures and wraps after the last page.
|
||||
Remaining overdue work retains a retry through the saved earliest deadline.
|
||||
Remaining overdue work retains a one-second continuation through the saved
|
||||
earliest deadline after a successful pass.
|
||||
Failures retain the existing 30-second retry throttle. New earlier creation or
|
||||
resolution of the earliest decision causes deadline reconciliation. When only a
|
||||
future expiry remains, the worker does not query again until that deadline or a
|
||||
@@ -48,7 +50,9 @@ committed change. No open decisions means no recurring expiry work.
|
||||
|
||||
Settlement requires the row to remain open. TTL settlement also rechecks that
|
||||
the saved deadline is due. Metadata is merged into the current row. The existing
|
||||
expiry activity and origin continuation are preserved. A deadline-driven expiry
|
||||
expiry activity is persisted in the same transaction as the terminal transition.
|
||||
Publication and origin continuation follow commit. If the audit insert fails,
|
||||
the expiry and continuation obligation both roll back. A deadline-driven expiry
|
||||
records `ttl`; target-driven expiration retains its own reason. When both causes
|
||||
are possible, the first successful terminal transition determines the reason.
|
||||
Continuation failures belong to the continuation worker after the decision is
|
||||
@@ -71,8 +75,8 @@ suspension.
|
||||
|
||||
## Verification
|
||||
|
||||
The combined selection passes 103 tests: 14 new real-PostgreSQL expiry worker
|
||||
cases, 50 decision service/continuation cases, and 39 startup cases. It covers
|
||||
The original combined selection passed 103 tests: 14 initial real-PostgreSQL expiry worker
|
||||
cases, 50 decision service/continuation cases, and 39 startup cases. It covered
|
||||
empty and terminal-history quiet, actual create and bundle producers, exact
|
||||
expiry, moving the next deadline earlier, cancellation, restart, outer rollback
|
||||
and commit, first creation during drain, failed retry through drain, failed wake
|
||||
@@ -86,7 +90,8 @@ checks all collected causes after recovery settles. The next selection passed
|
||||
101 cases; after the parent review repairs and bounded expiry/shutdown coverage,
|
||||
all 103 pass. No production hold, retry, or timeout was weakened.
|
||||
|
||||
Migration 0383 applies and replays successfully. With 40,000 synthetic decisions
|
||||
The original index applied and replayed successfully; after normal parent
|
||||
integration it is regenerated as `0389_brave_hulk.sql`. Fresh apply also passes. With 40,000 synthetic decisions
|
||||
and one open row, the next-deadline query uses the partial index, reads two shared
|
||||
buffers, and executes in 0.022 ms locally. The probe transaction rolls back. This
|
||||
is query evidence, not a production latency or savings claim. Workspace
|
||||
@@ -101,3 +106,33 @@ text into its tuple comparison; business deadline calculations still use Date.
|
||||
The regression failed before the fix and verifies progress past the failed page,
|
||||
then recovery of all failed rows after the fault is removed.
|
||||
The repaired expiry suite passes all 15 cases, and server typechecking passes.
|
||||
|
||||
|
||||
## Current review repairs and verification
|
||||
|
||||
Three review findings failed real PostgreSQL regressions before repair: the
|
||||
standalone worker ignored the configured batch limit, a successful overdue
|
||||
backlog waited thirty seconds between batches, and a failed audit write left the
|
||||
row expired without durable activity. The worker now honors its existing batch
|
||||
configuration and continues successful overdue work after one second. The
|
||||
shared deadline adapter accepts an optional `continuationMs`; omitted values
|
||||
preserve every existing consumer's retry interval. Errors still retain the
|
||||
existing thirty-second retry. Expiry and durable activity commit atomically,
|
||||
then publish activity and deliver the origin continuation. Provider calls stay
|
||||
outside that transaction.
|
||||
|
||||
All 129 selected cases pass: 18 expiry, 53 decision/continuation, 15 archive, 42
|
||||
startup and one scoped-deadline case. The archive selection exercises an existing
|
||||
shared-deadline consumer with the new option absent. Server typecheck/build and
|
||||
generated snapshot/schema drift pass. Parent journal entries remain unchanged
|
||||
and five generated snapshots remain. No snapshot was hand-edited.
|
||||
|
||||
The first complete selection passed 113 cases and failed the future-startup
|
||||
assertion because it inspected the scheduler before an additional committed
|
||||
notification reconciliation finished. Coordinator `ready` awaits the first
|
||||
admitted pass, while a notification arriving during that pass can schedule
|
||||
another immediate pass. The assertion now waits for reconciliation to expose
|
||||
the exact saved future deadline, then still proves the decision does not expire
|
||||
early. The three production regressions and this fixture failure remain
|
||||
recorded; no error retry or business deadline was relaxed to pass the tests.
|
||||
Fresh current-head CI and reviews remain merge gates.
|
||||
@@ -484,3 +484,10 @@ Final workspace typecheck/build and fresh PR CI/review remain required.
|
||||
The parent continuation PR is awaiting fresh review/CI on `5f96892a58`, with both
|
||||
initial findings repaired and resolved. The full inventory remains in scope.
|
||||
|
||||
Slice 10 review repair: configured batch bounds, one-second successful overdue
|
||||
continuations and atomic expiration/activity settlement pass all three previously
|
||||
failing real PostgreSQL regressions. All 129 affected expiry/continuation/archive/
|
||||
startup/deadline cases, server types/build and snapshot drift pass. Own concurrent
|
||||
index was regenerated as `0389_brave_hulk.sql`, preserving parent history. The
|
||||
initial startup-reconciliation assertion failure and corrected boundary are
|
||||
recorded in the owning behavior audit. Latest-head CI/reviews remain required.
|
||||
@@ -40,9 +40,11 @@ const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTes
|
||||
});
|
||||
afterEach(async () => {
|
||||
await coordinator?.stop(); coordinator = undefined;
|
||||
vi.useRealTimers(); vi.restoreAllMocks();
|
||||
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);
|
||||
@@ -94,9 +96,51 @@ const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTes
|
||||
expect(await db.select().from(activityLog).where(eq(activityLog.action, "decision.expired"))).toHaveLength(1);
|
||||
});
|
||||
|
||||
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(); await start();
|
||||
expect(coordinator!.nextWakeAt()).toBe(row.expiresAt.getTime());
|
||||
await vi.waitFor(() => expect(coordinator!.nextWakeAt()).toBe(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);
|
||||
|
||||
@@ -9,6 +9,7 @@ export function registerDeadlineWork(
|
||||
next: () => Promise<number | null>;
|
||||
canRun: () => boolean;
|
||||
retryMs: number;
|
||||
continuationMs?: number;
|
||||
// Optional batching latency for notifications; already-known deadlines still preempt it.
|
||||
notificationCoalesceMs?: number;
|
||||
},
|
||||
@@ -29,12 +30,14 @@ export function registerDeadlineWork(
|
||||
return;
|
||||
}
|
||||
const generation = ++requested;
|
||||
earliest = Date.now() + task.retryMs;
|
||||
const startedAt = Date.now();
|
||||
earliest = startedAt + task.retryMs;
|
||||
await task.run(signal);
|
||||
if (signal.aborted) return;
|
||||
const deadline = await task.next();
|
||||
// Back off failed or still-overdue work, not a successfully read future deadline.
|
||||
if (deadline === null || deadline > Date.now()) earliest = 0;
|
||||
earliest = deadline === null || deadline > Date.now()
|
||||
? 0 : startedAt + (task.continuationMs ?? task.retryMs);
|
||||
next = deadline === null ? null : Math.max(earliest, deadline);
|
||||
coalesceUntil = Date.now() + (task.notificationCoalesceMs ?? 0);
|
||||
reconciled = generation;
|
||||
|
||||
@@ -9,7 +9,7 @@ export function registerDecisionExpiryWork(
|
||||
canRun: () => boolean,
|
||||
) {
|
||||
return registerDeadlineWork(coordinator, DELIVERY_QUEUES.decisionExpiry, {
|
||||
retryMs: 30_000, canRun,
|
||||
retryMs: 30_000, continuationMs: 1000, canRun,
|
||||
run: signal => service.sweepTtlExpiry(new Date(), signal),
|
||||
next: service.nextExpiryAt,
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { and, asc, eq, getTableColumns, lte, sql } from "drizzle-orm";
|
||||
import { decisions, type Db } from "@paperclipai/db";
|
||||
import { logActivity } from "./activity-log.js";
|
||||
import { logActivity, publishActivity, type ActivityPublication } from "./activity-log.js";
|
||||
import { writeDecisionChange } from "./decision-work-notifications.js";
|
||||
|
||||
type Decision = typeof decisions.$inferSelect;
|
||||
@@ -10,16 +10,22 @@ const open = sql`${decisions.status} = 'open'`;
|
||||
export function decisionExpiryService(db: Db, deliverContinuation: (id: string) => Promise<void>) {
|
||||
let recoveryCursor: { expiresAt: string; id: string } | undefined;
|
||||
async function expire(decision: Decision, reason: ExpiryReason, now: Date) {
|
||||
const [updated] = await writeDecisionChange(db, async tx => tx.update(decisions).set({
|
||||
status: "expired", updatedAt: now,
|
||||
metadata: sql`${decisions.metadata} || ${JSON.stringify({ expiredReason: reason,
|
||||
...(decision.continuationPolicy === "wake_origin_agent" ? { continuationPending: true } : {}) })}::jsonb`,
|
||||
}).where(and(eq(decisions.id, decision.id), open,
|
||||
reason === "ttl" ? lte(decisions.expiresAt, now) : undefined)).returning());
|
||||
const publications: ActivityPublication[] = [];
|
||||
const updated = await writeDecisionChange(db, async tx => {
|
||||
const [row] = await tx.update(decisions).set({
|
||||
status: "expired", updatedAt: now,
|
||||
metadata: sql`${decisions.metadata} || ${JSON.stringify({ expiredReason: reason,
|
||||
...(decision.continuationPolicy === "wake_origin_agent" ? { continuationPending: true } : {}) })}::jsonb`,
|
||||
}).where(and(eq(decisions.id, decision.id), open,
|
||||
reason === "ttl" ? lte(decisions.expiresAt, now) : undefined)).returning();
|
||||
if (!row) return null;
|
||||
await logActivity(tx, { companyId: row.companyId, actorType: "system", actorId: "decision-expiry-sweeper",
|
||||
agentId: row.originAgentId, runId: row.originRunId, action: "decision.expired", entityType: "decision",
|
||||
entityId: row.id, details: { expiredReason: reason } }, publications);
|
||||
return row;
|
||||
});
|
||||
if (!updated) return 0;
|
||||
await logActivity(db, { companyId: updated.companyId, actorType: "system", actorId: "decision-expiry-sweeper",
|
||||
agentId: updated.originAgentId, runId: updated.originRunId, action: "decision.expired", entityType: "decision",
|
||||
entityId: updated.id, details: { expiredReason: reason } });
|
||||
for (const publication of publications) publishActivity(publication);
|
||||
await deliverContinuation(updated.id);
|
||||
return 1;
|
||||
}
|
||||
@@ -35,13 +41,15 @@ export function decisionExpiryService(db: Db, deliverContinuation: (id: string)
|
||||
let expired = 0;
|
||||
if (signal?.aborted) return { expired };
|
||||
const errors: unknown[] = [];
|
||||
const rows = await due(now, 100, recoveryCursor);
|
||||
const configuredBatchSize = Number(process.env.PAPERCLIP_DECISIONS_SWEEP_BATCH_SIZE ?? 100);
|
||||
const batchSize = Number.isFinite(configuredBatchSize) ? Math.max(1, Math.trunc(configuredBatchSize)) : 100;
|
||||
const rows = await due(now, batchSize, recoveryCursor);
|
||||
for (const row of rows) {
|
||||
if (signal?.aborted) return { expired };
|
||||
try { expired += await expire(row, "ttl", now); } catch (error) { errors.push(error); }
|
||||
recoveryCursor = { expiresAt: row.cursorExpiresAt, id: row.id };
|
||||
}
|
||||
if (rows.length < 100) recoveryCursor = undefined;
|
||||
if (rows.length < batchSize) recoveryCursor = undefined;
|
||||
if (errors.length === 1) throw errors[0];
|
||||
if (errors.length) throw new AggregateError(errors, "Decision expiry failed");
|
||||
return { expired };
|
||||
|
||||
Reference in new issue
Block a user