Skip to content

fix(startup): close startup-recovery vs /internal/execute-task race (#748) - #812

Merged
vybe merged 3 commits into
devfrom
feature/748-startup-recovery-race
May 12, 2026
Merged

vybe merged 3 commits into
devfrom
feature/748-startup-recovery-race

Conversation

@dolho

@dolho dolho commented May 12, 2026

Copy link
Copy Markdown
Contributor

Summary

Closes the race documented in #748:

T+0ms    Scheduler INSERTs row + POSTs /internal/execute-task (backend down)
T+5ms    Backend startup begins; recover_orphaned_executions sees no slot
         in Redis → marks row FAILED
T+30ms   Now-late /internal/execute-task handler runs; capacity.acquire()
         ZADDs slot for the already-FAILED execution → LEAKED SLOT

Two defences, both shipped together:

  1. STARTUP_RECOVERY_GRACE_SECONDS = 15 — recover_orphaned_executions
    skips rows whose started_at is within the grace window. Mirrors
    WATCHDOG_MIN_AGE_SECONDS (60s) at the regular-cycle watchdog
    (cleanup_service.py:609). The skipped row is recovered either by
    the late handler completing normally or by the regular watchdog cycle.
  2. Warming-up 503 gate — /internal/execute-task returns 503 until
    mark_startup_recovery_complete() flips a flag at the end of recovery
    (in a finally block, so even an exception-out path opens the gate).
    The scheduler retries on transient errors, so the request is replayed
    once the backend is done racing itself.

Defence 1 closes the documented timing. Defence 2 closes the inverse
timing where the late ZADD lands before recovery completes. Together
they make the race symmetrically unreachable.

Files changed

File Change
src/backend/services/cleanup_service.py STARTUP_RECOVERY_GRACE_SECONDS; _within_startup_grace; is_/mark_/reset_startup_recovery_flag*; recover_orphaned_executions returns skipped_grace in its dict
src/backend/main.py Calls mark_startup_recovery_complete() in finally after the startup recovery block
src/backend/routers/internal.py execute_task_internal returns 503 while is_startup_recovery_complete() is False
tests/unit/test_startup_recovery_race.py 12 cases (new file)

Test plan

Relates to #748.

🤖 Generated with Claude Code

…748)

`recover_orphaned_executions` (run on backend startup, main.py:467) marked
SQL execution rows as failed when their `agent:slots:{name}` ZSET
membership was missing, with no coordination against in-flight
`/internal/execute-task` requests the scheduler queued while the
backend was down. Result: row FAILED at T+0ms, slot ZADDed at T+30ms,
slot never released → leaked Redis slot until 1200s TTL or next
`_cleanup_stale_slots_for_agent` pass.

Two defences shipped, both addressing the seam from different sides:

1. **Grace window in recover_orphaned_executions** — rows whose
   `started_at` is younger than `STARTUP_RECOVERY_GRACE_SECONDS` (15s)
   are skipped instead of failed. Mirrors the regular-cycle watchdog's
   `WATCHDOG_MIN_AGE_SECONDS` (60s) pattern at cleanup_service.py:609.
   The skipped row is handled either by the late `/internal/execute-task`
   handler completing normally, or by the regular watchdog cycle once
   the row ages past the watchdog's own grace window.

2. **Warming-up 503 gate** — `/internal/execute-task` returns 503 until
   `mark_startup_recovery_complete()` flips a module-level flag at the
   *end* of recover_orphaned_executions (or its `finally`, on raise).
   The scheduler treats 503 as transient and retries, so the late
   request is replayed against a backend that's done racing itself.

Defence 1 alone closes the documented timing (recovery completes before
the late ZADD). Defence 2 closes the inverse timing (late ZADD lands
before recovery completes) and is the ordering primitive the issue
author preferred. Together they make the race symmetrically unreachable.

Tests: tests/unit/test_startup_recovery_race.py (12 cases, all green).
Covers: _within_startup_grace boundary behavior; fresh/old/mixed-batch
behaviour in recover_orphaned_executions; flag get/set/idempotency;
static-source check that routers/internal.py wires the gate.

Relates to #748.

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

`recover_orphaned_executions` now returns `skipped_grace` in its result
dict (#748). The empty-running-executions test compared the dict by
full equality, so adding the key broke it. Update the expected dict —
the new key is part of the function's contract.

All other tests in this file use key access (`result["recovered"]`)
and were unaffected.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
vybe pushed a commit that referenced this pull request May 12, 2026
…or missing (#749) (#814)

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.

Validated via /validate-pr. Two complementary defenses for the startup-recovery race — grace window mirrors the existing WATCHDOG_MIN_AGE_SECONDS pattern, 503 gate correctly uses a finally block so it opens even on exception. 12 test cases cover all the relevant timing paths. Clean. LGTM.

Both #748 (startup grace window) and #749 (Redis-side slot reconciliation)
touched recover_orphaned_executions. Keep both: skipped_grace counter and
_within_startup_grace from #748, _reconcile_orphaned_slots call and
redis_slots_reclaimed from #749. Return dict now carries all four counters.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@vybe
vybe merged commit 7b63018 into dev May 12, 2026

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

Merge conflict with dev — please rebase and re-push:

git fetch origin dev && git rebase origin/dev

Then force-push and this will be re-approved.

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
…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]>
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