Skip to content

fix(realtime): a file write is one executor submission; a failed resync is retried - #510

Merged
HananKavitzAmat merged 1 commit into
chunkhound:mainfrom
fstrasz:fix/resync-handover-upstream
Nov 16, 2026
Merged

HananKavitzAmat merged 1 commit into
chunkhound:mainfrom
fstrasz:fix/resync-handover-upstream

Conversation

@fstrasz

@fstrasz fstrasz commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Problem

A resync can fail every time it lands in the middle of a realtime file write, and then it is never retried.

A realtime file write was one DuckDB transaction spread over about six SerialDatabaseExecutor submissions, with awaits between them: begin, get file, update or insert, get chunks, delete, insert, commit. A resync's Rust-pipeline handover first calls set_rust_pipeline_in_progress(True) and then release_for_rust_pipeline(). If it lands between two of those submissions:

  1. The guard rejects the open transaction's remaining operations, and its rollback too, with DatabaseRustPipelineInProgressError.
  2. release_for_rust_pipeline() then runs its bypassed disconnect, whose CHECKPOINT runs inside the still-open transaction and fails with Cannot CHECKPOINT: the current transaction has transaction local changes.
  3. The resync fails, and _dispatch_resync stops after the first failure, so it is never retried.

The easiest way to hit this is a resync triggered while files are still being written. An example is an inotify queue overflow during a burst: the resync's scan starts while realtime writes for the same burst are in flight.

Fix

Rather than guard the race, the fix removes the window in which it can happen.

  1. A file write is one executor submission. store_file_result_async / _executor_store_file_result lives on SerialDatabaseProvider, so both DuckDB and LanceDB get it, and is declared in the DatabaseProvider protocol.
    • In one operation it gets the file, updates or inserts it, fetches the existing chunks, plans the change, deletes, inserts and commits.
    • On any error it rolls back inside the same operation.
    • The coordinator's chunk diff and size validation run on the database thread as a pure-Python plan callback.
    • The executor is single-threaded and first-in-first-out, so the handover's disconnect queues behind an in-flight write and runs after its commit.
    • A write submitted after the flag is set is rejected before it opens anything. It still raises DatabaseTemporarilyUnavailableError to the realtime busy-retry.
    • The Rust guard, the runner and their ordering are unchanged. Providers without transactions (LanceDB) run the same steps without BEGIN/COMMIT.
  2. The coordinator uses it. Its per-step rollback calls and the cancellation workaround are gone, because cancelling the await never cancelled the executor operation anyway. _store_file_record and _StatResult had no other callers and are removed.
  3. DuckDB _executor_disconnect resets transaction_active. Closing the connection aborts any transaction, and a stale True made in-operation transactional checks skip their own BEGIN/COMMIT.
  4. "store" joins the sampled auto-compaction write prefixes, so the write path keeps the sampling its per-step operations had.
  5. A resync whose scan raised is retried after 5, 15 and 45 s (_RESYNC_RETRY_DELAYS_SECONDS).
    • The retry runs inside the dispatch task, so stop() cancels a pending backoff.
    • Each failure keeps today's status writes.
    • An error status from the embedding follow-up is not retried.
    • A request made during a failed run still runs.
    • The resync status block gains retry_count and retry_pending.

Why the indexing_coordinator.py diff is larger than the rest: the per-file write path had to become one submission. The lookup, update-or-insert, chunk diff, delete and insert that used to be separate awaited provider calls now run inside one provider operation, with the diff passed in as a plan callback. Most of the +/- in that file moves that sequence; the chunk-diff rules themselves are unchanged.

Tests

Two new tests, both RED on main (cc1c8f9) and GREEN with this change (Windows, serial -n 0):

  1. tests/test_duckdb_compaction.py::TestRustPipelineGuard::test_handover_after_first_write_submission_succeeds uses a real coordinator and a real DuckDB file. It performs the Rust handover after the write's first submission and asserts that the file and its chunk are committed.
    • On main it fails with DatabaseRustPipelineInProgressError.
  2. tests/test_realtime_functional.py::TestRealtimeFunctional::test_failed_resync_is_retried uses a resync callback that raises once and asserts that the resync is retried and succeeds.
    • On main it fails because there is no retry: _RESYNC_RETRY_DELAYS_SECONDS does not exist.

Existing fakes in tests/unit/test_checksum_verify_flow.py and tests/unit/test_coordinator_per_file_txn.py are updated to the new contract.

The realtime, compaction and Rust-runner suites (tests/realtime tests/test_realtime_functional.py tests/test_realtime_failures.py tests/test_duckdb_compaction.py tests/unit/test_rust_pipeline_runner.py tests/unit/test_checksum_verify_flow.py tests/unit/test_coordinator_per_file_txn.py, serial):

Passed Skipped Failed
main cc1c8f9 266 34 0
this branch 268 34 0

End-to-end measurement

The setup:

  1. A Linux container under WSL2 with watchdog 7.1.0 and fs.inotify.max_queued_events=64, so that a burst overflows the kernel queue and triggers a resync.
  2. 500 files written into an existing directory. A new directory would not reproduce it, because its creation event triggers a directory scan.
  3. Runs interleaved between the two builds.

This was measured on our fork, where the same change sits on top of the inotify-overflow detection in #509; that is what turns the overflow into a resync. On main without #509, watchdog 7.1 rebuilds its watches after an overflow but nothing requests a resync. The handover race itself does not depend on #509: any resync that overlaps realtime writes can hit it.

Build Runs that overflowed Handover failed Files indexed of 500, per run
before 4 3 of 4 27, 54, 500, 71
after 5 0 of 5 500, 500, 500, 500, 500

A sixth run of the "after" build did not overflow, so it is excluded.

Known follow-up (not in this PR)

In 2 of the 5 "after" runs the service still ended degraded, although every file was indexed. A realtime write rejected while the resync's Rust run owned the database used up its busy-retry budget, about 3 s of backoff, before the run finished, and that error is never cleared. The status is misleading, but no data is lost. I plan to address it separately: a write rejected because a known owner holds the database should wait for the hold to end instead of spending its retry budget.

This change is standalone off main. It does not depend on #509.

🤖 Generated with Claude Code, reviewed by FStrasz

…nc is retried

Root cause: a realtime file write was one DuckDB transaction spread over
~6 executor submissions with awaits between them (begin, get file, update
or insert, get chunks, delete, insert, commit). A resync's Rust handover
sets the Rust-pipeline flag, which rejects the open transaction's remaining
ops and its rollback, then release_for_rust_pipeline's bypassed disconnect
runs CHECKPOINT inside it: "Cannot CHECKPOINT: the current transaction has
transaction local changes". The resync then failed, and _dispatch_resync
broke out on the first failure and never retried.

Design: remove the class instead of guarding it.
- store_file_result_async / _executor_store_file_result (on
  SerialDatabaseProvider, so DuckDB and LanceDB both get it; in the
  DatabaseProvider protocol) does get-file, update-or-insert, fetch
  existing chunks, plan, delete, insert and commit in ONE submission,
  rolling back inside the op on any error. The coordinator's chunk diff and
  size validation run on the DB thread as a pure-Python plan callback.
  The executor is single-threaded FIFO, so the handover's disconnect queues
  behind an in-flight write and runs after its commit; a write submitted
  after the flag is rejected before it opens anything and still raises
  DatabaseTemporarilyUnavailableError to the realtime busy-retry. The Rust
  guard, the runner and its ordering are unchanged. Providers without
  transactions (LanceDB) run the same steps without BEGIN/COMMIT.
- The coordinator uses it; its rollback calls and the cancellation patch
  are gone (cancelling the await does not cancel the executor op).
  _store_file_record and _StatResult had no other callers and are removed.
- DuckDB _executor_disconnect resets transaction_active: closing aborts any
  transaction, and a stale True made in-op transactional checks skip
  their own BEGIN/COMMIT.
- "store" joins the sampled-auto-compaction write prefixes, so the write
  path keeps the sampling its per-step ops had.
- _dispatch_resync retries a resync whose scan raised after
  _RESYNC_RETRY_DELAYS_SECONDS (5, 15, 45 s), inside the dispatch task so
  stop() cancels a pending backoff. Each failure keeps today's status
  writes; an embedding-follow-up error status is not retried; a request
  made during a failed run still runs. Status resync gains retry_count and
  retry_pending.

Tests: one handover-after-first-submission test against a real coordinator
and DuckDB file, one retry test; existing fakes updated to the new
contract.

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

@VakninAriel VakninAriel left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Code Review — PR #510

Verdict: ✅ Approve

Summary

A realtime file transaction could be interrupted between executor submissions by a Rust resync handover, leaving the handover unable to checkpoint and the failed scan unretried. This PR moves each file-and-chunk write into one executor operation and adds bounded retries for resync scans that raise.

What's good

  • The write operation keeps commit or rollback on the same executor submission as the file/chunk changes, removing the inter-submission transaction window rather than adding another timing guard.
  • The added regression contracts target the actual failure boundaries: a handover immediately after the first write submission and a resync callback that fails once before succeeding.

Freshness warning: Package freshness checked 2026-11-11T15:38:58.574960+00:00: STALE: included heads/eligibility changed; see overview and freshness audit before posting. This report applies only to its pinned SHA.

Severity Count
🔴 Critical 0
🟠 High 0
🟡 Medium 0
🟢 Minor 0

Findings

No retained findings. This is not a guarantee that the code is defect-free.


Review metadata and audit

Draft review for human approval. Nothing has been posted to GitHub.

Pinned head SHA: f41df729d507153e8844687988b610b8da4997b5

Package freshness checked 2026-11-11T15:38:58.574960+00:00: STALE: included heads/eligibility changed; see overview and freshness audit before posting. This report applies only to its pinned SHA.

PR: #510

Title: fix(realtime): a file write is one executor submission; a failed resync is retried

Author: fstrasz · Branches: fix/resync-handover-upstream → main

Diff merge base: cc1c8f9

Review scope: Entire pinned PR diff against main merge base cc1c8f9 through f41df72; relevant callers, lifecycle and tests inspected. Consolidation of independent Sonnet and Astra reviews, not an additional independent model review.

Eligibility: Bug fix addressing existing behavior; no new feature.

Overall assessment (audit only)

No substantiated runtime bug found in the one-commit pinned diff. Per-file writes now finish within one executor submission; bounded resync retries preserve requests. Reviewers identified typing debt and optional retry-policy refinements, not a demonstrated blocker.

Strength evidence

  • {"strength_index": 0, "path": "chunkhound/providers/database/serial_database_provider.py", "source": "pr-510.pinned.diff", "detail": "_executor_store_file_result performs upsert, chunk planning, batch changes and transaction completion together; its exception branch rolls back before re-raising."}
  • {"strength_index": 1, "path": "tests/test_duckdb_compaction.py; tests/test_realtime_functional.py", "source": "pr-510.pinned.diff", "detail": "test_handover_after_first_write_submission_succeeds checks persisted file/chunk state; test_failed_resync_is_retried checks two callback calls and cleared resync state. These are inspected test assertions, not a claim of local execution."}

Verification

  • Reconciler verified both completed statuses, provenance validity, exact pinned metadata/worktree HEAD, full-index diff bytes, report SHA-256 hashes and distinct actual assistant-message provider/model/responseModel identities.
  • Both reviewers ran uv run --no-sync mypy chunkhound: 995 errors in 90 files; respective merge-base comparisons yielded 985 errors. Ten new diagnostics were identified (eight executor-hook attributes, Timestamp NewType, and the retry-delay mixin attribute).
  • Both targeted pytest attempts were blocked at collection by the unavailable native extension; no tests executed. Sonnet attempted a DuckDB repro which hit the same import failure.
  • Reconciler read the full pinned diff and traced concrete DuckDB/LanceDB executor-hook declarations, request coalescing, retry completion and embedding follow-up error handling.
  • Reconciler verified indexing_coordinator.py:2148-2152 and embedding_service.py:270-272 catch ordinary embedding exceptions and return error dictionaries; pipeline.py:733-735 does not flag those results as scan_raised.

Limitations

  • No local behavioral test result validates transaction handover, rollback or retry behavior because chunkhound_native.chunkhound_native cannot load; the shared environment was not changed.
  • Mypy is not clean and the new ten diagnostics are acknowledged; code review did not establish missing concrete runtime hooks.
  • CI was green at inventory snapshot; no fresh remote CI execution by reconciler.
  • CI is a captured snapshot, not a fresh run or a guarantee of current branch status.
  • Model identities are verified declarations supplied by the reconciler; the renderer does not inspect raw reports or provenance events.

Disposition of discarded / merged findings

  • Sonnet backoff-delay candidate describes the intended bounded retry policy after an already-failed reconciliation. New requests remain recorded and are processed after the current backoff; no latency guarantee or lost request was demonstrated. Interruptible backoff is a policy enhancement, not a substantiated bug.
  • Sonnet embedding-exception retry candidate is not supported for ordinary provider failures: both embedding layers catch Exception and return error status, which this dispatcher explicitly does not retry. Bounded retries of persistent scan exceptions are expected retry-policy cost; no classification contract promises transient-only retries.
  • Sonnet retained retry_count candidate is diagnostic history, with retry_pending separately false on cancellation/exhaustion. No consumer was shown to misinterpret count as active retrying; optional naming/reset clarification, not runtime bug.
  • Astra Minor hook-typing finding is a reproducible static-verification regression, not absent methods at runtime: concrete providers implement the required hooks and transactions are capability-guarded. Preserved explicitly in verification/limitations rather than promoted to a ready-to-post functional bug against an already-failing baseline.
  • Sonnet cancellation observation is consistent with the documented single-submission design: cancelling the await cannot cancel work already executing in the worker. No open transaction is left across submissions.
  • LanceDB batch-deletion limitation predates this change; the old async deletion also skipped the absent hook. No stacked changes in this one-commit PR.
  • Final cross-PR audit explicitly ruled out inherited #504/#505 read-only filtering: this pinned head's events.py has no content-event gate, startup has no watchdog event_filter, and the full merge-base diff does not introduce them. The actual #510 handler/consumer Linux watchdog probe delivered value = 2 during the simulated in-flight pass, exit 0 (/tmp/chunkhound-final-audit-qfk_juar/probe-510.py). Do not infer this defect from PR numbering or ancestry assumptions.

Independent reviewer provenance

  • sonnet — provider: amat-tfy; requested model: standard-chat-dev/claude-sonnet-5.5; verified response model: aws-aidev-models/us.anthropic.claude-sonnet-5-5. Identity evidence · Raw report
  • astra — provider: amat-tfy; requested model: frontier-chat-dev/gpt-6-astra; verified response model: gpt-6-astra. Identity evidence · Raw report

CI snapshot

Captured: 2026-11-11T14:18:23.581921+00:00. Eligibility green: True. Counts: {"SKIPPED": 2, "SUCCESS": 23}

Reviewed by Ariel Vaknin via pi.dev

@HananKavitzAmat

Copy link
Copy Markdown
Collaborator

looks good

@HananKavitzAmat
HananKavitzAmat added this pull request to the merge queue Nov 16, 2026
Merged via the queue into chunkhound:main with commit 84ab53d Nov 16, 2026
25 checks passed
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 16, 2026
Brings in chunkhound#504's squash (11d1753) and chunkhound#510. This branch already carries chunkhound#504's final head (4e10023), and the squash is byte-identical to that head merged onto 84ab53d, so the conflicts in realtime/events.py and realtime/startup.py resolve to this branch merged with 84ab53d, which merges cleanly. No other conflicts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 17, 2026
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 17, 2026
Brings in chunkhound#510, chunkhound#504 and chunkhound#534. No conflicts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 17, 2026
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 17, 2026
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 17, 2026
Brings in chunkhound#521, chunkhound#510, chunkhound#504 and chunkhound#534 on top of the earlier merge of main. realtime/startup.py conflicted only in its imports: chunkhound#504 adds watchdog_event_filter to the .events import and this PR adds the .inotify_overflow import; both are kept. chunkhound#504's event_filter reaches this PR's InotifyObserver through the same schedule() call.

One semantic conflict, no textual one: chunkhound#504's test_watches_are_scheduled_without_read_only_events faked _create_watchdog_observer with no arguments and unpacked _bootstrap_fs_monitor as a tuple. This PR changed both (the factory takes on_overflow and returns the observer with its overflow detection; the bootstrap returns WatchdogBootstrap), so the test now fakes and reads them that way, as this PR's own inotify tests do. Its assertions are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

3 participants