Skip to content

feat(spaces): default-off cell sync API with fenced snapshots and optimistic mutations (B3) - #24868

Merged
Git-on-my-level merged 20 commits into
mainfrom
pgf/b3-spaces-sync
Nov 8, 2026
Merged

Git-on-my-level merged 20 commits into
mainfrom
pgf/b3-spaces-sync

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Requested by David

What changed and why

Add the default-off /v1/spaces/{sid}/{changes,snapshot,mutations,cursors} protocol over the cell store. The personal pilot requires sid == authenticated uid and an active owner membership. Snapshot starts retain 30/hour while signed continuations use 600/minute; invalid/forged tokens consume the start bucket. The four BYOK policies match the auth dependency. Route admission runs before FastAPI body parsing; cell failures retain safe type-only diagnostics.

Product invariants affected

B3 adds no invariant-globbed paths. B2 (#24805, merged) retains INV-CUTOVER-1 and INV-MEM-3; their existing fences remain authoritative.

How it was verified

Required R3 suites: 278 passed, 0 failed, 1 existing fakeredis/Lua skip. Environment preflight passed (18 checks, 8 optional warnings), async scan found no blockers, and route-policy baseline/inventory and PR metadata checks passed. Broader verification is blocked: repo-wide type checking hit its 1,800-second wall budget without diagnostics; make preflight stopped on a Firestore query-shape file timeout at the unchanged 300-second budget. Two isolated retries also timed out; the diagnostic retry reached 96% with no assertion failure reported. No full preflight/type-check pass or remote CI result is claimed. Credential-scrubbed local Python 3.11, synthetic authentication and private disposable PostgreSQL only; no production access or GCP tier.

Exact commands and evidence are in the local lane report .agent-artifacts/pgf/b3-fix-r3-result.md. The full backend selector was not executed, per fix-r3.

Tests

Regression tests cover another uid granted the owner role receiving 404 on all four routes, the personal uid still requiring an active owner role, BYOK rejection through the real auth dependency, a >30-page snapshot with the start bucket exhausted, epoch restart charging, invalid and forged token charging, signed-token space/since/address binding, the separate rate budgets and all four BYOK declarations.

UI evidence

UI-Evidence: none -- backend only

Failure class (fixes)

Failure-Class: none

Scoped cleanups (optional)

Reject malformed directory cell values, log unexpected exception types without sensitive details, and document the fingerprint-key divergence. The generated registry retains its owning date per lead direction. Ships dark; rollback is SPACES_SYNC_API_ENABLED=false. No client or domain adapter in B3; app-client OpenAPI remains untouched until W7. Pilot policies: changes/cursors 600/minute, snapshot starts 30/hour and continuation pages 600/minute, mutations 120/hour. Personal spaces only until shared-space write policy and cursor namespaces land; snapshot consumers keep page 1's head and restart on epoch changes.

Accepted protocol decisions remain: conflicts are recomputed without conflict receipts; fingerprint canonicalization stays isolated from Firestore and uses the base key; both 425 recovery conditions use resync_required plus reason. The personal-space pilot has no entity write allowlist and is owner-only: every route requires sid == uid and an active owner membership, so another uid (including one with an owner role) or a member row grants no sync access until W7 defines shared-space role policy (merge-owner review of cb6f132). Integer revisions are authoritative; datetime tokens provide released-client compatibility.

Merge order is B1 → B2 → B3. Deploy dark; enabling the backend flag requires B2's routing, migration, provisioning and admission runbook first. W7 owns the first client ramp under SUPPORTS_OFFLINE_CACHE. Rollback disables the flag immediately; previously committed mutations remain ordinary cell data covered by wipe/purge.

Long-term data foundation wave B3 (follows #24805). Rebased on main after #24805 merged; focused suites (spaces router, cell conformance, directory store/router, wipe, lifecycle inventory, async boundaries) 1940 passed on the rebased head. Default-off: SPACES_SYNC_API_ENABLED gates every route before body parsing.

🤖 Generated with Claude Code

Review fixes (round 2)

  • Resolve datetime revisions using database-clock timestamps assigned monotonically under the sequence-allocation lock. Row updated_at exposes that same microsecond-stable timestamp for datetime token round trips. Migration 0003_revision_timestamps.sql preserves change-log event/retention timestamps; older unstamped history requires an integer rebase.
  • Reject unsupported cell labels before constructing or reading the singleton cell store.
  • Include feed-shaped deletion entries in snapshot pages (including since), sharing the row keyset/page budget and suppressing tombstones for recreated rows.
  • Replay the original receipt revision even after another writer advances or recreates the row.

Regression coverage includes confirmed PostgreSQL row-lock contention with reversed caller timestamps, unknown-cell admission on all routes, incremental deletion reconciliation and pagination, and patch/delete replay after a concurrent advance. Fresh round-two required suites: 88 router + 36 cell conformance + 12 directory = 136 passed, zero failed/skipped, on d2d9fb83434. Type check (0 errors), async scan (0 findings), and final make preflight (44 checks) also pass. Broad selector coverage and the vendor-drill timeout retry are recorded in .agent-artifacts/pgf/b3-fix-r2-result.md.

Review fixes (round 3)

  • Require sid == authenticated uid AND active owner membership. Another uid with an owner role gets the same 404 as non-membership on all four routes.
  • Keep snapshot starts and epoch restarts at 30/hour; continuations use 600/minute (up to 300,000 rows/minute at the 500-row page budget). HMAC-SHA256 HTTP tokens bind sid, since and address; invalid/forged tokens consume the start bucket.
  • Correct all four BYOK declarations to validated_when_headers_present, matching get_current_user_uid and its BYOK validation. The existing generator regenerated the review inventory; no tracked generated policy copy exists.

Required R3 suites: 278 passed, 0 failed, 1 existing fakeredis/Lua skip. Environment preflight passed (18 checks, 8 optional warnings), async scan found no blockers, and route-policy baseline/inventory and PR metadata checks passed. Broader verification is blocked: repo-wide type checking hit its 1,800-second wall budget without diagnostics; make preflight stopped on a Firestore query-shape file timeout at the unchanged 300-second budget. Two isolated retries also timed out; the diagnostic retry reached 96% with no assertion failure reported. No full preflight/type-check pass or remote CI result is claimed. Credential-scrubbed local Python 3.11, synthetic authentication and private disposable PostgreSQL only; no production access or GCP tier.

Review fixes (round 4)

  • Encode binary values recursively in changes, snapshots and mutation-conflict rows as the cell codec's reserved singleton {"$bytes": "<base64>"}. The OpenAPI field descriptions specify this wire convention; nested objects/lists, empty bytes and UTF-8 bytes use the same reversible encoding.
  • Decode tagged mutation fields before applying them, retain native bytes through the route, and use the existing cell JSON codec for stable mutation fingerprints. Invalid tags return 422 before cell I/O; the existing 128 KiB limit measures the encoded operation.
  • Reproduced the original failure in all three response shapes before fixing it (3 failing regressions). Post-fix spaces HTTP suite: 114 passed; cell conformance: 36 passed, zero failures/skips. The new tests return each response document through mutation input and assert exact stored bytes, idempotent replay, and changed-byte mutation-ID conflicts. Shared codec verification and metadata checks are recorded in .agent-artifacts/pgf/b3-fix-r4-result.md.

R4 uses credential-scrubbed Python 3.11 and private disposable PostgreSQL only. No production access or GCP tier. Full selector, full preflight and repo typecheck are deliberately deferred to the lead push gate per the R4 brief; this round makes no new claim about those gates or remote CI.

@Git-on-my-level Git-on-my-level self-assigned this Nov 7, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-08T05:17:39.507388Z 41d627e New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cb6f132bc8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/models/space_sync.py Outdated
entity_id: str
author_id: str
rev: int
doc: dict[str, Any]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Encode native cell values before serializing sync rows

When a cell document contains non-UTF-8 bytes, this response model cannot serialize it: the cell pool restores native bytes through database/jobstore/codec.py, while Pydantic's default JSON serialization treats bytes as UTF-8. This is supported cell data, explicitly exercised with b'\x00\xff' in test_doc_semantics_and_rollback. Consequently, /changes and /snapshot return serialization errors for pages containing such documents, and mutation conflicts containing the same row fail as well, preventing clients from syncing valid stored data. Add a wire-safe encoding for native cell values rather than returning the decoded document unchanged.

Useful? React with 👍 / 👎.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3 issues found across 18 files

Confidence score: 3/5

  • backend/models/space_sync.py can fail to serialize valid non-UTF-8 cell bytes, breaking changes, snapshots, and mutation conflicts. Encode byte-valued document fields with a wire-safe representation before serializing SpaceRow.doc.
  • cursors in backend/routers/spaces.py runs SQL outside CellStore. Move the state read into a CellStore method and have the route call it.
  • pull in backend/database/cells/feed.py reads space_heads again even though _floor already did so in the same snapshot. Reuse _floor's values and drop the extra query.

You’re at about 92% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact [email protected].

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/routers/spaces.py">

<violation number="1" location="backend/routers/spaces.py:223">
P3: The `cursors` route runs its own SQL through `store.pool.connection()`. Move this state read into a `CellStore` method next to `head()`/`set_cursor()`, and have the router call that method.</violation>
</file>

<file name="backend/database/cells/feed.py">

<violation number="1" location="backend/database/cells/feed.py:143">
P3: The final `read_enrolled_head` call in `pull` repeats a space_heads read that `_floor` already performed in the same snapshot. Use the values from `_floor` and drop the extra query.</violation>
</file>

<file name="backend/models/space_sync.py">

<violation number="1" location="backend/models/space_sync.py:26">
P2: Encode byte-valued document fields with a wire-safe representation before serializing `SpaceRow.doc`; the default UTF-8 serializer raises on valid non-UTF-8 cell bytes, breaking changes, snapshots, and mutation conflicts.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread backend/database/cells/store.py Resolved
Comment thread backend/utils/rate_limit_config.py Resolved
Comment thread backend/database/cells/mutations.py Resolved
Comment thread backend/database/cells/feed.py Resolved
Comment thread backend/routers/spaces.py Resolved
Comment thread backend/models/space_sync.py Resolved
Comment thread backend/routers/spaces.py
store.set_cursor(sid, request.device_id, last_seq=request.last_seq, now=time.time())
# One read keeps the persisted monotonic cursor, head and epoch consistent,
# including an advance or purge racing this acknowledgement.
with store.pool.connection() as conn:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The cursors route runs its own SQL through store.pool.connection(). Move this state read into a CellStore method next to head()/set_cursor(), and have the router call that method.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/routers/spaces.py, line 223:

<comment>The `cursors` route runs its own SQL through `store.pool.connection()`. Move this state read into a `CellStore` method next to `head()`/`set_cursor()`, and have the router call that method.</comment>

<file context>
@@ -0,0 +1,232 @@
+        store.set_cursor(sid, request.device_id, last_seq=request.last_seq, now=time.time())
+        # One read keeps the persisted monotonic cursor, head and epoch consistent,
+        # including an advance or purge racing this acknowledgement.
+        with store.pool.connection() as conn:
+            state = conn.execute(
+                'SELECT c.last_seq, h.next_seq, h.epoch FROM sync_cursors c '
</file context>

)
head = conn.execute('SELECT next_seq, epoch FROM space_heads WHERE space_id=%s', (space_id,)).fetchone()
return PullPage(entries, rows, raw[-1][0] if raw else cursor, head[0] if head else 0, head[1] if head else 0)
head, epoch = read_enrolled_head(conn, space_id)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The final read_enrolled_head call in pull repeats a space_heads read that _floor already performed in the same snapshot. Use the values from _floor and drop the extra query.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/database/cells/feed.py, line 143:

<comment>The final `read_enrolled_head` call in `pull` repeats a space_heads read that `_floor` already performed in the same snapshot. Use the values from `_floor` and drop the extra query.</comment>

<file context>
@@ -116,8 +140,52 @@ def pull(self, space_id: str, *, cursor: int, limit: int = 200, now: float) -> P
                     )
-            head = conn.execute('SELECT next_seq, epoch FROM space_heads WHERE space_id=%s', (space_id,)).fetchone()
-        return PullPage(entries, rows, raw[-1][0] if raw else cursor, head[0] if head else 0, head[1] if head else 0)
+            head, epoch = read_enrolled_head(conn, space_id)
+        next_cursor = raw[-1][0] if len(raw) == limit else head
+        return PullPage(entries, rows, next_cursor, head, epoch)
</file context>

Comment thread backend/route_policy_manifest.yaml Resolved
Active membership alone let a 'member' row snapshot and mutate a personal
space. Every /v1/spaces route now requires an active owner membership until
shared-space role policy lands.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5d656b64ee

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

raise conflict('revision_unavailable', _current_row(tx.conn, space_id, entity, entity_id))
if base != rev:
raise conflict('base_revision_mismatch', _current_row(tx.conn, space_id, entity, entity_id))
buffer(tx, {**doc, **operation.get('fields', {})}, rev)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate reserved codec tags before committing patch fields

With the sync API enabled, a valid mutation containing fields: {"metadata": {"$datetime": "not-a-date"}} passes request validation and is committed unchanged. However, database/jobstore/codec.py interprets single-key $datetime and $bytes objects when loading JSONB; this example raises ValueError on every subsequent document read. Consequently, snapshot/change pages containing the row return 503, and even attempts to repair or delete it through this API fail because mutations first read the poisoned document. Reject malformed reserved-tag objects recursively, or decode and validate the wire representation before persisting it.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 41d627ef11

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +22 to +24
if isinstance(value, (list, tuple)):
return [_encode_document_value(item) for item in value]
return value

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve datetime types in document wire round trips

When a stored document contains a native datetime, this encoder leaves it unchanged and Pydantic serializes it as an ordinary ISO string. Sending that document back in mutation fields then persists the string because _decode_document_value only restores bytes. Thus, a read/edit/write round trip silently changes supported cell data types, including nested datetime values explicitly exercised by test_doc_semantics_and_rollback. The new $bytes handling fixes binary round trips, but datetime values still need an unambiguous wire representation and corresponding decoding so clients can preserve timestamps without confusing them with literal strings.

Useful? React with 👍 / 👎.

Comment on lines +236 to +239
head, _epoch, revision_us = self.conn.execute(
'UPDATE space_heads SET next_seq=next_seq+%s, updated_at=%s, '
'revision_us=greatest((extract(epoch FROM clock_timestamp())*1000000)::bigint, revision_us+1) '
'WHERE space_id=%s AND NOT tombstoned RETURNING next_seq, epoch, revision_us',

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bind datetime revisions to an observed committed version

When a client uses a wall-clock datetime as its base revision while another write is in flight, optimistic concurrency can accept an unseen update. flush() samples this timestamp before writing the documents and before CellStore.run() commits. A client can therefore read the old document and capture a datetime after that sample but before the commit; once the writer commits, seq_as_of() resolves the client's token to the newer revision, and the mutation passes the revision check instead of returning a conflict. This can overwrite a concurrent edit, especially during a slow multi-document flush or commit. Bind datetime tokens to an observed document revision, rather than treating this pre-commit timestamp as proof that the client saw the write.

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit e8aab05 into main Nov 8, 2026
67 checks passed
@Git-on-my-level
Git-on-my-level deleted the pgf/b3-spaces-sync branch November 8, 2026 07:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant