Skip to content

fix(kb): the embedding-switch heartbeat can leave an ownerless state hash with no TTL that reads as idle #20023

Closed

Description

@mrveiss

Problem

After #19967 the settle script refuses a record this run does not own, but the heartbeat just before it can still write one. Read at main 0881619009, in autobot-backend/knowledge/embedding_switch.py.

_cut_over calls _heartbeat(run) (:372) and then the settle script (:373). _heartbeat checks the work claim, not the hash, then calls _set_state (:220), which is a plain HSET (:138). If the hash has vanished while the run still holds its claim, that HSET recreates it with a heartbeat field and no owner. Earlier heartbeats (:264, :277) can add total, done and failed in the same way.

How long the hash lasts

No TTL exists on this key. This module has no EXPIRE or ex= for STATE_KEY; the only expire hits are in comments. So the ownerless hash lasts until one of these:

  • the next start_switch that gets the claim, which deletes it (:162);
  • removal from outside this module.

_finish will not clear it: with no matching owner it logs a warning, releases the claim and returns (:244-248). The wording "until its TTL" in #19849, and "expired" in the comment at :75 and in the tests, describes a TTL the code does not set.

A way for the key to vanish exists on paper: the repo's Redis configs set maxmemory-policy allkeys-lru (for example autobot-infrastructure/autobot-database/templates/redis.conf:11), and that policy evicts keys with no TTL. clear_single_redis_database in autobot-backend/api/cache_redis_databases.py:113 also runs flushdb on a named database.

What reads it

Reader Line With an ownerless hash
switch_status (status API, and the return of start_switch) :122, :127 state defaults to idle, with the extra fields included. It does not read stale, because idle is not in _ACTIVE
request_switch_cancel :184 and its switch_status call Returns none, so a running build cannot be cancelled or force-closed
note_write :208 state is absent, so writes are no longer noted for replay
_finish :244 Refuses, so the run's outcome and reason are never recorded
_SETTLE_UNLESS_CANCELLED_LUA :373 Returns -1, so no cutover. This is the #19967 fix, and test_a_state_record_lost_during_convergence_never_cuts_over covers it
_CANCEL_IF_BUILDING_LUA :184 Returns 0 and writes nothing

What follows from the code: no cutover happens from an ownerless record, and it does not block the next start_switch. It is not clearly harmless, though. An operator sees idle while the build still holds the claim, a new start is refused as "already running" meanwhile, and the failure reason is lost, leaving only a log line.

The same applies after cutover. The heartbeat after the settle sleep and the later ones in _converge can recreate the hash, and then _finish refuses, so a switch that did happen reads as idle with no completed record.

Not determined

  • Whether this has ever happened on a host. No host was observed: not the live maxmemory-policy, not whether the knowledge database is under memory pressure, not whether a key was evicted.
  • Whether flushdb can reach the knowledge database through the cache-clear path; the db_name callers were not traced.
  • Whether a write missed by note_write after cutover is lost or caught by the _converge count check; _converge was not read for this.
  • The race between the claim renewal and the HSET in _heartbeat (they are not atomic), and what that write does to a newer run's record.
  • How the frontend renders this status: a grep of autobot-frontend/src for the switch route found no reader, and other clients were not checked.

Discovered During

Landing the merge train, PR #19988, after #19967 under #19849.

Acceptance Criteria

  • An ownerless record cannot persist (for example the heartbeat writes only when owner still matches), or it is shown harmless, with each reader above covered.
  • A test with a vanished hash asserts the chosen outcome for what is left in the key, not only that no cutover happened.
  • The stale "TTL" and "expired" wording around STATE_KEY matches what the code does, or a TTL is added.
  • Each "Not determined" item is answered, or stated as out of scope with a reason.

Activity

  1. mrveiss commented on Nov 7, 2026

    @mrveiss
    OwnerAuthor

    Landed via merge train #21031 (PR #21016). Verified on main: AC1 ticked - knowledge/embedding_switch.py _heartbeat writes through _set_state_if_owner (_SET_IF_OWNER_LUA), raising 'lost its state record' and recreating nothing. AC2 ticked - embedding_switch_owner_20023_test.py::test_a_heartbeat_on_a_vanished_record_writes_nothing_and_fails_the_run asserts the key stays absent, status reads idle, cancel returns none, note_write notes nothing. AC3 ticked - module docstring now states the state hash has NO TTL and writes are owner-conditional. AC4 left unchecked: no answer to the 'Not determined' items (host eviction policy, flushdb reach, post-cutover note_write, claim/HSET race, frontend reader) is recorded; the live-eviction items also need host evidence.

  2. mrveiss commented on Nov 7, 2026

    @mrveiss
    OwnerAuthor

    AC4 answered from code at origin/main 361d419987 (after #21016). AC4 stays unchecked: item 1 needs host evidence and nothing honest scopes it out. Paths are repo-relative.

    # Item Verdict
    1 Has an ownerless record / eviction ever happened on a host needs host evidence (checks below)
    2 Can flushdb reach the knowledge database settled from code for every caller; whether one ran needs host evidence
    3 A write missed by note_write after cutover settled from code, with one residual window
    4 Claim renewal vs HSET race, and a newer run's record settled from code
    5 Frontend rendering of the status settled from code (repo clients); external API clients are out of scope

    1. Eviction: what the code configures

    knowledge is DB 1 (autobot_shared/redis_management/types.py:130); the switch hash lives there (autobot-backend/knowledge/embedding_switch.py:133-135, database="knowledge"). maxmemory-policy is a server-wide setting in Redis, not per database, so every DB below gets the same policy. Every place the repo writes it says allkeys-lru, which evicts keys with no TTL:

    • autobot-slm-backend/ansible/roles/redis/templates/redis-stack.conf.j2:102-103 (maxmemory {{ redis_memory_limit }}, role var 6gb in roles/redis/vars/main.yml) -- the role the installer uses
    • autobot-slm-backend/ansible/templates/redis/redis-stack.conf.j2:29-30 (group var 6gb, inventory/group_vars/database.yml:79-80)
    • autobot-slm-backend/ansible/playbooks/deploy-native-services.yml:108-109 (6gb)
    • autobot-infrastructure/autobot-database/templates/redis.conf:10-11 (2gb), autobot-infrastructure/shared/config/redis-optimized.conf:12-13 (8gb), docker-compose.yml:57 (512mb)
    • No script or playbook sets a different policy at runtime; the only CONFIG SET is notify-keyspace-events (playbooks/deploy-database.yml:382).

    The code therefore allows eviction of this key but does not show it happened. The size cap differs by template (512mb to 8gb), so which one the host runs is a runtime fact. Needs host evidence -- read-only, run through the builtin tooling, against the Redis instance:

    • CONFIG GET maxmemory-policy and CONFIG GET maxmemory
    • INFO memory (used_memory, maxmemory, maxmemory_policy)
    • INFO stats (evicted_keys, counted since the last restart or CONFIG RESETSTAT)
    • INFO keyspace (DB 1 key count)
    • -n 1 EXISTS autobot:kb:embedding_switch, and if present -n 1 HGET autobot:kb:embedding_switch owner (an existing record with no owner is a leftover ownerless hash) and -n 1 TTL autobot:kb:embedding_switch (expect -1)

    2. flushdb / flushall callers (non-test, whole tree)

    Caller DB reached Reaches knowledge (1)?
    autobot-backend/api/cache_redis_databases.py:113 via clear_single_redis_database only _CLEARABLE_DATABASE_NAMES = ("cache","analytics") (:29), i.e. DB 5 and 11; any other name, including knowledge, is refused with 400 (:61-75) No
    autobot-backend/api/knowledge_mcp.py:902 (_vector_op_flush, needs confirm) get_redis_client(database="vectors") (:70-75); vectors is an alias of logs (types.py:152, :210), so DB 8 No (despite the name, it is not the knowledge DB)
    autobot-infrastructure/shared/scripts/setup/knowledge/fresh_kb_setup.py:70 (_clean_redis_databases, run from fresh_setup :162, no confirmation prompt) main, knowledge, prompts, agents, metrics, logs, sessions, workflows, vectors, models Yes -- a manually run setup script, not an app path
    autobot-infrastructure/shared/scripts/cache/clear-all-caches.sh:200-202, clear-backend-cache.sh:74-76 -n 2, -n 4, -n 5 (prompts, metrics, cache by the table; the script comments label them differently) No
    MCP flushdb / flushall declared ahead of time in autobot_shared/auth/mcp_tool_permissions.py:117-118,275-276, admin-only; no live tool registered (autobot-backend/services/mcp_dispatch.py:73) Not reachable today
    Ansible roles / installer no FLUSH* anywhere No

    So the only code path that empties DB 1 is fresh_kb_setup.py. Whether anyone ran it, or an operator ran FLUSHDB by hand, is a host question. Needs host evidence, read-only:

    • INFO commandstats -- cmdstat_flushdb / cmdstat_flushall calls (counted since the last restart or stats reset; 0 or absent means none since then)
    • the audit log for cache.clear entries (api/cache_redis_databases.py clear_and_audit) -- these can only name DB 5 / 11
    • shell history / job log for fresh_kb_setup on the backend host, if the tooling exposes it

    3. Writes after cutover

    note_write (embedding_switch.py:251-258) notes a fact id whenever state is building or settling (_ACTIVE, :62); settling starts at the cutover step (_SETTLE_UNLESS_CANCELLED_LUA, :79-87) and lasts until _finish. After the settle sleep _cut_over runs _converge again (:429-465), which replays the pending set and requires count == count_facts() and an empty pending set (:404-418). A failure ends as completed_with_warnings with the reason, never silently. The durable row is the SQL fact (knowledge/fact_store.py:68-81); the vectors are a rebuildable projection. Residual: a write landing between the last _converge check and _finish is added to the pending set but not replayed by this run. Not traced here: whether the normal write path also embeds into the rebound collection, which would cover it.

    4. Claim renewal vs state write

    _heartbeat (:261-269) renews the claim, then writes through _SET_IF_OWNER_LUA (:96-109). The two steps are separate, but the write is one atomic script that does HGET owner and HSET together. If the claim lapsed and a newer run started, start_switch deletes the key and writes its own owner (:200-205); the old run's script then sees a missing or different owner and returns 0, so it writes nothing, recreates nothing, and _heartbeat raises. _finish (:291-319) is guarded the same way and releases only its own claim. Covered by embedding_switch_owner_20023_test.py (foreign-owner, vanished, and a real Lua engine case).

    5. Frontend reader

    The three routes are /api/embeddings/switch (POST, DELETE) and /api/embeddings/switch/status (autobot-backend/api/embeddings.py:262-320). In the frontends, SLM frontend and SLM backend the only mentions are the generated types autobot-frontend/src/types/generated/api.ts:33885-33907; no component or client calls them. Out of scope: other API consumers outside this repo -- they are not enumerable from code, and the response shape did not change in #21016.

    What closes AC4

    Item 1's host checks (first list) and, to confirm no FLUSHDB ran, the commandstats check in item 2. Once both results are posted here, tick AC4.

  3. mrveiss commented on Nov 7, 2026

    @mrveiss
    OwnerAuthor

    Read-only host check for AC4 on the live install, 2026-11-07. The install is at 22097e0 (T89, before T91). Redis has been up 377357 s (~4.4 days).

    Check Result
    CONFIG GET maxmemory-policy allkeys-lru
    CONFIG GET maxmemory 6442450944 (6 GiB)
    INFO memory used_memory 73632984 (~70 MiB); maxmemory 6442450944; policy allkeys-lru
    INFO stats evicted_keys 0
    INFO keyspace db1 keys=2921, expires=106
    -n 1 EXISTS autobot:kb:embedding_switch 0 (no switch record present now, so owner/TTL not applicable)
    INFO commandstats flushdb / flushall no entries among 78 recorded command types, so 0 calls since the restart ~4.4 days ago

    Reading: eviction is possible in principle (allkeys-lru, and the record has no TTL), but it hasn't happened. Usage is ~1% of maxmemory, 0 keys were evicted, and no FLUSHDB or FLUSHALL ran in this uptime window. The record's absence now matches no switch being in progress.

  4. mrveiss commented on Nov 7, 2026

    @mrveiss
    OwnerAuthor

    AC4 is answered and ticked. Every "Not determined" item now has an answer:

    • Items 2-5 are settled from code on main at 361d419 (issuecomment-6708146234).
    • Item 1 (has eviction, or an ownerless record, ever happened on a host?) is answered by the read-only host check posted on this issue:
      • The eviction policy is allkeys-lru, with maxmemory at 6 GiB. Used memory is about 70 MiB (about 1%), and evicted_keys is 0.
      • autobot:kb:embedding_switch does not exist at present.
      • FLUSHDB and FLUSHALL show 0 calls over the current uptime of about 4.4 days.
      • So eviction is possible under the policy but has not happened, and there is no ownerless record now.
      • Limit: these counters reset when Redis restarts, so they say nothing about the time before the current uptime.

    AC1 through AC4 are now all ticked against code on main (PR #21016, train T91) or against host evidence. The one remaining edge case, a claim still held while its record is absent, is tracked separately as #21017. Closing this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions