Skip to content

fix(startup): sweep Redis for orphan slots whose SQL row is terminal or missing (#749) - #814

Merged
vybe merged 1 commit into
devfrom
feature/749-redis-slot-recovery
May 12, 2026
Merged

vybe merged 1 commit into
devfrom
feature/749-redis-slot-recovery

Conversation

@dolho

@dolho dolho commented May 12, 2026

Copy link
Copy Markdown
Contributor

Summary

Closes #749. Mirror of #748 (PR #812) on the inverse direction:

Direction Symptom Fix
SQL ahead of Redis row FAILED before slot was ZADDed #748 grace-window skip
Redis ahead of SQL slot ZADDed but ZREM never ran this PR

The second bug is the textbook "backend killed mid-execute" leak: uvicorn auto-reload (dev) or signal (prod) kills the in-flight handler between `capacity.acquire()` (ZADD on `agent:slots:{name}`) and the `finally`-block `capacity.release()` (ZREM). The slot persists until 1200s TTL or the next acquire on the agent. Canary S-01 (#411) detected this shape three cycles in a row during the same incident that filed #748 + #749.

Changes

  • New `_reconcile_orphaned_slots()` in `cleanup_service.py`.
  • Wired into `recover_orphaned_executions()` after the SQL→Redis pass. Result dict adds `redis_slots_reclaimed`.
  • The sweep runs even when SQL has zero running rows (the bug's textbook shape — SQL is clean, Redis isn't).

Test plan

  • `tests/unit/test_redis_slot_recovery.py` — 10 cases:
    • Orphan with missing SQL row → ZREM.
    • Orphan with terminal SQL row → ZREM.
    • Running SQL row → left alone.
    • Within grace window → skipped even if orphan (avoids racing live ZADDs).
    • Drain sentinel → skipped.
    • Metadata key deleted with member.
    • Multiple agents aggregated.
    • Redis unreachable → returns {} without raising.
    • Empty SQL still sweeps Redis (the textbook shape).
    • Source-level constant pin.
  • `test_orphaned_execution_recovery.py::test_no_running_executions` updated from full-dict equality to key-by-key checks (forward-compatible with bug: startup execution recovery races with concurrent in-flight /internal/execute_task calls #748's `skipped_grace` too).
  • Acceptance criterion fix: add missing logging_config.py to backend Dockerfile #4 from the issue: canary S-01 stays clean for ≥1 cycle after a forced restart on a stack with active scheduled load. Needs staging.

Relates to #749. Companion to #748 (PR #812).

🤖 Generated with Claude Code

…or missing (#749)

Companion to #748. The startup recovery path is asymmetric — it walks
SQL `running` rows and patches SQL when Redis lost the matching slot,
but never SCANs Redis for the inverse leak: a slot ZADDed by
`capacity.acquire()` whose finally-block `capacity.release()` ZREM
never ran (typical cause: backend killed mid-execute by uvicorn reload
or signal). The leaked slot persists until the 1200s TTL elapses or the
next acquire on this agent triggers `_cleanup_stale_slots_for_agent`.
Canary S-01 (Issue #411) detects this exact shape; rows #26/#27/#28 in
`canary_violations` reproduced it three cycles in a row during the
incident that filed #748 + #749.

Implementation:

  - New `_reconcile_orphaned_slots()` SCANs `agent:slots:*`, mirroring
    the canary's `_collect_redis_slot_state` and the slot service's own
    `cleanup_stale_slots`.
  - For each member: skip drain sentinels (`drain-*`), skip members
    within `SLOT_RECOVERY_GRACE_SECONDS` (15s, symmetric with the SQL
    grace window in #748), then look up SQL row.
  - If SQL row is terminal (`success`/`failed`/`cancelled`/`skipped`)
    or missing entirely → ZREM the member + DELETE the metadata key.
  - Wired into `recover_orphaned_executions()` so it runs on startup
    after the SQL→Redis pass. Returns a new `redis_slots_reclaimed`
    counter in the result dict.
  - The function is called even when SQL has zero running rows — the
    textbook bug shape is "SQL terminal, Redis still holds the slot,"
    which the SQL→Redis pass cannot see.

Result-dict regression: the existing
`tests/unit/test_orphaned_execution_recovery.py:test_no_running_executions`
asserted full-dict equality. Relaxed to key-by-key checks so future
diagnostic keys can be added without breaking the existing test.

Tests: tests/unit/test_redis_slot_recovery.py (10 cases, all green).
Covers: orphan-with-missing-SQL → ZREM, orphan-with-terminal-SQL →
ZREM, running-SQL → leave alone, within-grace → skipped even if
orphan, drain sentinel → skipped, metadata key deleted with member,
multiple agents aggregated, Redis-down doesn't crash recovery,
empty-SQL still sweeps Redis (the textbook bug shape), source-level
pin of constants.

Relates to #749. Companion to #748 (PR #812).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Clean fix for the inverse Redis-slot leak. Implementation mirrors existing SCAN/grace-window patterns, all 10 test cases cover the edge cases including the textbook empty-SQL shape. Approved.

@vybe
vybe merged commit d9e81a5 into dev May 12, 2026
9 checks passed
dolho added a commit that referenced this pull request Oct 6, 2026
…d up (Abilityai/trinity-enterprise#810, #812, #814)

Found by driving the section end to end on a local instance (seeded
people, canon, three agents) with layout-shift capture on every step.

- Replacing the primary with someone already on the agent promotes
  their existing row instead of adding a second one. Before, the person
  was listed twice (primary and approver) and, under ent#814, held two
  seats to choose between. The old primary still steps down first.
- The add form clears the seat after a successful add. Before, the seat
  typed for one person was silently given to the next one added.
- First load keeps the loaded section's shape (seat bar, a two-person
  list card, the add form) and no longer flashes "No seat yet" for an
  agent that has one. On a slow network the operator list below moved
  133px on arrival; it now moves 5-24px for agents with up to two
  people.
- A failed replacement says where the agent stands, from the re-read
  roster ("Leo Park is still the primary."), not only the error.
- On a phone each row stacks its details above its controls; the kind
  select no longer covered the person's name.
- The Workspace role card renders the no_seat finding. ent#812 had
  mapped it as a role error, which the backend never sends, so the
  sentence could not appear.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
vybe added a commit that referenced this pull request Oct 11, 2026
…and the three-state consent (trinity-enterprise#811/#814/#817)

api-endpoints.md gains GET /api/agents/{name}/canon/roles; backend.md gains
canon_roles_service and the resolve_seat / resolve_served_seat contract on the
assignment seam; database.md marks allow_proactive as NULL/0/1 with both
migration names.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
vybe added a commit that referenced this pull request Oct 11, 2026
…tyai/trinity-enterprise#810–#814, #817) (#3271)

* feat(access): manage who an agent serves from its Access tab (Abilityai/trinity-enterprise#810)

Assignments (primary, approver, collaborator, viewer) had no UI: setting
an agent's primary human or its approvers took an API call. Agent Detail
› Access now has a "People this agent serves" section above the
operator list, over the existing ent#500 endpoints.

An instance admin sees the primary apart from the stakeholders, with
the seat it serves, each row's proactive-brief consent and role-check
state; adds a person picked by name, changes a kind in one action on the
row, removes a row, and replaces the primary as one flow that demotes
the old primary first and puts it back if the new one cannot be written.
Every refused write shows the backend's own reason. Non-admins see the
same section read-only. The section is absent without the assignments
module.

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

* feat(access): seats on the assignments section — an agent holding one, optional and clearable roles (Abilityai/trinity-enterprise#811)

The public half of ent#811, on top of the ent#810 section.

- services/assignment_provider: the optional provider method seat_for
  and resolve_seat(agent), which answers which seat an agent holds
  itself or serves through its primary with no triggering user. Always
  a dict, never a raise: no provider, a provider without seat_for, no
  answer, a raise or a malformed shape all read as "no seat" with a
  named reason, the failure direction the readiness gate needs.
- The section's header has both forms: "Holds the seat: <id>" (the
  agent itself, which wins) or "Serves the seat of its primary". An
  admin can record, change or clear the seat the agent holds; a refusal
  names the agent that already holds it.
- The seat on a row is optional when adding or replacing the primary,
  and a row's seat can be added, changed or cleared (explicit null).
- With no primary yet, the add form starts on Primary.

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

* feat(objectives): owned objectives come from the seat on record, not x-role (Abilityai/trinity-enterprise#812)

Under the 2026-10-06 ruling (R50 + R50a) the seat is recorded in
Trinity, held by a person or by an agent; x-role.role in template.yaml
stops being truth. The objective join was the one surface that relied
on it.

- "Owned" resolves through assignment_provider.resolve_seat: the seat
  the agent holds (that seat only), else the seats its assigned people
  hold, primary first; a shared companion owns the union.
- The canon declaration alone enables the join; x-role is neither
  required nor read.
- An agent with no seat owns nothing and a no_seat finding says why and
  what to do (it replaces role_id_invalid); supporting objectives still
  show. The role card renders the sentence.
- supporting_agents is read as before, documented as frozen.
- The response's role carries case and seats.

Existing suites that declared their seat through x-role now record it
through a registered provider, which is what an assigned primary does.

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

* feat(readiness): a companion is an agent whose primary holds a seat, not one whose template has x-role (Abilityai/trinity-enterprise#813)

The readiness gate (ent#689) held an unstamped agent's proactive brief
when its template declared x-role. Under the 2026-10-06 ruling the seat
is recorded in Trinity, so "is this a companion" is now answered by
assignment_provider.resolve_seat: a primary that holds a seat (serves).

- An agent holding a seat itself, no primary with a seat, no seat
  lookup or a lookup error all read as "not a companion", so the brief
  fires as before (fails open, #1638).
- The owner's stamp still decides first and the seat is not looked up
  for a stamped agent; the rollout seed and held-schedule behaviour of
  ent#689 are unchanged.
- The template is no longer read: one container read less per brief,
  and an agent can no longer take itself out of scope by editing its own
  files.
- Each decision is logged with its reason.

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

* feat(access): canon seats, three-state consent, and drift on read (Abilityai/trinity-enterprise#817)

The public half of ent#817, completing ent#810's remaining criteria.

- Canon seats (OSS-core, operator ruling 2026-10-06): GET
  /api/agents/{name}/canon/roles lists <canon>/roles/*.yaml with id,
  title and updated through the agent door the objective join uses, on
  the same per-agent read budget, self-gated for agent keys. Every empty
  answer is named (stopped, no canon, no roles/, unreadable, timeout).
- Proactive consent in three states: agent_sharing.allow_proactive NULL
  = not asked, 0 = declined, 1 = consented. New shares are written NULL;
  a data migration on both tracks (SQLite + Alembic 0090) moves the
  legacy DEFAULT-0 rows to NULL. Who may be messaged is unchanged: only
  1 allows it. Shares and the Access list carry proactive_consent.
- The assignments section: seat fields suggest the canon's seats (a
  typed id still works), the header and rows show the role's title and
  the file's updated stamp, drift reads current / changed / missing /
  unknown with its reason, and consent reads in three states.

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

* feat(access): a shared companion serves the seat of the person each run is for (Abilityai/trinity-enterprise#814)

- assignment_provider.resolve_served_seat(agent, email): the person's
  own seat, the agent's own when it holds one (holds wins), the
  primary's as the fallback; never raises. A provider that predates
  the OPTIONAL served_seat_for falls back to seat_for.
- Seat decisions (ent#638) are stamped with the served seat; the
  agent's decided_by_role is only the fallback when nobody's seat is on
  record (its prompt used to name the primary's seat on every run).
- The prompt keeps its Primary human line and adds "Seat this run
  serves" only when the run serves a different seat: a chat user, or
  the Workspace a scheduled brief is delivered to (read off the
  execution row, never rendered). Suppressed audiences render nothing.
- The add form no longer pre-fills the primary's seat for every new
  person.

The one-primary rule, the primary display name and the primary address
are unchanged.

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

* fix(access): what a live walkthrough of the assignments section turned up (Abilityai/trinity-enterprise#810, #812, #814)

Found by driving the section end to end on a local instance (seeded
people, canon, three agents) with layout-shift capture on every step.

- Replacing the primary with someone already on the agent promotes
  their existing row instead of adding a second one. Before, the person
  was listed twice (primary and approver) and, under ent#814, held two
  seats to choose between. The old primary still steps down first.
- The add form clears the seat after a successful add. Before, the seat
  typed for one person was silently given to the next one added.
- First load keeps the loaded section's shape (seat bar, a two-person
  list card, the add form) and no longer flashes "No seat yet" for an
  agent that has one. On a slow network the operator list below moved
  133px on arrival; it now moves 5-24px for agents with up to two
  people.
- A failed replacement says where the agent stands, from the re-read
  roster ("Leo Park is still the primary."), not only the error.
- On a phone each row stacks its details above its controls; the kind
  select no longer covered the person's name.
- The Workspace role card renders the no_seat finding. ent#812 had
  mapped it as a role error, which the backend never sends, so the
  sentence could not appear.

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

* fix(access): a failed replacement's message reads as two sentences (Abilityai/trinity-enterprise#810)

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

* fix(workspace): the role card reads the seat on record and the viewer's assignment, not x-role (live-check follow-up)

The 2026-10-06 live check of this PR and ent#818 left three open items:

- The Workspace role card took its role from x-role.role and its "Seat ·"
  line from x-role.seat (an email), so a shared companion's card said
  "sales-lead" while the Access tab said Head of Sales. It now reads the
  seat this agent serves for the viewer (resolve_served_seat: held, else
  the viewer's own, else the primary's) — the answer the agent's prompt
  gets — and says where it came from (holds / your seat / its primary's),
  never a person. No seat → role.error no_seat, said once, with the
  supported objectives still listed. x-role remains only as the readiness
  claim and as a reason to show the card.
- "Your relationship" was never wired: the agent's own primary read "no
  assignment recorded". It is now the viewer's assignment kind via the
  provider's kinds_for (Abilityai/trinity-enterprise#818), answered for a
  stopped agent too.
- "Add operator" pushed the page 47px wider than a 390px screen: the
  email input now gives way (min-w-0) and the button does not wrap.

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

* test: classify ent#814's prompt-context fields for #3274's guard; run the ent#817 migration on the engine's connection

- test_3274's free-text guard (from dev) requires every Optional[str]
  ExecutionContext field to be scanned or named platform-controlled:
  served_role_id is a sanitized seat id, served_person_email is never
  rendered.
- The ent#817 migration test wrote through get_engine() but migrated
  through get_db_connection(); under seed 12345 the two pointed at
  different files ('no such table: agent_sharing'). It now migrates on the
  engine's own DBAPI connection.

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

* test(ent814): the seat-decision user stub carries agent_name, as the real User does

dev's ent#839 self-gate reads current_user.agent_name before any lookup; a bare
SimpleNamespace(id=1) raised AttributeError after the merge.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* docs(architecture): catalog the canon roles read, the seat resolvers and the three-state consent (trinity-enterprise#811/#814/#817)

api-endpoints.md gains GET /api/agents/{name}/canon/roles; backend.md gains
canon_roles_service and the resolve_seat / resolve_served_seat contract on the
assignment seam; database.md marks allow_proactive as NULL/0/1 with both
migration names.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(seat-decisions): the seat on record validates as a canon role id, dots included (trinity-enterprise#814)

Since ent#814 the served seat wins over the agent's decided_by_role, but the
record's check was the ask_class slug (no dots) while canon role ids follow
objective_join_service._ID_RE (roles/head.of.sales.yaml is a valid seat). A
dotted seat on record refused every decision with 422 and the agent could not
work around it. decided_by_role now takes the lowercased canon id shape;
ask_class keeps the strict slug. Regression tests in test_ent814_served_seat.py.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* test(ent731): the guard-metrics whole-read test records its seat like its ent#666 siblings

dev's ent#731 suite reuses the ent#666 fakes but not the autouse _seat_on_record
fixture ent#812 added there, so after the merge read_objective_join owned nothing
(x-role is no longer read) and the test indexed an empty list. Importing the
fixture registers it for this module.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Eugene Vyborov <[email protected]>
obasilakis pushed a commit that referenced this pull request Oct 12, 2026
…80b6) (#3607)

Carries Abilityai/trinity-enterprise#818: seats (#811), per-person seats
(#814), drift on read and three-state consent (#817). It is the private pair
of #3271, whose public seam reads the provider's optional `seat_for` /
`served_seat_for`. The adapter at 8331df5 implements neither, so on dev every
seat holder's role card and objective join read `no_seat` (#3534).

Migration graph checked before advancing (docs/ENTERPRISE.md):
scripts/ci/check_alembic_heads.py gives 21 revisions, 1 head
(0020_seat_holders), PASS.

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.

2 participants