mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-29 12:59:13 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agents can propose secrets and bindings for approval. > - Pending proposals already contain their expiry and encrypted value. > - The server scans for expired proposals on every maintenance tick, even when none exist. > - Committed proposal changes and saved expiry times provide the required triggers. > - This PR uses those triggers and preserves scrubbing, approval checks, and recovery. > - Empty and completed proposal history no longer causes recurring expiry queries. ## Linked Issues or Issue Description Refs #17443. This is the second PR in the sleep migration stack and targets its branch. **What problem does this solve?** The periodic proposal scan contacts PostgreSQL when no proposal needs maintenance. That obstructs idle database behavior across tenant instances. **What is the proposed solution?** Use transaction-aware notifications for creation and resolution. Reconstruct the earliest pending expiry at startup. Run cleanup at that deadline, or retry while reconciliation remains unfinished. **Why is this useful?** It removes an idle scan while retaining security checks and physical ciphertext cleanup. No queue table or migration is required. ## What Changed - Added intent notifications before secret/binding creation, approval, terminal transitions, and linked interaction resolution. The existing outer transaction owns settlement. - Kept expiry selection, ciphertext scrubbing, dependent rejection, and authorization in the secret-proposal service. - Registered a startup and deadline worker in place of the aggregate maintenance sweep. Empty/terminal states disarm; overdue batches and failures retain retries. - Reused shared scoped deadline dispatch for secret expiry. The service owns company-filtered SQL and expiry policy. Custom-image expiry continues to use `registerDeadlineWork`. - Added real PostgreSQL producer, outer-transaction, concurrent-write, expiry, restart, interaction resolution, and drain/resume tests. Updated startup wiring fixtures and documented the supported writer/lifecycle contract. ## Verification - Landing reconciliation at `c10eb1bcf752b058713e05d3345e5cf38dd3fa72`: 160 tests pass across the complete secret-proposal, scoped deadline, company batch, coordinator, startup, custom-image service and custom-image worker suites; no cases skipped in the accepted runs. Server typecheck passes. This integrates master after #17443 landed; fresh remote CI and Ponytail review are required before merge. Current head: `5bbe17ad9ebc4573b08ed1a9323644ef9608ca09`. This remains a single-duty PR stacked on #17443. - Integrated pinned master `8548173fc9efdc0fa07644fb92dcc0b6851a95e5` with normal merges. Every branch passed generated-schema checks and its target-branch migration-order gate. Existing SQL is unchanged; the 25 stack migrations follow master’s new migration. - Duty-specific producer coverage, lifecycle tests, and earlier failure records: [2026-10-08-instance-sleep-and-scheduler-inventory.md](https://github.com/paperclipai/paperclip/blob/5bbe17ad9ebc4573b08ed1a9323644ef9608ca09/doc/plans/2026-10-08-instance-sleep-and-scheduler-inventory.md), [2026-10-24-recurring-server-sleep-stack.md](https://github.com/paperclipai/paperclip/blob/5bbe17ad9ebc4573b08ed1a9323644ef9608ca09/doc/plans/2026-10-24-recurring-server-sleep-stack.md). - Combined tip `51e6cbe67979b55b340ea9f0f434c5b5c682ccd6`: **355 startup/cancellation/recovery/dispatch/preservation tests**, **75 connection-management tests**, and production server typechecking pass. These combined checks do not mean every intermediate PR independently ran the full repository suite. - Real master-to-stack database upgrade passes: **379 unchanged prior migration receipts plus 25 new migrations**, with the gateway responsibility fixture preserved. - Owning-branch checks: 84 runner installation/settlement cases plus runner typechecking and generated TypeScript/Rust profile agreement; 253 GitHub review workflow cases. Stop-attribution and held-worker readiness regressions failed before their fixes. - Failure accounting: the initial combined run passed 349 cases and failed six idle assertions in a reused preservation database containing old cancelled runs. Repeating the combined command with a fresh preservation database passed. Earlier invalid project selection, merge import/type errors, and the interrupted full local suite are not counted as passing checks. - **Latest-head CI and review remain required.** Prior CI findings include GitHub idle observation, route teardown, attention cleanup, touch-picker E2E, workspace health, and voice-cleanup timing; local passes do not erase those failures. No full local repository-suite, deployed sleep, fleet cost, or live Copilot qualification claim is made. ## Risks - Notifications cover supported writers sharing the database signal owner. Independent SQL writers and other process roots require a separate ingress contract; startup recovery alone is not live replica support. - The shared coordinator and scoped worker also serve later stack duties. Their defaults remain intact; existing voice, chat, native, and startup consumers are included in integrated verification. - Startup now checks overdue proposals immediately. During drain, physical cleanup waits; approval still rejects expired proposals synchronously. - Each due company pass remains bounded to 100 rows. Failed scopes back off from 30 seconds to five minutes; healthy overdue work keeps draining. Self-generated write hints coalesce and do not erase a failed sweep's backoff. - Heartbeat-disabled behavior and Cloud sleep-safety gates remain unchanged. This does not establish deployed suspension or external wake coverage. Tool review and gateway token cleanup remain separate slices. ## Model Used OpenAI Codex, GPT-6 family, with reasoning and code execution. The exact serving model identifier and context window 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 (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
138 lines
6.4 KiB
TypeScript
138 lines
6.4 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;
|
|
// Opt in only when run has recorded per-item failure backoffs. Other
|
|
// eligible items may already be due, unlike an unchanged failed deadline.
|
|
nextRunAtOnError?: () => number | null;
|
|
// An empty queue's maintenance may wait until dispatch admission reopens.
|
|
// Notifications and unresolved producer writes still reconcile in drain.
|
|
pausePassiveMaintenance?: boolean;
|
|
// Accounting and stop delivery finish already-admitted obligations;
|
|
// they must continue during admission drain, never warm standby.
|
|
runDuringDrain?: boolean;
|
|
}) {
|
|
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;
|
|
let pendingWork = true;
|
|
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; }
|
|
if (!input.canRun() && task.pausePassiveMaintenance && !pendingWork && !dirty &&
|
|
!finishIntent && !databaseWorkPending(input.owner, queue)) {
|
|
// A timer alone must not change the idle generation during a slow
|
|
// backup. Retry without querying or admitting work; a notification
|
|
// still preempts this deadline and retains its normal intent hold.
|
|
schedule(task.retryMs);
|
|
return;
|
|
}
|
|
dirty = false;
|
|
const finish = beginIdleTrackedWork();
|
|
const attempt = new AbortController();
|
|
let runFailed = false;
|
|
controller = attempt;
|
|
running = Promise.resolve().then(() => reconcileDatabaseWork(input.owner, queue))
|
|
.then(() => workerStopped || !(input.canRun() || (task.runDuringDrain && input.canReconcile?.())) ? undefined : task.run(attempt.signal).catch(error => { runFailed = true; throw error; })).then(() => workerStopped ? false : task.hasPending()).then(pending => {
|
|
pendingWork = pending || databaseWorkPending(input.owner, queue);
|
|
if (pendingWork) 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);
|
|
let failure = error;
|
|
try {
|
|
const scopedRetry = runFailed && task.nextRunAtOnError;
|
|
const next = input.canRun() ? (scopedRetry ? scopedRetry() : task.nextRunAt?.()) : null;
|
|
if (next != null && (scopedRetry || next > Date.now())) schedule(0, Math.max(Date.now(), next));
|
|
} catch (deadlineError) {
|
|
failure = new AggregateError([error, deadlineError], "Delivery failure deadline could not be read");
|
|
}
|
|
// Logging must never turn a recoverable sweep failure into an
|
|
// unhandled rejection or prevent other queues from running.
|
|
try { if (!workerStopped) input.onError(failure, 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();
|
|
},
|
|
};
|
|
}
|