mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-29 04:25:52 +01:00
## Thinking Path > - Paperclip manages AI agent work and message delivery. > - Delivery workers restore saved retry and maintenance deadlines. > - The coordinator converts each future deadline to a delay and back. > - A clock tick between those reads can move the deadline. > - This pull request keeps the saved future timestamp. > - A deterministic test covers the clock tick. ## Linked Issues or Issue Description Refs #16503. This separate fix addresses an unrelated CI failure found during its review. **What happened?** The unchanged delayed GitHub publication restart test intermittently reports a wake deadline one millisecond after the saved timestamp. The coordinator subtracts one clock reading from the deadline, then adds the delay to a later reading. **Expected behavior** Keep a future saved deadline exactly. Preserve the current retry behavior for expired deadlines during idle reconciliation. **Steps to reproduce** Register a task with a future `nextRunAt` timestamp. Advance `Date.now()` by one millisecond on each read. The old coordinator reports `nextWakeAt()` one millisecond after the saved timestamp. The new unit test forces this sequence. ## What Changed - Let the internal scheduler accept the existing absolute future deadline. - Keep relative retry and immediate wake scheduling unchanged. - Add a deterministic advancing-clock regression. Keep the chat integration assertion unchanged. ## Verification - Based on `origin/master` at `c91f7a6e5f`. - Coordinator suite and the unchanged delayed GitHub publication restart case: 16 passed, 1346 unrelated cases skipped. - The new regression fails against the original coordinator with the exact one-millisecond offset. - Server typecheck passed. - On head `d2db3e15d6dfafd390bab59529474abebb19d09c`, all 55 hosted checks passed, with 2 expected skips. This includes all server/chat shards, Runner checks, build, canary dry run, security checks, and end-to-end tests. - Standard Greptile and Apex are both 5/5 on that exact head, with no review threads. Apex completed after green CI; final CI verification remains fully green and the branch is mergeable. - `git diff --check` and the pre-push secret/PII scan passed. ## Risks Low risk. The change keeps the saved future timestamp. Existing tests cover retry, idle drain, preemption, and shutdown behavior. No schema or API change is required. ## Model Used OpenAI Codex, GPT-6, with reasoning, repository inspection, code execution, and testing. The exact deployment model ID and context window are not exposed in this session. ## 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 references) - [x] My branch name describes the change and contains no internal Paperclip ticket id - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes (no public contract changed) - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip <noreply@paperclip.ing>
110 lines
4.7 KiB
TypeScript
110 lines
4.7 KiB
TypeScript
import { subscribeDatabaseWork, databaseWorkPending, reconcileDatabaseWork } from "@paperclipai/db";
|
|
import { createWorkScheduler } from "./work-scheduler.js";
|
|
import { type DeliveryQueue } from "./delivery-work-notifications.js";
|
|
import { beginIdleTrackedWork } from "./task-admission.js";
|
|
|
|
export function createDeliveryWorkCoordinator(input: {
|
|
owner: object;
|
|
canRun: () => boolean;
|
|
// Idle drain may reconcile admitted writes without dispatching new work.
|
|
// Warm standby can disable both operations.
|
|
canReconcile?: () => boolean;
|
|
onError: (error: unknown, queue: DeliveryQueue) => void;
|
|
}) {
|
|
const scheduler = createWorkScheduler();
|
|
const workers = new Map<DeliveryQueue, { wake: () => void; stop: () => Promise<void> }>();
|
|
let stopped = false;
|
|
|
|
return {
|
|
// Only these registered tasks are represented; not yet the whole instance.
|
|
nextWakeAt: scheduler.nextWakeAt,
|
|
register(queue: DeliveryQueue, task: {
|
|
retryMs: number;
|
|
run: (signal: AbortSignal) => Promise<unknown>;
|
|
hasPending: () => Promise<boolean>;
|
|
// Scoped hints belong to the outer transaction, including uncertainty recovery.
|
|
onSettled?: (hints?: ReadonlySet<string>) => void;
|
|
// Optional maintenance/retry deadline restored from durable state.
|
|
nextRunAt?: () => number | null;
|
|
}) {
|
|
if (stopped) throw new Error("Delivery coordinator is stopped");
|
|
if (workers.has(queue)) throw new Error(`Delivery worker already registered: ${queue}`);
|
|
let dirty = false;
|
|
let scheduledAt: number | null = null;
|
|
let running: Promise<void> | null = null;
|
|
let workerStopped = false;
|
|
let controller: AbortController | null = null;
|
|
let finishIntent: (() => void) | undefined;
|
|
function schedule(delay: number, deadline?: number) {
|
|
if (workerStopped) return;
|
|
const at = deadline ?? Date.now() + delay;
|
|
if (scheduledAt !== null && scheduledAt <= at) return;
|
|
scheduledAt = at;
|
|
scheduler.schedule(queue, at, start);
|
|
}
|
|
function start() {
|
|
if (workerStopped || running) return;
|
|
scheduler.cancel(queue);
|
|
scheduledAt = null;
|
|
if (!input.canRun() && !(input.canReconcile?.() ?? false)) { schedule(task.retryMs); return; }
|
|
dirty = false;
|
|
const finish = beginIdleTrackedWork();
|
|
const attempt = new AbortController();
|
|
controller = attempt;
|
|
running = Promise.resolve().then(() => reconcileDatabaseWork(input.owner, queue))
|
|
.then(() => workerStopped || !input.canRun() ? undefined : task.run(attempt.signal)).then(() => workerStopped ? false : task.hasPending()).then(pending => {
|
|
if (pending || databaseWorkPending(input.owner, queue)) schedule(task.retryMs);
|
|
else { finishIntent?.(); finishIntent = undefined; }
|
|
const next = task.nextRunAt?.();
|
|
if (next != null) {
|
|
const delay = Math.max(0, next - Date.now());
|
|
schedule(delay === 0 && !input.canRun() ? task.retryMs : delay, delay > 0 ? next : undefined);
|
|
}
|
|
}).catch(error => {
|
|
schedule(task.retryMs);
|
|
// Logging must never turn a recoverable sweep failure into an
|
|
// unhandled rejection or prevent other queues from running.
|
|
try { if (!workerStopped) input.onError(error, queue); } catch { /* Recovery remains scheduled. */ }
|
|
}).finally(() => {
|
|
running = null;
|
|
controller = null;
|
|
finish();
|
|
if (dirty) schedule(0);
|
|
});
|
|
}
|
|
function wake() {
|
|
if (workerStopped) return;
|
|
dirty = true;
|
|
if (!running) schedule(0);
|
|
}
|
|
const unsubscribe = subscribeDatabaseWork(input.owner, queue, (event, hints) => {
|
|
if (workerStopped) return;
|
|
if (databaseWorkPending(input.owner, queue)) {
|
|
finishIntent ??= beginIdleTrackedWork();
|
|
// Give the transaction time to settle. Its settlement notification
|
|
// replaces this deadline with an immediate wake on the normal path.
|
|
if (!running) schedule(task.retryMs);
|
|
}
|
|
if (event === "settled") { task.onSettled?.(hints); wake(); }
|
|
});
|
|
const worker = { wake, async stop() {
|
|
workerStopped = true;
|
|
controller?.abort(new Error("Delivery worker stopped"));
|
|
unsubscribe();
|
|
scheduler.cancel(queue);
|
|
await running;
|
|
finishIntent?.(); finishIntent = undefined;
|
|
} };
|
|
workers.set(queue, worker);
|
|
const ready = Promise.resolve().then(() => { start(); return running; });
|
|
return { ready, wake };
|
|
},
|
|
async stop() {
|
|
stopped = true;
|
|
scheduler.stop();
|
|
await Promise.all(Array.from(workers.values(), worker => worker.stop()));
|
|
workers.clear();
|
|
},
|
|
};
|
|
}
|