Skip to content

Latest commit

 

History

History
251 lines (185 loc) · 39.1 KB

storage.md

File metadata and controls

251 lines (185 loc) · 39.1 KB

Storage and persistence

Chopin stores all durable state in PostgreSQL behind one internal storage interface (StorageAdapter in apps/server/src/storage/port.ts). Application code talks only to that interface, never directly to SQL. PostgreSQL is the only production storage driver; an in-memory implementation (MemoryStorage) exists solely for unit and contract tests.

At a high level, PostgreSQL stores:

  • Documents and collaboration state: document metadata, URL slugs and historical aliases, full document checkpoints, incremental live-editing updates, and activity history snapshots.
  • Chat, decisions, and research: Chat messages, threads, file/image attachments, Decision cards and answers, comments, research offers and staged requests, and child documents.
  • Agents, machines, and builds: active implementation runs, background jobs, encrypted user AI credentials, paired machine tokens, short-lived launch placeholders, and single-writer server locks.

Plaintext GitHub tokens, raw browser cookie secrets, open in-memory rooms, live cursor presence, and Copilot SDK sessions are never written to PostgreSQL. Encrypted credentials use SESSION_ENCRYPTION_KEY, which stays outside the database. See Session boundary for how sessions are encrypted and restored.

Browsers keep a cache of the documents their reader opened, described in Documents kept in the browser; PostgreSQL stays the only authority.

State model

Every document ("channel") has a versioned JSON snapshot called its sidecar stored alongside its collaborative Yjs document. The sidecar holds document revision counters, questions, comments, shared drafts, top-level Chat messages, parent/child links, MCP update replay records, implementation graphs, active build state, and lifecycle history. PostgreSQL keeps the top-level Chat messages in rows of their own (chat_entries) and saves the sidecar without them; a load puts them back.

Key properties of the sidecar:

  • Validation on load: Opening a room validates the sidecar version and core structure, dropping a malformed optional implementation graph rather than refusing the whole document.
  • Monotonic Chat sequence numbers: If a Retry removes recent Chat messages, transcriptSeq in the sidecar (and last_seq on chat_threads, migration 042) remembers the highest sequence number already sent to browsers so a restarted server never reuses a sequence number. Rolling back past that migration requires removing transcriptSeq from sidecars, dropping chat_threads.last_seq, and deleting migration record 043_chat_thread_seq.
  • Messages waiting in line: Queued Planner messages mark their position on the transcript entry (queued) while keeping turn execution context (sender, login session, child focus, orchestrating document, repository) server-only in chat_queue (migration 059), written before marking queued and deleted once started or dropped. On startup, the lease holder opens every unarchived document with queued rows and starts them. Rolling back past migration 059 requires removing 059_chat_queue from chopin_migrations (and optionally dropping chat_queue). See Messages while the Planner works.
  • Plan state: A document marked draft or ready stores its latest mark in planState (state, reason, revision, author, timestamp, seq, and the last 256 applied idempotency keys). Rolling back to a release that rejects unknown sidecar keys requires stripping planState from sidecars first. See Draft or ready to build.
  • Conversation analysis (v2): Lives inside the sidecar with separate queues for decision and research offers, keeping exact source references, shared draft checkpoints, and idempotent acceptance keys. See Research offers from Chat.

Adapter guarantees

Every storage implementation passes a shared contract suite proving these invariants:

  • Atomic, fenced writes: Commits check both the expected revision and the active server's writer lease fencing token, rejecting stale writers cleanly.
  • Single-transaction consistency: collaboration.commit can save a Yjs document update, replace the sidecar, and append events in one database transaction. Even when only Chat, decisions, or build state change, committing them together guarantees clients never restore mismatched document and decision state.
  • Idempotency and ordering: Operation IDs prevent duplicate writes, updates replay in strict sequence order, and checkpoints atomically replace prior checkpoints and Yjs epochs.
  • Clean lifecycle state: Lists hide archived documents by default while direct ID and slug lookups still find them; archiving and restoring are idempotent; deleting a top-level document removes it and its children atomically under the writer lease; and historical slugs stay reserved without hijacking another document's URL.
  • Safe credential and session storage: Expiring browser sessions and paired machines store only token hashes and encrypted credentials; credential rotation checks revisions so it never resurrects a deleted session; startup clears expired sessions, metadata-only sessions, and Planner owners (except remote Planner holds that survive handover).
  • Non-blocking lease checks: leases.peek reads the writer lease without acquiring locks so a standby server waiting for handover never slows down the active server.
  • Clear error classification: Missing records, revision conflicts, corrupt data, and database outages surface as distinct errors.

Counters

Storage counters track database durability separately from document-editing counters:

  • Storage revision: increments on every accepted durable commit to a channel.
  • Storage sequence: strictly orders commits carrying Yjs updates or events. Sidecar-only commits still advance the sequence without writing a Yjs update row, so gaps in channel_updates.sequence are normal.
  • Checkpoint through_sequence: records which updates are already folded into the checkpoint.
  • Yjs epoch: distinguishes incompatible collaborative histories so they can never be merged.
  • Generated-description revision: tracked independently on channel metadata so updating an AI-generated summary (document-summary@1) never bumps document revisions or reorders the sidebar by updated_at.
  • Archive and restore: update only archived_at and updated_at, leaving document, collaboration, and build revisions untouched.

See the counter glossary in Architecture and job generations in Background jobs.

PostgreSQL schema

The migration runner maintains chopin_migrations with a content checksum for every applied file. Editing an applied migration fails startup as corruption.

Core application tables beyond the base channel, snapshot, update, event, operation, session, machine, and background-job tables:

Table What it stores
document_versions Activity history: one row per editing session with author (empty for Chopin), canonical MDX snapshot, revision, hash, and start/end timestamps.
workflow_run_stages Legacy table kept for schema compatibility (no longer written or read; Chat no longer renders workflow run cards). Deleted with its document.
planner_link_holds Saved state for a remote Planner link that dropped with pending work or during a zero-downtime restart handover: user/machine identity, held sessions, open questions, unacknowledged answers, handover deadline (handover_until), and fence. No secrets.
planner_model_choices Per-document model and reasoning-level selection, who chose it, and when. Stored verbatim so temporarily unavailable models remain selected and resume if they return. No secrets.
planner_catalogs Last model list reported by a document's remote Planner for a specific account, used only to show the picker immediately while the Planner reconnects. Removed with the document or account. No secrets.
planner_credentials SHA-256 hash, machine, document, and expiry of each short-lived Planner credential issued to a paired machine, plus the requester of a guest Planner there (migration 063). Raw tokens are never stored.
machine_databases Per-machine PostgreSQL login for MACHINE_STORE_URL: role name, AES-GCM encrypted password (bound to machine, role, and revision), pending rotation password, and lifecycle state (pending, ready, failed, disabled, dropped).
repository_logins One PostgreSQL login per launch (a Planner on a machine, a run, a spare Planner) to its repository's Atomic database (migration 060): role, database, repository, machine, launch, AES-GCM encrypted password, revision, state (live, dropping, withdrawn), deadline. Forgotten once its launch ends, its machine is revoked, or a week past its deadline.
planner_deferred_turns Legacy table from earlier releases that queued Planner turns. No longer written; open rows are closed cleanly at startup (see A live database from an earlier release).
ai_credentials One row per user and AI provider (github-copilot, openai, anthropic, chatgpt, claude), storing connection method (api-key, github-sign-in, subscription), AES-GCM encrypted key or OAuth tokens, last-four key suffix, last_used_at, and rejected_at (set on provider 401 auth errors until reconnected).
ai_placeholders SHA-256 digests of stand-in tokens handed to agent launches (tagged by owner: run:<id>, session:<id>, or link:<id>, and the grant's account id), bound to the document's archive_generation. Purged on expiry, completion, revocation, archive, or deletion. In-memory cutoff counters (AiCutoffs) ensure revoked launches stop immediately. No raw tokens are stored.
copilot_answers Copilot's last answer about each GitHub token people use GitHub Copilot with, keyed by a SHA-256 of the token and its Copilot account: whether Copilot took it (access or none), the account's Copilot model list, when it answered, and until when it is relied on (30 minutes), so a restart doesn't ask Copilot again meanwhile. Removed a day after it lapses. No tokens are stored.
ai_usage One row per proxied AI model request: launch, user, provider, model, outcome (pending, ok, error, unsent, unknown), HTTP status, short error code, and token counts. Stale pending rows become unknown at startup; ended rows purge after 90 days. No prompt or response text.
mcp_sessions Active external MCP client sessions (ID, user, client name/version, timestamps). Idle sessions are periodically swept.
mcp_invocations Idempotency records for invoke_planner calls (caller, document, key, request fingerprint, posted Chat entry ID, cached result, invoked/uncertain state). Swept after 7 days; stores no instruction text.
decision_seen Per-person seen marks for the Decisions inbox: user, document, card, and the card generation seen (a reopened card has a higher one, so it reads as new again), migration 058. Kept only for an open card of a document the person can read. Deleted with the document or user.
decision_history One row per settled decision card (answered, discarded, cancelled, expired) of a document, for the Decisions inbox's search: the card's summary (sidecarSettledCards: id, status, title, first prompt, question count, first answer, askedAt, origin, asker) and its lowercased search text, migration 061. Written with the sidecar it comes from, read per document newest asked first by its index. Deleted with the document.
chat_entries One row per entry of a document's top-level Chat transcript, migration 062: its id, its place in the transcript (ord), a digest of its JSON and the JSON itself. Written with the sidecar it comes from, only the entries that changed, and read in order when the document opens. Deleted with the document.
decision_answers Pending and delivered answers for Planner-opened Decision cards, keyed by document and decision generation so answers run at most once and newer answers replace older ones.
chat_attachments Uploaded Chat images (PNG, JPEG, WebP, GIF) and plain-text files (never HTML or SVG), storing validated bytes, sniffed type, name, size, and optional original dimensions when resized by the browser (original_size, original_width, original_height, migration 040). Unsent uploads expire after 1 day.
chat_threads One row per Chat thread (channel_id, root_id) storing the root snapshot, replies, last_seq, compactions, context usage, fork metadata, thread-asked Decision cards, and writer fence. Kept outside the sidecar so older releases still read sidecars cleanly.
chat_queue One row per message waiting in line for a Planner turn (channel_id, thread, entry_id): its sender, login session, child focus, orchestrating document and repository, which its turn needs and no client reads. Written before the entry says it waits, deleted once its turn's start is saved or it is let go, and with its document (migration 059).
chat_session_state Per-document top-level Chat compaction records, context usage, Atomic session state, per-entry fork points, unread notes from thread Planners, and retry-delivery notes. Fenced by the writer lease.
plan_images Document images keyed by document and SHA-256 hash (PNG, JPEG, WebP, GIF, AVIF, BMP, ICO). Bounded at upload (1 MiB for upload_image, MAX_STORED_IMAGE_BYTES defaulting to 10 MiB for tool images, 2 MiB over agent connection).

Additional schema rules worth knowing:

  • Unanswered decision count: JavaScript maintains channel_state.unanswered_decisions directly rather than using a SQL generated column, because sidecar JSON text can contain escaped NULs or unpaired UTF-16 surrogates that PostgreSQL JSONB rejects.
  • Open decision cards (channel_state.open_cards): Computed on every commit alongside unanswered_decisions (storing card summaries without volatile draft revisions, sanitizing NULs and lone surrogates for JSONB) so the Decisions inbox lists cards without reading sidecars. Migration 058 adds the columns cleanly without locking on data backfill; the lease holder backfills stale rows in batches (decisionInbox.backfill), and inbox reads refresh stale rows on demand.
  • Chat transcript rows (chat_entries): Every sidecar write updates only transcript entries whose position or SHA-256 digest changed and sets channel_state.transcript_revision to the written revision (a commit that leaves the sidecar unchanged advances transcript_revision alongside the document revision if already current).
    • PostgreSQL saves the sidecar without its transcript (channel_state.sidecar, sidecar_core, and the checkpoint at that revision) so Chat messages write only a few rows plus a small sidecar. sidecar_core is stored as JSON text inside a JSONB string so strings containing NULs or lone surrogates stay valid.
    • (channel_id, ord) is unique (checked at commit so entries can reorder in one write).
    • If a sidecar has no transcript, or has entries without unique IDs, PostgreSQL keeps the full transcript in sidecar with sidecar_core and transcript_revision unset. Rows are current only when both columns are set and transcript_revision matches the document's revision; otherwise the document loads its transcript from sidecar until its next write.
    • Every reader outside apps/server/src/storage/ loads stored documents through loadStored (plan/service.ts), which reassembles the transcript from chat_entries.
    • Rolling back to a release that includes migration 062 works directly; rolling back to a release before 062 requires putting transcripts back into sidecar first (see Rolling back past migration 062).
  • Settled decision cards (decision_history): Updated transactionally on every sidecar write whenever the settled-card digest (channel_state.history_digest) changes. Migration 061 adds the table and columns without a blocking backfill; the lease holder backfills stale documents one at a time under row locks (decisionInbox.backfillHistory). Searches filter readable documents first, then seek each document's newest-first index.
  • Parent/child links: channels.parent_channel_id enforces one-level nesting within the same repository (no grandchildren, no cross-repo parents). research_workspaces.published_channel_id restricts deletion so published research links stay intact.
  • Archive generations: channels.archive_generation increments on every archive and never decreases on restore. Archiving locks the document row so any AI launch prepared before the archive cannot write new placeholders afterward.
  • Planner reset timestamp: channels.planner_reset_at (migration 052) records when a writer last reset the document's Planner so paired machines discard older Planner disks or folders (see Linux microVMs and Windows sessions).
  • Machine resources and one pool: machines.resource_limits (migration 057) holds the CPU and memory limits a machine's owner saved for its agents ({ "cpus"?, "memoryMib"? }, none while both are the defaults), and machines.resource_report what its connector last reported of its host and the limits it applies. Neither holds a secret (see Machine resources). Migration 071 (071_one_pool.sql) drops the removed machine_choices and machine_favorites tables and machines.shared column.
  • Slugs and titles: Display titles may repeat, while URL slugs stay unique per repository. Renaming a document assigns a new canonical slug and keeps all previous slugs as reserved aliases, even while archived.
  • On-demand image thumbnails: Original image bytes are stored once and resized on demand via Bun.Image to fixed Slack-style widths (64, 80, 160, 360, 480, 720, 800, 960, 1024 via ?w=<width>), cached only in memory (apps/server/src/images/resize.ts). Animated GIFs are served untouched. Oversized uploads are resized down before storage so older releases still read them.
  • Chat @// pointers: Composer pointers (commands, headings, decisions, repo files) are stored separately under pointers while document and research links stay under references, keeping sidecars readable if a deployment rolls back to a release that did not recognize pointer types.

Archival and deletion

  • Listing and lookup: Channel lists and scans skip archived documents unless includeArchived is set. Direct UUID and slug lookups still open archived documents and their old aliases.
  • Archive and restore: Lock and update the channel row; repeating the same state is a harmless no-op.
  • Permanent deletion (channels.delete): Unlike archiving, deletion erases every trace of a document and its children in one fenced transaction (and counts as an AI cutoff). You can delete only a top-level document (children are deleted with their parent). To respect ON DELETE RESTRICT foreign keys, the transaction deletes published research requests and investigations first, then child channels, then the parent channel, letting cascading foreign keys remove sidecars, Chat transcript rows, snapshots, updates, events, operations, Planner holds, AI placeholders, threads, attachments, images, history, MCP records, build state, slugs, and jobs.
  • After deletion: No tombstone row stays in PostgreSQL; the server caches deleted IDs in memory for 10 minutes solely to make duplicate delete calls idempotent. Former slugs and MCP creation keys become free for reuse. Live deletion does not erase prior operator database backups.

Commit and acknowledgement

Chopin always writes durable state to PostgreSQL before replying to clients or broadcasting live updates:

  • Browser edits are batched, validated, and committed in one transaction that locks the channel row, checks the expected storage revision and writer lease fence, enforces operation idempotency, and saves the update plus sidecar.
  • Server-authored document edits, decisions, Chat messages, build graph updates, and lifecycle reports follow the same commit-before-publish rule.
  • Research requests commit before emitting research:changed. When an answer job finishes, publication creates the child channel (at revision zero) and links published_channel_id in one fenced transaction so neither half appears alone. See Background jobs and workers.
  • Document-summary jobs (output:"description" V1 artifacts) project their description and provenance under the writer fence without creating a collaboration commit. Generated descriptions are treated as untrusted model output.

Checkpoints and retention

A checkpoint stores canonical MDX, its source hash, complete Yjs bytes, epoch, generation, covered sequence, storage revision, and a sidecar snapshot. Writing a checkpoint atomically replaces the prior checkpoint and deletes already-covered rows from channel_updates.

Important retention caveats for operators:

  • Checkpointing does not prune channel_operations, channel_events, or MCP update replay records inside the sidecar; those remain until the document is deleted or cleaned up manually.
  • The Yjs update journal is a crash-recovery store, not a keystroke audit log.
  • Activity history (document_versions) is recorded separately after each source-changing commit. Edits by the same author within 10 minutes extend their current history session; another author, Chopin, or a longer gap starts a new session. Recording runs outside the critical commit path so a history write failure never blocks an edit. Restoring a past version commits a normal fenced rewrite while preserving current decision, questionnaire, research, and investigation cards.
  • Opening History triggers a version-summary background job (on the AI accounts of whoever opened History and asked first, running HISTORY_MODEL where those accounts offer it, else their default) to write one-line summaries for up to 20 unsummarized recent sessions, keyed by source hash so growing sessions are re-summarized automatically.

Recovery

When opening a document, PostgreSQL reads channel metadata, sidecar, checkpoint, journal updates, events, and Planner state in one REPEATABLE READ snapshot.

  • Avoid duplicate sidecar reads: Opening reads the checkpoint's copy of the sidecar only if the channel has never saved its own sidecar.
  • Answer before loading Chat rows: When chat_entries rows are current, PostgreSQL reads the sidecar without its transcript and loads chat_entries in parallel while restoring the document. plan:open answers as soon as the document is restored; the room then finishes awaiting and checking chat_entries before allowing any save or other read. Openings that must write immediately (settling a title, interrupted jobs, or a first checkpoint) wait for chat_entries first.

The room restores state in five steps:

  1. Validate the sidecar and checkpoint metadata.
  2. Load the Yjs document and confirm it matches the stored canonical MDX and source hash.
  3. Replay ordered journal updates from the matching epoch.
  4. Project the restored document to canonical MDX once to validate it. Opening reuses that projection without converting again, and re-parses it only when the document's title matters (deciding whether an active document needs its channel title written back, or whether an archived or build-locked document matches its channel title).
  5. Repair any broken anchors conservatively before returning the open snapshot.

Browser-created channels can exist with metadata alone until their first plan:open; MCP-created channels commit their initial checkpoint atomically with creation.

Documents kept in the browser

A reader's browser caches opened documents in IndexedDB (chopin-documents in apps/web/src/document-cache.ts). Reopening a document shows it immediately, read-only, while Chopin fetches only changes since the cached version. PostgreSQL stays the only authority.

  • What is cached: The document's Yjs state and epoch. PlanProvider (packages/editor/src/provider.ts) writes a cache copy after 2 seconds of quiet and when switching documents, only while the tab has zero unacknowledged edits. Unacknowledged edits live only in the in-memory outbox; caching one would make the next visit treat it as server-known state and never send it.
  • Cached first screen: Alongside the Yjs state, Chopin saves a static snapshot of the document's top screen (apps/web/src/first-screen.ts) with its column position and page CSS rules.
    • When opening a document URL directly, the browser reads that snapshot early and displays it as soon as the session confirms the same account, before the editor builds or the server responds. It disappears once the live editor renders.
    • If the server then refuses the document (403, 404, or a deleted/refused room), the browser removes the snapshot and deletes the cached copy immediately. Someone who lost access may see their own prior top screen briefly until the refusal arrives (at most two lookups if an early page-start lookup fails and the page open checks again).
    • The snapshot is reused only for the same app build, theme, and window size. It renders inside a closed shadow root with scripts, event handlers, frames, and interactive inputs stripped on capture and again before display.
  • Syncing from cache: plan:open sends the cached epoch and Yjs state vector so the server returns only the diff. The browser applies the cached state under the provider's origin so it is never echoed back as an edit, keeping the editor read-only until the server replies. If the epoch changed (after compaction or a rebuild) or the copy fails to apply, the browser deletes the cache and loads fresh from the server.
  • Opening at page start: Loading a document URL directly opens the room connection before the editor mounts (Real-time connection lifecycle). Once the session identifies the signed-in user, it waits up to 300 ms for the cached copy and sends that exact copy's epoch and state vector. The editor initializes from that same copy rather than re-reading IndexedDB. If the server answers with a different epoch, the editor builds from the server's full reply without asking again.
  • Per-account isolation and sign-out: Copies are keyed by account and document. Opening a document under a different account deletes the previous account's copies. Signing out deletes all copies before ending the session, and the sign-in screen clears them again. Every write checks inside the same IndexedDB transaction that the account still owns the store, and a clear timestamp prevents any older open tab from writing or deleting another account's copies afterward.
  • Refusals and renamed slugs: A 403, 404, or room refusal (by document URL, /channels/<id>, or parent of a child document) deletes the cached copy and records a refusal marker for both the document ID and address in the same transaction. Every read, write, and first-screen lookup checks that marker so another open tab cannot re-cache the document before its own room receives the refusal; only a fresh lookup started after the refusal clears it (prefetch lookups count from when they were sent). Every resolved URL—including renamed slugs, normalized with lowercase owner/repo and no trailing slash—is recorded immediately so refusing an old slug finds the cached copy too.
  • Limits and storage failures: Documents over 4 MiB of Yjs state are not cached. Above 64 MiB total or 100 documents (counting first-screen snapshots), least-recently-opened copies are evicted first; quota errors drop older copies to keep the newest. Changing the cache schema drops older versions and ignores newer versions from rolled-back deploys. Blocked site data, full disks, or damaged profiles simply skip caching; private windows clear copies when closed.

Planner ownership and sessions

PostgreSQL stores browser session IDs, user IDs, expiry times, and encrypted GitHub credentials (for hosted logins); raw cookie secrets stay only in the serving process.

On startup after claiming the writer lease:

  • Chopin clears web_sessions metadata-only/expired rows and resets Planner owner references (setting status to unavailable so the next writer starts fresh).
  • Exception for remote Planner handover: If planner_link_holds references a valid, unexpired credentialed session, Chopin keeps that owner reference so the reconnecting Planner client resumes seamlessly after a restart. Paired machine holds name the machine instead, so the machine's backend reclaims the document when it reconnects.
  • Child document cleanup: CollaborationStore.dropChildConversations clears any legacy Chat transcript or analysis state on child documents (which have no Chat UI), leaving questions, comments, and document content untouched. Any child whose decision records cite a Chat message is skipped and logged rather than broken.
  • Build runs survive restarts: Active external implementation runs keep their graph lock, progress, and history across server restarts.

Writer lease

Only one Chopin server process may write to a PostgreSQL database at a time, enforced by the chopin:writer lease row:

  • A second process exits at startup unless HANDOVER=wait is set, in which case it waits in standby until the active server releases the lease (see Deploys nobody can see).
  • The active server renews the lease every 10 seconds on a dedicated database connection (separate from the shared pool). If a renewal stalls past ~5 seconds it fails and retries; an unanswered renewal aborts at 6 seconds (terminating its PostgreSQL backend session); PostgreSQL also aborts any renewal transaction left idle for 2 seconds. If the lease is lost or the 25-second safety deadline expires, the server drains and stops.
  • Write fencing: Every fenced write locks the lease row FOR KEY SHARE plus a per-lease advisory lock so writes serialize cleanly while renewals (FOR NO KEY UPDATE) do not block behind writes, and takeovers (FOR UPDATE) wait for in-flight writes to finish before claiming the lease.
  • Lock-free polling: Standby processes call leases.peek (a plain SELECT with no row lock) and attempt acquire only once the lease shows as released or expired on PostgreSQL's clock.

Running multiple active writers simultaneously is not supported. See Self-hosting for backup and upgrade steps.

Migrations

SQL migrations live with the PostgreSQL adapter and run strictly in order, verified by checksums in chopin_migrations.

Run migrations manually from source:

bun run migrate

The Docker image runs migrations automatically before starting the server; overriding the container command skips automatic migrations. Because the migration runner loads the full app configuration, all required GitHub and OAuth environment variables must be set when running migrations standalone.

Rolling back past migration 062

A Chopin release older than migration 062_chat_entries refuses to start on a database where 062 ran, and cannot read documents whose sidecars omit the transcript.

To roll back to a pre-062 release, stop every Chopin server and run this single transaction. It copies each transcript from chat_entries back into sidecar only where the rows are current at the document's revision—leaving untouched any sidecar written since by an earlier release, which is already whole—building the JSON as raw text (preserving NULs and lone surrogates), and then undoes migration 062:

BEGIN;
LOCK TABLE channels, channel_state, chat_entries IN ACCESS EXCLUSIVE MODE;
UPDATE channel_state
SET sidecar = to_jsonb(
	left(channel_state.sidecar_core #>> '{}', -1)
	|| CASE WHEN channel_state.sidecar_core #>> '{}' = '{}' THEN '' ELSE ',' END
	|| '"transcript":['
	|| coalesce((
		SELECT string_agg(chat_entries.entry, ',' ORDER BY chat_entries.ord)
		FROM chat_entries WHERE chat_entries.channel_id = channel_state.channel_id
	), '')
	|| ']}'
)
FROM channels
WHERE channels.id = channel_state.channel_id
	AND channel_state.sidecar_core IS NOT NULL
	AND channel_state.transcript_revision = channels.revision;
DROP TABLE chat_entries;
ALTER TABLE channel_state DROP COLUMN sidecar_core, DROP COLUMN transcript_revision;
DELETE FROM chopin_migrations WHERE id = '062_chat_entries';
COMMIT;

Checkpoints need no changes: Chopin reads a checkpoint's sidecar only for documents that never saved a sidecar of their own, which still keep the whole sidecar. Upgrading again later re-applies migration 062 and reads each document from its sidecar until its next write.

A live database from an earlier release

Older Chopin releases queued Planner messages that could not start immediately in planner_deferred_turns and saved deliveryState on Chat entries. Current Chopin never queues messages for an absent Planner (a message starts a turn, steers a running turn, or is refused immediately), while handling existing rows cleanly:

  • Automatic cleanup at startup: Once the writer lease is acquired, deferredTurns.retire runs one idempotent fenced update: waiting rows become cancelled and started rows become interrupted, logging the count once.
  • Effect on old messages: Any previously waiting message remains in Chat as a normal posted message with its deliveryState and deliveryFailure badges stripped on load; the sender can ask again if needed.
  • Safe rollback: No schema migration is added and the table stays intact with closed rows, so rolling back to an earlier release works without restoring the database.
  • Deploy check: Before upgrading a live instance, run SELECT count(*) FROM planner_deferred_turns WHERE state IN ('waiting','started') to see if any users have messages waiting for an offline machine.

Adding an adapter

Storage adapters are compiled into Chopin (dynamic runtime loading of third-party storage packages is not supported). To add a new backend:

  1. Implement all stores in StorageAdapter under apps/server/src/storage/<driver>.
  2. Keep its schema and migrations in that folder.
  3. Wire configuration parsing and register the driver.
  4. Verify it against apps/server/src/storage/contract.ts using a real database instance, and add that check to CI.

Run the PostgreSQL storage contract and process-lifecycle tests with:

bun run test:postgres