feat(fleet): add CAS-protected stale worker retirement capability (Closes #980) #982
Open
jcwalker3
wants to merge 2 commits from
feat/issue-980-stale-worker-retirement into master
pull from: feat/issue-980-stale-worker-retirement
merge into: :master
:master
:feat/issue-985-project-scoped-launcher-identity
:fix/issue-983-cross-repo-base-ref
:feat/issue-980-stale-worker-retirement
:fix/issue-975-client-identity-heartbeat
:fix/issue-973-cross-repo-canonical-roots
:fix/issue-970-safely-resolve-missing-worktrees
:fix/issue-969-native-mcp-bootstrap
:feat/issue-664-break-glass-restart
:feat/issue-708-mcp-namespace-attachment
:feat/issue-665-restart-audit
:fix/issue-700-durable-walls
:fix/issue-704-prevent-env-workspace-bindings
:feat/issue-707-cross-project-boundaries
:fix/issue-690-review-profile-switch-guard
:fix/issue-953-bootstrap-lock-provenance
:feat/issue-949-native-fleet-inventory
:fix/issue-943-runtime-context-helpers
:fix/issue-945-owning-pr-renewal-evidence
:fix/issue-941-scope-guard-bootstrap-wiring
:docs/issue-930-remote-mcp-coupling-inventory
:fix/issue-892-author-bootstrap-deadlock
:fix/issue-686-detect-reject-manual-mcp
:fix/issue-672-mcp-config-drift
:fix/issue-689-deterministic-mcp-namespace
:feat/issue-666-concurrent-mcp-restart-tests
:feat/issue-659-maintenance-drain-mode
:feat/issue-648-notifications-console
:fix/issue-670-direct-master-incident
:feat/issue-644-console-recovery
:feat/issue-650-providers-insights
:feat/issue-669-scoped-component-recovery
:docs/issue-668-mcp-ha-rolling-restart
:feat/issue-667-console-restart-controls
:feat/issue-645-linkage-console
:feat/issue-643-request-preview-initiate
:fix/issue-897-permission-stale-runtime-classification
:feat/issue-641-runtime-session-view
:feat/issue-663-restart-classes
:feat/issue-661-drain-proof-hard-gate
:fix/issue-854-semantic-container-exclusion
:issue-640
:fix/issue-682-starlette-httpx2
Labels
Clear labels
allocator
anti-stomp
architecture
bug
chore
codex
concurrency
contamination
control-plane
dashboard
database
design
documentation
enhancement
gitea
glitchtip
important
incident
incident-bridge
integration
jenkins
labels
leases
mcp
mcp-health
mcp-menu
multi-project
mutating
nice-to-have
observability
portability
preflight
protected-branch
queue
read-only
reconnect
recovery
refactor
release
reliability
resumable-review
reviewer
roadmap
safety
security
self-hosted
sentry
stale-runtime
status:blocked
status:in-progress
status:pr-open
status:ready
terminal-lock
testing
tracker
type:bug
type:feature
type:feature
type:guardrail
visibility
workflow
workflow-hardening
workflow-hardening
Controller-owned work allocator
Prevent concurrent LLM session stomping
Architecture / structural design
OpenAI Codex client / workflow session surface
Concurrent session safety
Workflow or session contamination incident
MCP control-plane coordination and allocation authority
MCP operational dashboard/queue view
Internal coordination storage (SQLite/Postgres)
Design / investigation, no implementation
Docs / runbooks
New feature or improvement
Gitea MCP workflow
GlitchTip integration
Operational or process incident requiring durable audit trail
Sentry-to-Gitea incident bridging
Integration testing
Jenkins integration
Label taxonomy management
Lease adopt/release/expire lifecycle
MCP server / tooling
MCP namespace and runtime health
MCP menu surface
Work spanning multiple monitoring projects or Gitea repos
Mutating action; requires gating
Observability, metrics, traces, error reporting
Cross-platform / portability
Shared preflight gates before mutation
Protected branch / stable-branch policy concern
Work queue visibility and allocation
Read-only, no mutation
MCP client reconnect/reload recovery path
Recovery paths for stale/foreign leases
Code refactor / restructure
Release / versioning
Reliability / failure handling
Persist and resume prepared review verdicts across sessions
Reviewer workflow tooling
Roadmap / umbrella issue
Safety rails and fail-closed mutation guards
Security / trust boundary
Self-hosted infrastructure integration
Sentry error monitoring integration
Stale backend daemon / runtime-vs-master parity failures
Issue is blocked
Issue is being worked on
Issue has an open pull request
Issue is ready for work
Terminal review lock (#332) path
Tests / test coverage
Issue tracker hygiene / meta
Bug or defect
Feature or enhancement
Feature or enhancement
Safety gate or guardrail
Workflow state visibility for LLMs/operators
Cross-tool workflow
LLM workflow coordination hardening
LLM workflow coordination hardening
No labels
Milestone
No items
No Milestone
Projects
Clear projects
No projects
Notifications
Due Date
No due date set.
Dependencies
No dependencies set.
Reference: Scaled-Tech-Consulting/Gitea-Tools#982
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.
Summary
Adds a sanctioned controller/reconciler capability that retires conclusively
stale MCP worker-registry rows through a dry-run-first, compare-and-swap
protected workflow (#980).
#978 / merged PR #979 made the fleet observable but read-only. There was no
native mutation that could retire registry rows whose owning process is gone,
and the only available token —
mcp_fleet_snapshot'sregistry_revision— isseeded with
snapshot_atat second precision, so a CAS gated on it can neverpass. This implements the corrected R3-C contract from the #980 body.
Stable registry CAS
New
mcp_fleet_retirement.registry_fingerprint(rows)derives the tokenexclusively from canonical retirement-relevant registry content
(
FINGERPRINT_FIELDS): identity, ownership, liveness, registration state,repository binding. It contains no
snapshot_at, wall-clock, request,report-generation, or serialization time, and the serialized rows are sorted so
iteration order cannot perturb the digest. Numeric values are canonicalised, so
a TTL that round-trips through SQLite as
900.0hashes identically to900.A second
candidate_fingerprintpins the exact approved candidate set.The existing time-seeded
fleet_revision/registry_revisionis leftexactly as it is — a separate token was the smaller and safer change, and the
#978 snapshot's shape and semantics are unchanged.
Transactional revalidation and fail-closed behaviour
WorkerRegistry.retire_stale_workersperforms the whole decision inside oneBEGIN IMMEDIATEtransaction: re-read the authoritative rows → recompute theregistry fingerprint from those rows → recompute the eligibility plan from
those rows (re-reading active workflow leases, so a lease acquired after
planning still protects its worker) → compare the candidate fingerprint →
revalidate every requested identity → retire each survivor with a guarded
UPDATEthat additionally assertsstatus,last_heartbeat_at,generation_id,session_id,fencing_epoch, andpidare unchanged.There is no window between a safety check and its matching write, so the
check/delete race cannot occur. Drift returns
registry_revision_movedorcandidate_set_movedwithretired_count: 0and no write. Any exception —including a commit failure — rolls back and returns
transaction_failedwithsuccess: false,retired_count: 0,mutation_performed: false; a partialwrite can never be reported as success.
A registration is retired only when every conjunct holds:
statusactive,all required registry fields present, parsable heartbeat, not live,
pid_alive is False(an unprobeableNonefails closed), expired heartbeat,ownership_state == "stale", canonical repository binding, no identityevidence shared with a live or unprobeable worker, and no active workflow-lease
ownership. Everything else is preserved with a structured reason code.
Retired rows keep their history (
status -> retired, plusretired_at,retired_by,retirement_reason); nothing is deleted. Becauseretiredis notactive, the #978 snapshot counts them as historical rather than stale.Retirement does not repair untrusted live identity. Live workers on legacy
pid-/proc-instance identities are preserved untouched and keep theirlegacy_incomplete_identityblockers, sostale_worker_count: 0alongsidelive_fleet_safe: falseis a truthful result, and thepost_applyblockreports the remaining blockers rather than claiming safety.
Authorization
Exposed as
gitea_plan_stale_worker_retirement(read-only) andgitea_apply_stale_worker_retirement, both restricted tocontroller/reconcilerrole kinds — matching thegitea_snapshot_instance_fleetrestriction. The Gitea operation gate stays
gitea.readbecause the mutationlands in the local control-plane worker registry, not in Gitea, exactly as
the #601 lease lifecycle does. No new Gitea write permission is introduced for
any profile and no author permission is broadened. Apply additionally
re-asserts master parity, stable-runtime mode, fresh capability resolution,
workflow-lease enumeration, and #948 daemon-cohort uniqueness before touching
anything.
No authorization bypass, recovery grant, or BAA activation is added, and the
observational fleet snapshot is not turned into a gate on author work.
Changes
mcp_fleet_retirement.py(new) — pure decision layer:registry_fingerprint,candidate_fingerprint,plan_stale_worker_retirement,summarize_plan,reason codes,
FINGERPRINT_FIELDS,REQUIRED_IDENTITY_FIELDS.mcp_worker_identity.py—STATUS_RETIRED; additiveretired_at,retired_by,retirement_reasoncolumns;WorkerRegistry.retire_stale_workers.gitea_mcp_server.py— the two tools plus_retirement_role_block,_retirement_runtime_block,_retirement_protected_owners,_retirement_plan,_retirement_revalidation_plan,_retirement_post_apply.task_capability_map.py— four additive task entries,gitea.read/controller.docs/stale-worker-retirement.md(new), cross-linked fromdocs/instance-fleet-identity.md; both tools registered indocs/mcp-tool-inventory.md.tests/test_issue_980_stale_worker_retirement.py(new).Tests
tests/test_issue_980_stale_worker_retirement.py— 40 passed, 23 subtestspassed. Covers token stability across observation times, canonical ordering,
numeric-typing stability, retirement-relevant change detection (8 subtests),
heartbeat and TTL changes, plan-performs-no-mutation, moved registry token
retires zero, moved candidate set retires zero, per-target revalidation, a
worker becoming live between plan and apply, a worker becoming ambiguous,
incomplete legacy identity fail-closed, mixed eligible/ineligible fleets,
transaction failure cannot report partial success, structured
mutation_performed/ reason-code accuracy, idempotent replay, post-apply fleetcompatibility, and capability exposure. Includes the explicit regression test
proving the old
snapshot_atderivation moved the token one second apart whilethe new registry CAS token does not.
Adjacent suites (#980, #978, #975, #948, task-capability role invariants) —
192 passed, 124 subtests passed.
Full suite, both runs from
branches/worktrees (baseline detached at master108cbfa173de34470d7abc022b929e6b3adc418a):The failing test set is byte-identical between the two runs (
commover thesorted
FAILEDlines reports no line on either side): zero regressionsintroduced, zero pre-existing failures masked. The +40 passing delta is this
PR's new tests.
The 28 baseline failures reproduce identically on unmodified master and are
pre-existing (branch-cleanup guard, commit payloads, dirty-orphan worktree
recovery, #702 review findings, #784 dependency-edge schema, #956 threat-model
anchors, mcp_server preflight/whoami, post-merge moot lease, PR-ownership
mismatch, preflight workspace forwarding, reconciler cleanup/close/supersession,
workspace-guard alignment). They fall outside the scope of this change.
Scope
BAA, issue #981, PR #906, and issue #650 are not dependencies of this work
and were not touched. Review
624, branchfeat/issue-650-providers-insights,worktree
branches/conflict-fix-pr-906-983e8ac, profiles, configuration,credentials, sessions, and running processes were not modified. No real worker
registry row was retired — every test uses a throwaway SQLite database.
Reviewer focus
Token stability (
FINGERPRINT_FIELDScompleteness), the transaction boundary inWorkerRegistry.retire_stale_workers, the per-row guardedUPDATE, and thefail-closed preservation of active or ambiguously identified workers. One
deliberate interpretation is called out in the module docstring and the doc:
trusted
inst-…launcher provenance is not required for retirement, because#980 places trusted
client_instance_idpropagation out of scope and requiringit would preserve every legacy row forever; what is required is that the registry
fields the eligibility conjunction reads are present.
Closes #980
repo: Scaled-Tech-Consulting/Gitea-Tools
pr: #982
issue: #980
reviewer_identity: sysadmin
profile: prgs-reviewer
session_id: 65116-044a9d36aaed
worktree: /Users/jasonwalker/Development/Gitea-Tools/branches/review-pr982-c0c6d14
phase: claimed
candidate_head:
c0c6d14b73target_branch: master
target_branch_sha:
108cbfa173last_activity: 2026-07-30T20:03:53Z
expires_at: 2026-07-30T20:13:53Z
blocker: none
Canonical PR State
STATE: request_changes — independent reviewer found three hard-rule blockers (authorization, identity proof, external safety inputs outside TX)
WHO_IS_NEXT: author
NEXT_ACTION: prgs-author addresses only B1–B3 on PR #982, adds required regression tests, pushes a new head, and publishes a new exact-head author handoff.
NEXT_PROMPT:
WHAT_HAPPENED: Independent prgs-reviewer review of PR #982 at pinned head
c0c6d14b73. Scope reconstructed (1 commit, 8 files, Closes #980). Focused #980 tests 40/40 pass; adjacent 195 pass. Formal REQUEST_CHANGES for B1/B2/B3.WHY: Gate A hard rule fails (apply authorized solely by gitea.read). Gate B hard rule fails (complete untrusted legacy rows are retireable). Gate D hard rule fails (lease DB + PID probe outside registry TX without equivalent fencing at write time).
ISSUE: #980
HEAD_SHA:
c0c6d14b73REVIEW_STATUS: REQUEST_CHANGES
MERGE_READY: no
BLOCKERS: B1 dedicated mutation capability missing; B2 incomplete identity = non-null columns only; B3 external lease/PID safety inputs not fenced at UPDATE.
VALIDATION: whoami sysadmin/prgs-reviewer; parity in_parity mutation_safe at 108cbfa173de; head pin confirmed; lease 18835 own_active; worktree branches/review-pr982-c0c6d14 @
c0c6d14clean; focused tests 40 passed; adjacent 195 passed; no live registry mutation; no source edits.LAST_UPDATED_BY: sysadmin / prgs-reviewer (gitea-reviewer)
Independent review — REQUEST_CHANGES (V6-B)
Reviewed head:
c0c6d14b73add36ac157d501c603fd9ea51de1daReviewer:
sysadmin/prgs-reviewer(namespacegitea-reviewer)Base:
master@108cbfa173de34470d7abc022b929e6b3adc418aAuthor:
jcwalker3(identity separation verified)Author handoff (I5-A, comment 18823) and all author test claims were treated as untrusted until independently verified.
Scope reconstruction (verified)
Exactly one commit above master; eight files as claimed:
mcp_fleet_retirement.py,mcp_worker_identity.py,gitea_mcp_server.py,task_capability_map.py, three docs,tests/test_issue_980_stale_worker_retirement.py.Closes #980present. No unrelated behavior observed.Non-blocking design strengths: stable fingerprints without wall-clock; plan mutation-free; drift retires zero; TX rollback reports
transaction_failed; per-row guarded UPDATE; live/unprobeable/shared-identity/foreign/protected rows preserved in plan layer; retired rows historical not deleted; post-apply does not claim fleet safety with residual live legacy blockers.Blocking findings
B1 — CRITICAL (Gate A): Apply authorized by
gitea.readalonetask_capability_map.pyapply_stale_worker_retirement/gitea_apply_stale_worker_retirement;gitea_mcp_server.pygitea_apply_stale_worker_retirement,_retirement_role_block_profile_operation_gate("gitea.read")then capability re-check still requires onlygitea.read. Role controller/reconciler is secondary, not a mutation capability.gitea.read. Plan and apply share the observational permission class.CapabilityExposureTestsassertsgitea.read; never proves only-read profiles cannot apply.gitea.worker_registry.retiregranted only to controller/reconciler; map apply tasks only; gate apply with that permission before any write; keep plan ongitea.read.gitea.readdenied; author/reviewer/merger denied; controller/reconciler with mutation perm allowed on isolated temp DB; plan still read-only.B2 — CRITICAL (Gate B): Incomplete identity = missing columns; complete untrusted legacy rows retire
mcp_fleet_retirement.pyREQUIRED_IDENTITY_FIELDS,plan_stale_worker_retirement_missing_identity_fieldsonly null/blank checks. Full columns +legacy-pid-…+ dead PID + expired HB → eligible. Independent probe confirmed candidate_count=1 for such a row.inst-*provenance deliberately excluded; liveness is localos.kill(pid,0)only.B3 — HIGH (Gate D): Lease DB + PID liveness outside worker-registry TX
WorkerRegistry.retire_stale_workers;_retirement_protected_owners;is_process_aliveNon-blocking
Verdict
REQUEST_CHANGES at
c0c6d14b73add36ac157d501c603fd9ea51de1da. Do not merge.WHO_IS_NEXT: prgs-author to address only the exact requested changes on PR #982, add the required regression tests, push a new head, and publish a new exact-head author handoff.repo: Scaled-Tech-Consulting/Gitea-Tools
pr: #982
issue: #980
reviewer_identity: sysadmin
profile: prgs-reviewer
session_id: 65116-044a9d36aaed
worktree: /Users/jasonwalker/Development/Gitea-Tools/branches/review-pr982-c0c6d14
phase: released
candidate_head:
c0c6d14b73target_branch: master
target_branch_sha:
108cbfa173last_activity: 2026-07-30T20:09:19Z
expires_at: 2026-07-30T20:19:19Z
blocker: manual-release
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.