Skip to content

perf(sync): checkpoint and mark a ledger segment in one transaction - #24253

Merged
Git-on-my-level merged 2 commits into
mainfrom
lane/fswrites-sync-ledger
Nov 1, 2026
Merged

Git-on-my-level merged 2 commits into
mainfrom
lane/fswrites-sync-ledger

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Summary

Firestore write cut (lead ruling 268f54: "take every efficiency gain").

Every successful sync segment with a content ledger ran two transactions on the same users/*/sync_content_ledger/{content} document: checkpoint_sync_content_partial_result, then add_processed_sync_segment_id. Each did one read and one write. The write probe (#24218) measured both at about 0.49-0.50M writes/day on backend-sync plus backfill on Sunday 2026-11-01, so this cut saves:

  • ≈0.5M writes/day and ≈0.5M reads/day on Sunday;
  • about $0.9/day on Sunday and about $1.7/day on weekdays, at $1.385/M writes plus $0.461/M reads.

database.sync_ledger.checkpoint_and_mark_sync_segment now does both in one transaction (one read, one write). The pipeline uses it whenever the segment has an ID; segments without one keep the checkpoint-only call.

Outcomes and failure points are unchanged:

  • Foreign or stale owner: nothing is written, and the pipeline raises SyncJobRunLeaseLost where the old checkpoint raised (inside the segment lock, before the job marker).
  • Already-processed segment: the partial result is still checkpointed, as the old checkpoint did, and the pipeline raises after the job marker, where the old mark raised.
  • Silence-only segments (no result to checkpoint) still use add_processed_sync_segment_id.

The ledger's processed marker now commits atomically with its result contribution, instead of after it by ordering. The cumulative partial is still written under segment_lock, so concurrent segments cannot regress it.

Crash windows: a retry skips a segment if either the job marker or the ledger marker is set (pipeline.py ~3311).

  • New window (ledger marked, job marker not yet written): the retry skips the segment, and its ledger partial is guaranteed present.
  • The old window (ledger partial written, nothing marked) reprocessed the segment. That is not weaker.

Product invariants affected

  • INV-DATA-1 (path match: utils/sync/pipeline.py, database/sync_ledger.py): same document, fields, owner fence and ordering guarantees. The checkpoint and marker become one atomic commit.

Verification

All runs used backend/test.sh under bin/omi-heavy + nice -n 19, at the unit layer, unless noted:

  • New tests/unit/test_sync_ledger_checkpoint_mark.py (6): owned new segment → one write carrying both fields; already processed → checkpoint only; four foreign-owner shapes → no write.
  • test_sync_v2 (175), test_sync_silent_failure (65), test_sync_two_lane (47), test_sync_geolocation_enrichment (6), test_sync_cap_coordinator (41), test_wal_audio_coverage_pipeline (10): pass. Tests that mocked the two calls now mock the combined call where a segment ID exists.
  • Hermetic e2e (backend/testing/e2e/run.sh -k sync): 11 passed.

Rollback

Revert. No data migration: the document shape is identical.

Failure-Class: none

Line-Count-Exception: backend/utils/sync/pipeline.py | 3937 -> 3959 | one combined ledger call beside the existing checkpoint path, with its raise points kept where the separate calls raised; no new pipeline logic

🤖 Generated with Claude Code

View guided diff Turn on auto-fix

Each successful sync segment ran two transactions on the same content
ledger document (checkpoint, then processed marker): ~0.5M writes and
~0.5M reads/day each on 2026-11-01. Combine them into one commit with the
same owner fence and the same raise points.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-11-01T16:04:52.673835Z
We couldn’t complete this review. Comment @codex review to try again.
dc28d19 PR opened
ℹ️ 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

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@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.

2 issues found across 6 files

Confidence score: 4/5

  • test_sync_ledger_checkpoint_mark.py could pass even if the checkpoint write replaces the ledger and drops its owner and processed-marker fields. Assert the recorded (data, merge) values.
  • test_sync_v2.py could pass even if the transactional helper is bypassed, because the legacy mock raises the same exception. Make the test distinguish those paths.
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/tests/unit/test_sync_v2.py">

<violation number="1" location="backend/tests/unit/test_sync_v2.py:2723">
P2: This setup leaves the regression test unable to prove that the transactional helper is used: the legacy mock raises the same exception, so bypassing `checkpoint_and_mark_sync_segment` still produces `upstream_error`. Make the legacy mock non-raising or assert it is unused, and assert `checkpoint_and_mark_sync_segment` was called once.</violation>
</file>

<file name="backend/tests/unit/test_sync_ledger_checkpoint_mark.py">

<violation number="1" location="backend/tests/unit/test_sync_ledger_checkpoint_mark.py:48">
P2: This assertion ignores whether the already-processed checkpoint uses `merge=True`, so a replacing write that wipes the ledger owner and processed-marker fields would pass the test. Assert the recorded `(data, merge)` tuple, not only `data`.</violation>
</file>

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

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

stubs['pipeline'].compute_sync_segment_id = MagicMock(return_value='segment-1')
stubs['pipeline'].process_segment = MagicMock(return_value=True)
stubs['pipeline'].checkpoint_sync_content_partial_result.side_effect = RuntimeError('ledger unavailable')
stubs['pipeline'].checkpoint_and_mark_sync_segment = MagicMock(

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: This setup leaves the regression test unable to prove that the transactional helper is used: the legacy mock raises the same exception, so bypassing checkpoint_and_mark_sync_segment still produces upstream_error. Make the legacy mock non-raising or assert it is unused, and assert checkpoint_and_mark_sync_segment was called once.

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/tests/unit/test_sync_v2.py, line 2723:

<comment>This setup leaves the regression test unable to prove that the transactional helper is used: the legacy mock raises the same exception, so bypassing `checkpoint_and_mark_sync_segment` still produces `upstream_error`. Make the legacy mock non-raising or assert it is unused, and assert `checkpoint_and_mark_sync_segment` was called once.</comment>

<file context>
@@ -2720,6 +2720,9 @@ async def test_success_metric_waits_for_durable_segment_checkpoint(self, fenced_
             stubs['pipeline'].compute_sync_segment_id = MagicMock(return_value='segment-1')
             stubs['pipeline'].process_segment = MagicMock(return_value=True)
             stubs['pipeline'].checkpoint_sync_content_partial_result.side_effect = RuntimeError('ledger unavailable')
+            stubs['pipeline'].checkpoint_and_mark_sync_segment = MagicMock(
+                side_effect=RuntimeError('ledger unavailable')
+            )
</file context>

def test_already_processed_segment_still_checkpoints_like_the_separate_calls():
outcome, sets = _run({**OWNED, 'processed_segment_ids': ['seg-2']})
assert outcome == sync_ledger.SEGMENT_ALREADY_PROCESSED
assert [data for data, _ in sets] == [{'partial_result': {'conversation_ids': ['c']}, 'updated_at': NOW}]

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: This assertion ignores whether the already-processed checkpoint uses merge=True, so a replacing write that wipes the ledger owner and processed-marker fields would pass the test. Assert the recorded (data, merge) tuple, not only data.

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/tests/unit/test_sync_ledger_checkpoint_mark.py, line 48:

<comment>This assertion ignores whether the already-processed checkpoint uses `merge=True`, so a replacing write that wipes the ledger owner and processed-marker fields would pass the test. Assert the recorded `(data, merge)` tuple, not only `data`.</comment>

<file context>
@@ -0,0 +1,58 @@
+def test_already_processed_segment_still_checkpoints_like_the_separate_calls():
+    outcome, sets = _run({**OWNED, 'processed_segment_ids': ['seg-2']})
+    assert outcome == sync_ledger.SEGMENT_ALREADY_PROCESSED
+    assert [data for data, _ in sets] == [{'partial_result': {'conversation_ids': ['c']}, 'updated_at': NOW}]
+
+
</file context>

@Git-on-my-level
Git-on-my-level merged commit 0a27151 into main Nov 1, 2026
61 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/fswrites-sync-ledger branch November 1, 2026 18:06
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