Files
PaperClipAI/doc/plans/2026-10-26-database-backup-sleep-schedule.md
fa5e70faf4 fix(server): schedule automatic backups through shared lifecycle (#17836)
<!-- entire-trail-link-start -->
https://entire.com/gh/paperclipai/-/trails/39/changes/paperclip/39
<!-- entire-trail-link-end -->

## Thinking Path

> - Paperclip manages agent work and its durable state.
> - Automatic database backups protect that state on a configured
schedule.
> - Their independent interval is outside the shared deadline and
shutdown lifecycle.
> - An enabled backup schedule owes real work even when no queue
changed.
> - The existing coordinator can own this deadline without another table
or notification protocol.
> - This change preserves backup policy and moves scheduling into that
shared lifecycle.

## Linked Issues or Issue Description

Refs: #17835. Related work: #11756 (abortable backups), #3549
(stale-backup catch-up), #2120 (interval unref), #16364 (bounded
shutdown steps). This slice changes scheduling; it does not implement
those separate features.

**What existing behavior does this improve?**

Automatic database backup scheduling and shutdown ownership.

**Current behavior**

A standalone interval invokes backups, skips drain and warm standby, and
is not registered with the shared work scheduler. Its future deadline is
invisible there. The interval is not cleared or joined by the delivery
coordinator during shutdown.

**Proposed behavior**

Register the configured backup deadline with the shared coordinator.
Call the existing backup owner only when due. Keep the startup-relative
phase, skip missed slots, retain the next interval after failure or a
busy-owner skip, and join active scheduled work on shutdown.

**Reason and benefit**

One scheduling lifecycle owns overlap, admission, deadlines and
shutdown. Waiting does not query the database. This is a true periodic
obligation, so enabled backups still recur; it is not an empty-queue
polling removal or a claim of measured savings.

This existing slice now follows the merged import-spool parent #17835
and targets master. Merge authorization and exact-head CI/review gates
are tracked separately.

## What Changed

- Add a small backup scheduling owner using the existing coordinator and
scheduler.
- Replace the automatic-backup interval in startup. Register only when
backups are enabled, independently of heartbeat scheduling.
- Preserve the existing backup executor, manual serialization, retention
reads, pre-sleep verification, restart marker and host-sleep gates.
- Test deadlines, drain/standby, failures, busy-owner skips, slow
attempts, restart and shutdown. Update startup-marker tests to exercise
the registered deadline.
- Record the audit and update inventory item 15. No schema or backup
format changes.

## Verification

- Current source acceptance: **130 passing cases in four complete
files**, no skips: backup worker, startup checkpoints, scoped deadline
work and delivery coordinator. Database build, production server
typechecking/build, module boundaries, target migration order and Runner
profile identity pass.
- Runtime and all four selected test sources are byte-identical to
accepted source `11775eee7ed795b989cbb31052e69643c468c3cf` after normal
parent reconciliation. The parent carries the tool-access test-order
repair; it changes no backup behavior.
- Historical broader checks and the real JavaScript backup/restore
probe, including their intermediate failures and limits, remain in [the
backup audit](doc/plans/2026-10-26-database-backup-sleep-schedule.md).
They are not claimed as repeated current-head acceptance.
- No full local repository-suite, deployed suspend/wake, pg_dump, live
provider or cost-savings claim. Final-head CI, security, Greptile 5/5
and any actionable Ponytail findings remain separate merge gates.

## Risks

- Enabled backups still require periodic database and disk work. This
change centralizes the deadline; it does not reduce backup frequency or
establish deployed cost savings.
- The backup engine has no AbortSignal contract. Coordinator stop joins
an active scheduled backup, so a stalled backup can delay graceful
shutdown. Bounded backup cancellation remains separate work.
- Restart still starts a new ordinary interval; it does not replay
historical slots. The existing pre-sleep marker still requests an
immediate verified restart backup and persists on failure.
- A due backup waits during drain or standby and retries on the next
coordinator attempt after admission reopens, within one configured
interval.
- The internal deadline is not a persisted Cloud alarm. Existing
scheduled-backup and checkpoint sleep gates remain unchanged. The real
probe qualifies the JavaScript engine only, not pg_dump or deployed
shutdown latency.

## Model Used

OpenAI Codex (GPT-6-based coding agent). Repository inspection, ordinary
Git merges, source-composition proofs and local lifecycle tests were
used for this reconciliation. No subagents were used in the current
merge campaign.

## 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 URLs)
- [x] My branch name describes the change 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>
Co-authored-by: Codex <noreply@openai.com>
2026-10-29 07:55:53 -05:00

7.7 KiB

Automatic database backup scheduling

Scope and ownership

Inventory item 15: automatic database backups. This is slice 60, based on the import-spool cleanup branch (PR #17835). The server used an independent interval for this duty. It neither exposed its next deadline through the shared work scheduler nor joined the delivery coordinator's shutdown.

An enabled backup schedule is a real recurring obligation. This change does not turn it off after an empty read, reduce its frequency, or claim that scheduled backups become event-only work. No backup job table or database notification producer is needed: startup configuration creates the obligation.

The new database-backup-work.ts owns cadence. The existing runServerDatabaseBackup callback continues to own backup serialization, settings reads, archive creation, retention, checkpoint verification, error logging, and idle-work tracking. Manual and pre-sleep calls keep that same owner. index.ts registers the schedule only when automatic backups are enabled. The existing shared coordinator owns timers, admission gates, coalescing, failure reporting, and stopping. Other workers' contracts are unchanged.

Deadline and lifecycle contract

  • The first ordinary backup is due one configured interval after registration, after any existing restart-marker backup. This preserves the previous startup-relative cadence. There is no new persisted wall-clock schedule.
  • Discovery and early wakes perform no backup, settings query, filesystem read, or database transaction. hasPending reads no external state. The configured future deadline remains visible through the shared scheduler.
  • A due callback invokes the existing backup owner once. It preserves the owner's null result when a manual or pre-sleep backup is already active.
  • Success, failure, and a busy-owner skip all advance to the next future slot on the original cadence. A slow backup skips elapsed slots rather than creating a catch-up backlog. Failures remain logged and are attempted again at the next configured interval, as before.
  • Drain and warm standby prevent dispatch. Passive waiting does not read the database or hold an idle receipt. The due obligation remains in memory; after admission reopens it runs on the next coordinator attempt, within one configured interval. It does not replay each missed slot.
  • Shutdown stops the shared timer and waits for an already-running scheduled backup. The existing backup implementation has no AbortSignal contract, so this is a join, not cancellation. A stalled backup can delay graceful shutdown; adding bounded backup cancellation is separate work (see PR #11756).
  • Restart retains the existing behavior: a fresh ordinary interval begins. A pre-sleep marker still requests the existing immediate verified startup backup. A failed startup backup leaves that marker for the scheduled retry. This slice does not add stale-backup catch-up (see PR #3549).

Host sleep boundary

markIdleStartupComplete({ scheduledBackups: ... }), the backup checkpoint opt-in, wake marker, readIdleLocalWork gate, and archive verification are unchanged. Without the existing checkpoint proof, scheduled backups remain a host-sleep blocker. With that proof, the existing restart-marker protocol still owns wake recovery. A registered in-process deadline is not a persisted Cloud alarm. This slice proves scheduling and lifecycle behavior, not host suspension, external wake delivery, or fleet savings.

Verification

The complete six-suite run passed 152 tests, without skips:

pnpm exec vitest run \
  server/src/__tests__/database-backup-work.test.ts \
  server/src/__tests__/server-startup-feedback-export.test.ts \
  server/src/__tests__/delivery-work-coordinator.test.ts \
  server/src/__tests__/work-scheduler.test.ts \
  server/src/__tests__/idle-local-work.test.ts \
  server/src/__tests__/instance-database-backups-routes.test.ts
pnpm -r typecheck
pnpm build

The nine new worker cases exercise the real coordinator and count both backup calls and database-driver calls. They cover no early work, drain/standby and startup during drain, failure before drain, busy-owner skips, slow work with concurrent wakes, stop while active, and startup-relative restart behavior. Startup integration covers enabled/disabled registration independently of the heartbeat scheduler. Existing checkpoint tests now invoke the registered backup deadline, retaining their assertions about marker persistence, startup readiness, verification failures, and idle receipts.

A separate real PostgreSQL probe used two fresh disposable test databases. It created a row, waited for the new worker to call the actual JavaScript backup engine, verified the archive, restored it into the second database, and compared the committed row. It also checked no early invocation and no invocation after coordinator stop. The final probe passed. Its first launch referenced a nonexistent cleanup export; the next probe restored the correct row but rejected the PostgreSQL Result subclass when compared to a plain array. The harness was corrected to compare row contents and rerun with fresh databases. Neither failure required a production change. This probe does not qualify the pg_dump engine or prove deployed shutdown latency.

Workspace typechecking and the full build passed. The repository-wide local test:run remains unverified under the previously recorded embedded PostgreSQL capacity limitation; targeted suites are not a substitute claim. Remote CI and review acceptance are separate and remain pending until checked at the PR head.

October 29 master reconciliation and current acceptance

The current merge campaign carries this existing backup slice through the reviewed import-spool parent in #17835 and targets master after that parent lands. The normal parent merge preserved the backup worker, production registration and all four selected test files byte for byte. Parent changes since qualification are the import-spool audit and its inherited tool-access concurrency test repair; they do not change backup execution or scheduling. No packages, schema, backup format, interval policy, or sleep gate are added by this reconciliation.

Qualification at source 11775eee7ed795b989cbb31052e69643c468c3cf passed 130 cases in four complete files, without skips, in 7.24 seconds: database-backup-work, server-startup-feedback-export, scoped-deadline-work and delivery-work-coordinator. The tests cover deadline replacement, no work before a deadline, drain and standby admission, retry after failure, busy-owner skips, slow callbacks, coordinator stop and startup checkpoint-marker behavior. Database package build, production server typechecking and build, module boundaries, target migration order and Runner profile identity also passed. The reviewed runtime and these four test sources remain identical to that accepted source; a documentation-only publication does not claim another run.

The package tree remains the already qualified profile-80 parent tree. Historical six-suite and real JavaScript backup/restore probe results above remain evidence for their original revisions. This current four-file acceptance does not claim a repeated physical backup/restore probe, a pg_dump qualification, a full local repository-suite pass, live provider acceptance, measured host suspension or cost savings. Fresh CI, security and review results must be checked on the final published head separately.

Automatic backups remain a genuine scheduled obligation. The shared deadline is visible internally, but it is not a persisted external Cloud wake alarm. Existing checkpoint and host-sleep gates still govern whether an instance may suspend. Shutdown still joins an active backup whose executor has no AbortSignal contract.