Skip to content

fix(kb): the embedding-switch heartbeat and finish write only while the record is still the run's own (#20023) - #21016

Closed
mrveiss wants to merge 3 commits into
mainfrom
issue-20023-embedding-heartbeat-owner
Closed

mrveiss wants to merge 3 commits into
mainfrom
issue-20023-embedding-heartbeat-owner

Conversation

@mrveiss

@mrveiss mrveiss commented Nov 7, 2026 •

Copy link
Copy Markdown
Owner

Refs #20023 (the claim-held, record-absent case still reads idle; tracked in #21017)

Thinking Path

The heartbeat and _finish wrote the state hash with a plain HSET. When the hash had vanished while the run still held its claim, that write recreated it with no owner, and every reader then saw idle. The fix makes every write after the start owner-conditional in one atomic Lua step, so a vanished record stays absent instead of coming back ownerless. No TTL is added: the hash is the last-run record and a TTL would make it vanish by design. The wording is corrected instead.

What Changed

  • autobot-backend/knowledge/embedding_switch.py: new _SET_IF_OWNER_LUA and _set_state_if_owner. _heartbeat writes through it and raises "lost its state record" when it returns 0, so the run fails and _finish releases the claim. _finish writes through it too (its separate owner pre-check was a non-atomic read). Force-close passes an empty owner: it matches any record that still exists (including an ownerless one an older build left behind) and never creates one. start_switch keeps its unconditional write, after it holds the claim and has deleted the old record. Module docstring and the settle-script comment no longer say "expired" for the record; the lock's lapse is called a lapse.
  • autobot-backend/knowledge/embedding_switch_test.py: the fake Redis understands the new script.
  • autobot-backend/knowledge/embedding_switch_owner_20023_test.py: new tests (the original test file is near the 600-line ceiling).

Readers with a vanished hash (all covered)

Reader Result now
switch_status exactly {"failed_ids": [], "state": "idle"}, nothing else (test asserts it)
request_switch_cancel none
note_write notes nothing (test asserts the pending set is empty)
_finish writes nothing, warns, releases the claim (test)
settle script / cancel script unchanged, -1 / 0, write nothing (existing tests)
heartbeat raises, writes nothing; the key is asserted absent

Not determined: answers

  1. Has it happened on a host? Not determined and not claimed. No host was observed in this change; read-only host observation (live maxmemory-policy, evictions on the knowledge database) is out of scope for a code PR. With the fix the ownerless state can no longer be produced, whatever the answer.
  2. Can flushdb reach the knowledge database through the cache-clear path? No, from the code: _CLEARABLE_DATABASE_NAMES = ("cache", "analytics") in api/cache_redis_databases.py, and clearable_database rejects knowledge with a 400 pointing to the deletion-proposal queue. Other flushdb callers (api/knowledge_mcp.py, setup script) were listed but not traced: out of scope here, no change depends on them.
  3. Is a write missed by note_write after cutover lost? Reading _converge: after the settle sleep it replays pending ids, then compares store._collection.count() with fact_store.count_facts(); a mismatch after the replay rounds yields completed_with_warnings with the reason, not silence. A write that lands in neither the pending set nor the count is not possible while the record is owned; with a vanished record the run now fails at the next heartbeat instead of continuing blind.
  4. The claim-renewal vs HSET race: still two steps (extend_claim, then the write), but the write now checks owner atomically. If a newer run took over in between, the old run's write returns 0, writes nothing, and the old run fails; the newer record is untouched (test: foreign owner leaves the record byte-identical).
  5. Frontend rendering: no reader found in autobot-frontend/src or autobot-slm-frontend/src beyond the generated API types; other clients not checked. Out of scope: the status payload contract is unchanged.

Not done, proposed for approval (#17038)

  • Existing ownerless records already in a deployment are not touched by this PR. The next start_switch replaces one, and force-close still reaches one. If an operator wants one cleared sooner, that is a deletion proposal for the approval queue.
  • A hash that vanished entirely while a run holds the claim still reads idle with a start refused as "already running" until the run fails at its next heartbeat. Reporting a held claim with no record as its own state would change the status contract; proposed as a follow-up decision, not done here.

Verification

~/.venv-python-suite/bin/python -m pytest knowledge/embedding_switch_test.py knowledge/embedding_switch_owner_20023_test.py api/embeddings_switch_19379_test.py : all pass (54 passed with repo_tests/embedding_override_single_writer_19379_test.py)
Tests include the script on a real Lua engine (fakeredis): vanished record writes nothing and the key stays absent; foreign owner writes nothing; ownerless legacy record reachable only by force-close.

Model Used

Claude Sonnet 5.5

Single-issue rationale

The change is confined to one module whose write path it replaces; no other open issue touches it.

@mrveiss mrveiss added bug Something isn't working priority: medium backend area: kb-retrieval Wave 5 · cluster J — Knowledge-base retrieval quality phase:M4.4 One config source labels Nov 7, 2026
@coderabbitai

coderabbitai Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 50 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 22097e0 and f4d017a.

Files selected for processing: 4

  • autobot-backend/knowledge/embedding_switch.py
  • autobot-backend/knowledge/embedding_switch_lock.py
  • autobot-backend/knowledge/embedding_switch_owner_20023_test.py
  • autobot-backend/knowledge/embedding_switch_test.py
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Notice: 29 open PRs — past the runaway threshold (25)

This is not a request to defer this PR. There is no cap on open PRs (#19397) -- nothing blocks opening or pushing a PR.

This notice only means the count is high enough to be worth a glance for a runaway — something opening PRs in a loop, or a merge pipeline that has stalled so nothing is draining.

Currently open:

If the queue is draining normally, ignore this. Otherwise:

  1. Check whether CI is dispatching at all — see the ci-dispatch-watchdog status on these PRs
  2. Approved PRs land through the merge train the coordinator sequences (merge commits, never squash) -- check the open chore(merge-train) PR is moving, not each PR on its own
  3. Look for a loop opening near-identical PRs

Warn-only runaway detector — .github/workflows/pr-queue-gate.yml. It never blocks a merge.

@mrveiss

mrveiss commented Nov 7, 2026

Copy link
Copy Markdown
Owner Author

Code review (code-reviewer pass) at e02c511 — APPROVE

Check Result
Correctness Every post-start state write goes through _SET_IF_OWNER_LUA (HGET owner then HSET in one script), so a vanished hash is never recreated ownerless and a newer run's record is never overwritten. Single key, so cluster-safe.
Force-close Now carries the stale record's owner; the empty-owner path only matches an existing (legacy ownerless) record and never creates one. force_release (release whoever holds it) is removed, with no remaining callers in the tree, so a force-close can no longer drop a newer run's claim.
Heartbeat Failing the write raises, run_switch records the failure via _finish (which logs with logger.exception).
Tests fail without the change Vanished-record and foreign-owner heartbeats, mid-build vanish, force-close after a new start, plus two tests against a real Lua engine (fakeredis[lua] is in requirements-ci-test.txt). The in-memory fake mirrors the script, and the real-engine tests cover the script itself.
Hardcoding / sleeps / loggers / size None; embedding_switch.py 468 lines, test file 553.

Nits, not blocking:

  • The ownership-lost message in _finish dropped from warning to info on the reasoning that the loss was reported where it was detected. True for the heartbeat and settle paths; a record that vanishes between cutover and the final _finish(..., "completed") is reported only at info. Keep warning for the state == completed* path, or say so in the comment.
  • A force-close of a stale record with an empty owner can still match a run that started since (the legacy case). Narrow, documented, acceptable.

@mrveiss

mrveiss commented Nov 7, 2026

Copy link
Copy Markdown
Owner Author

Landed on main via merge train #21031 (merge commit 361d419); every commit of head e02c511 is in main.

@mrveiss mrveiss closed this Nov 7, 2026
@mrveiss
mrveiss deleted the issue-20023-embedding-heartbeat-owner branch November 7, 2026 14:19
timothybrush pushed a commit to timothybrush/AutoBot-AI that referenced this pull request Nov 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: kb-retrieval Wave 5 · cluster J — Knowledge-base retrieval quality backend bug Something isn't working phase:M4.4 One config source priority: medium

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant