Repository navigation
feat(spaces): default-off cell sync API with fenced snapshots and optimistic mutations (B3) - #24868
Conversation
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
| entity_id: str | ||
| author_id: str | ||
| rev: int | ||
| doc: dict[str, Any] |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
3 issues found across 18 files
Confidence score: 3/5
backend/models/space_sync.pycan 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 serializingSpaceRow.doc.cursorsinbackend/routers/spaces.pyruns SQL outsideCellStore. Move the state read into aCellStoremethod and have the route call it.pullinbackend/database/cells/feed.pyreadsspace_headsagain even though_flooralready 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
| 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: |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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>
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]>
There was a problem hiding this comment.
💡 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) |
There was a problem hiding this comment.
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 👍 / 👎.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 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".
| if isinstance(value, (list, tuple)): | ||
| return [_encode_document_value(item) for item in value] | ||
| return value |
There was a problem hiding this comment.
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 👍 / 👎.
| 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', |
There was a problem hiding this comment.
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 👍 / 👎.
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 requiressid == authenticated uidand 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-1andINV-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
basekey; both 425 recovery conditions useresync_requiredplusreason. The personal-space pilot has no entity write allowlist and is owner-only: every route requiressid == uidand an activeownermembership, so another uid (including one with an owner role) or amemberrow 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)
updated_atexposes that same microsecond-stable timestamp for datetime token round trips. Migration0003_revision_timestamps.sqlpreserves change-log event/retention timestamps; older unstamped history requires an integer rebase.entriesin snapshot pages (includingsince), sharing the row keyset/page budget and suppressing tombstones for recreated rows.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 finalmake 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)
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)
{"$bytes": "<base64>"}. The OpenAPI field descriptions specify this wire convention; nested objects/lists, empty bytes and UTF-8 bytes use the same reversible encoding..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.