Skip to content

Sync protocol

Access, snapshot, delta and push routes are implemented in contracts, the API, and the generated SDK. The space-scoped design owns engine semantics and the provider catalog.

Every request uses an authenticated user-scoped client and current database authorization. A cursor grants no access. Tokens have authenticated integrity and bind actor, space, Membership period, stream, projection version, fixed view, progress, and expiry. Bigint positions use decimal strings. Timestamps are display/conflict metadata, not continuation positions.

Access: GET /api/v1/sync/access

The first request has no cursor. Continuations use the returned opaque cursor. Pages contain up to 100 (group_id, membership_id) items, protocol_version: 1, projection_version: 1, scan_id, access_revision, server_time, valid_until, next_cursor, and complete. Only the final page has complete: true; its authority applies to the assembled pages from that exact revision, not the final page alone.

Read current access and revision consistently. A changed revision or elapsed deadline returns manifest_changed; restart the incomplete scan. Validity ends five minutes after scan start or at the next access-policy transition, whichever is earlier. An empty complete result is valid. Network errors, 401, partial/malformed pages, and unknown versions cannot prove absence. There is no conditional 304 shortcut in the initial protocol.

The current readable-space policy has no timed access transition, so Phase 1 uses the five-minute cap. Continuations bind the actor, scan, revision, keyset position, and deadline with an HMAC whose key stays in the private database schema. manifest_changed returns 409; invalid_cursor returns 400. The endpoint returns the existing success/error envelope and Cache-Control: no-store.

Clients apply complete observations through an account coordinator with persisted scan generation and last-applied access revision. Retirement compare-and-sets leases captured at scan start. Join/leave/deletion outcomes and token-proven revocations invalidate older scans. A delayed manifest cannot retire a newly joined Membership or its queue. Same-revision time transitions require a current scan; expiry is not proof of missing membership.

Snapshot: POST /api/v1/sync/snapshot, GET /api/v1/sync/snapshot

POST begins a read session for one authorized space/stream/view. The body contains protocol version, projection version, group and Membership identity, stream kind, and fixed Timeline dates/timezone identity. Content projection 8 adds shared Recipe and Variation nutrition (recipe_nutrition, key [id]) to library after recipe_notes; projection 7 added Variation kinds, owners and line patches (D-212), and projection 6 Recipe categories (D-211). Content projection 5 adds kind to meal_ideas rows (D-210). Projection 4 added recurring_meals to shared after meal_entries, and both recurrence links to Entry rows (see recurring meals). It follows window-free meal_ideas in library (projection 3, D-186) and the Recipe Entry fields of projection 2. Access projection and protocol remain 1. A request or validly signed cursor with an older content projection returns protocol_incompatible. Clients replace older cached views with fresh snapshots and preserve their queued commands. An invalid signature remains invalid_cursor. It captures committed head B and returns a snapshot cursor plus a delta cursor at B. It creates no domain rows and accepts no arbitrary table name.

GET accepts the snapshot cursor and returns an immutable-key page from the active provider catalog. Fields are operations, observed_through, next_cursor, and scan_complete. Operations are current authorized upserts with typed keys and validated projections. scan_complete means every entity was scanned; the client must catch up from B before publishing the replacement view. Empty entity pages are valid, but never imply completion of other entities.

Snapshot cursors expire after one hour. Changed Membership, policy/projection generation, window, or a pruned B invalidates the scan. Discard staging and recover only that scope, preserving eligible pending commands and the prior readable base. A transient error does not erase the base.

Delta: GET /api/v1/sync/pull

The cursor identifies one space/stream/view and scanned journal position. There is no since timestamp, timestamp overlap, or full-ID reconciliation endpoint. Scan at most 200 journal references per page and return:

FieldMeaning
operations{ entity, key, kind: "upsert", row } or { entity, key, kind: "remove" }; removals carry no body.
observed_throughCommitted head at which current projections were read, as a decimal string.
next_cursorContinuation after the last scanned reference, present even when caught up.
caught_upScanned position reaches this read's observed head, with no references remaining.

Read head locks first, then references and projections in a fresh statement snapshot. Rehydration may observe changes newer than an individual scanned reference. Clients track per-key observation versions separately from scanned progress and retain staged removals against delayed upserts. Publish staged base changes and the checkpoint together only after catch-up and a local lease check. Empty filtered pages still advance scanned progress.

An Entry moved outside the fixed window returns removal; moving inside returns upsert. Deletion references retain resolved Meal Space identity after parent deletion. Shared and actor-private streams have separate positions. Private changes never enter another actor's response.

Snapshot/delta pages cap rows/references at 200 and uncompressed responses at 2 MiB. Providers must bound individual projections to fit. Oversized rows produce projection_too_large, never truncated success. Unknown entities/invalid rows reject the whole page without progress. Cursors below the retained floor return cursor_expired. Initial retention is 30 days, not a maximum offline duration.

Push: POST /api/v1/sync/push

Each command contains a stable operation ID, group ID, originating Membership period, fixed kind, and validated payload. The server derives actor from auth.uid() and action from command kind. Client roles, sponsorship, cached summaries, and local leases are never permission evidence.

The outer sync_push_apply RPC prelocks affected identities in canonical order and dispatches to the same focused mutations as REST. Return an exact partition of operation IDs into accepted and rejected dispositions. Duplicate IDs, unknown kinds, and malformed envelopes fail before applying. Rejections use closed class/reason enums. Safe server projections may appear only while the actor can currently read them.

  • Expected access_denied, domain_conflict, and validation_failed outcomes are isolated per command. Concealed tenant failures use not_found without shared payloads.
  • Infrastructure failure rolls back the outer batch. Retry the same IDs with backoff, including after a lost response. Receipts follow the existing privacy-safe replay contract.
  • A new write must match the current Membership period and action decision. Rejoin cannot revive old commands. An update to a missing row never becomes an insert.
  • Snapshot omission changes the base, not the pending command; its focused mutation supplies a named rejection. Ordinary writes use client_updated_at LWW.
  • M2 Recipe base edits use apply_recipe_edit with opening revision/aggregate and local candidate. A true collision commits no part of that Recipe and becomes local Needs review work. An explicit user resolution makes a new command against the latest revision. Canonical no-ops emit no activity.

Clients park readable rejected input and never automatically replay it after promotion. Confirmed access loss disposes affected shared payloads. Queue acknowledgement and local adoption share a lease-checked transaction; stale acknowledgements change nothing. Server time is not a pull cursor.

Failure dispositions

manifest_changed and invalid_cursor are implemented in the existing strict error envelope. Snapshot and delta dispositions below are implemented. Push dispositions remain in its planned section.

Reason / outcomeClient behavior
manifest_changedRestart enumeration; accumulated pages cannot prove absence.
cursor_expired, snapshot_expiredRecover the affected view; preserve eligible queue.
scope_changedRefresh access and recover the current projection/policy/window.
scope_revokedOnly from a valid prior token proving lost Membership; lease-check, fence, and purge.
not_foundPause affected work and refresh access; a missing row alone cannot prove space loss.
invalid_cursor, invalid requestReject; retain progress and report a protocol error.
protocol_incompatibleShow update required and pause all content in the current runtime; preserve pending work, checkpoints and staging. Compatible access checks and cleanup continue.
projection_too_largeStop affected recovery, retain work/progress, report provider error.
401Pause for reauthentication; retain encrypted state.
429, timeout, unavailable, deadlock/serialization rollbackPreserve identities/progress and retry with jittered backoff.
Unknown/malformed responseApply nothing and report protocol error; never treat as empty success.

The M1 content endpoints share a protocol. One named incompatibility response stops automatic content requests across Meal Spaces until an explicit runtime reopen or app restart. Native Retry after updating reopens the same database; it does not clear progress or create new operation IDs. If the access endpoint itself returns protocol_incompatible, automatic access requests also stop until a new runtime starts. This named response is separate from the malformed-response diagnostic streak. Network and authentication failures during later compatible access checks remain visible without clearing the content pause.

Before any request capable of observing revocation, persist a pending-observation marker. Clear it only after handling the result and committing any required cleanup intent. After a crash with unresolved observations, complete a fresh access check before reopening old cached content. A handled network failure without an authoritative observation may clear its marker without purging. Realtime only prompts authorized reads; it cannot replace their results.

Snapshot/delta implementation notes

The begin body has protocol_version, projection_version, group_id, membership_id, stream, from, until, and planning_timezone. Dates must describe the current Timeline interval. The response contains captured_head, snapshot_cursor, and delta_cursor. Snapshot pages traverse shared groups then meal_entries; private snapshots traverse user_group_prefs. A full 200-row page may need an empty follow-up page to establish the end of that provider.

Delta tokens expire after 30 days and renew on each successful pull. Snapshot tokens retain their original one-hour expiry across pages. Retention can invalidate either earlier. Cursor key IDs allow a new active signer while older verification keys remain. Never remove a verification key until every issued token has expired. No request role can read these keys.

Timezone aliases preserve their spelling through the signed view identity. PostgreSQL posix/ aliases normalize to the corresponding ordinary name at the settings write boundary. The old Factory placeholder migrates to UTC; new writes reject it. A Planning timezone change invalidates the current token and requires a replacement view.

packages/sync validates pages and stages per-key observation versions through the injected DataStore. It publishes after delta catch-up, committing rows and cursor together under the scope lease. A failed request leaves the readable base intact. A confirmed revocation must finish its durable fence before clearing the pending-observation marker. Phase 5 persists these markers and fences in SQLite; the storage runbook describes restart recovery.

GET /api/v1/sync/view?group_id=…&membership_id=… returns from, until, and planning_timezone from the server clock and current Meal Space settings. Use it for initial bootstrap and view replacement. It authorizes the exact current Membership and returns no shared content. This resolves the date window before a client has its first groups projection.

Implemented push envelope

POST /api/v1/sync/push accepts { commands: [...] }, with 1–50 commands and a 2 MiB body limit. Each command has operation_id, group_id, entry_id, kind and the corresponding Entry request in input. The originating membership_id stays inside that immutable input. No HTTP idempotency header is required; each operation owns its receipt.

kind: reorder requires anchored placement input: membership_id, client_updated_at, entry_date, nullable slot, anchor_entry_id, and side of before or after. Relative direction requests are available only through the direct reorder route. A changed source or neighbor schedule is a domain conflict. The client persists the selected anchor and request ID; it never translates a retry into another relative step.

The SQLite queue treats each reorder as a barrier for that Meal Space. Earlier changes settle first, the reorder is claimed alone, and later changes wait for atomic catch-up and acknowledgment. Coalescing cannot cross the barrier or consume a reorder. Rejected dependencies remain in Needs review and block later changes in that space while other spaces can sync.

The result partitions every operation exactly once into accepted (content-free Entry result) or rejected (access_denied, domain_conflict, or validation_failed, plus a closed reason). Duplicate operation IDs reject the whole envelope. Unexpected database failures roll back the batch and return 503; retry the same IDs and payloads. Current authority is checked even on replay.

The engine ports TogetherDone's serializer and exponential backoff. A single scheduler runs complete access checks, scoped pulls and claims. Remote hints coalesce for 250 ms; local writes debounce for 500 ms; foreground access polling runs every 30 seconds. Failed attempts use jitter and a 60-second backoff cap. Stop drains in-flight work and cancels trailing runs. Each cycle sends at most four batches, then schedules a follow-up if pending work remains. If no command can be claimed, blocked intent waits for an explicit wakeup or normal foreground polling. Explicit rejections park immediately, before catch-up can fail. Accepted acknowledgements publish with catch-up rows and cursor in one store transaction. Durable queue claiming and settlement are supplied by the SQLite adapter. Scope/view generations guard every commit; a changed view retains operation IDs and a new Membership disposes the former queue.

Idea commands

Push accepts idea_create, idea_edit, idea_delete, idea_link, and idea_reorder. Each command includes operation_id, group_id, idea_id, and its focused command input. Create gets its id from the envelope. The operation id is the same receipt identity used by REST; expected_command_id on a delete names a successful predecessor for that Idea, actor and Membership. Missing or pruned dependencies are conflicts, never permission to delete the newest version. Stale Idea outcomes are rejected conflicts and must be reviewed with a fresh operation id.

Scheduling, converting to a Recipe and copying to another Meal Space are REST-only compound actions. Scheduling retains the Idea. Optional removal is a separate conditional delete after schedule success, using the returned Idea version. Sync does not combine these actions into one command.