Skip to content

fix: apply tool inventories in capture order so stale captures cannot overwrite newer state (Spec 117 PR-3; #1565) - #1609

Merged
Dumbris merged 2 commits into
mainfrom
fix/117-pr3-capture-ordering
Oct 13, 2026
Merged

Dumbris merged 2 commits into
mainfrom
fix/117-pr3-capture-ordering

Conversation

@Dumbris

@Dumbris Dumbris commented Oct 13, 2026

Copy link
Copy Markdown
Member

Scope

Spec 117 PR-3 only (#1565): tool inventories are applied in the order they were captured, so an older tools/list result that reaches the apply late cannot overwrite newer approval records, index entries, last-good snapshots or StateView (dispatch) hints.

  • Capture identity (FR-030). Every upstream tools/list carries managed.InventoryCapture{Seq, Epoch, Client}. The flight leader stamps it from a process-global counter when it owns the list and before the upstream request; coalesced waiters get the capture of the flight they joined (held in the existing per-flight listToolsCall). New: ListToolsCaptured, ListToolsFreshCaptured. ListTools/ListToolsFresh keep their signatures.
  • Retirement (FR-036). Client.Retire() (atomic flag) is set by the manager when it replaces (endpoint change) or removes a client, under captureMu W. CaptureIsCurrent = same client, not retired, connection epoch unchanged.
  • Captured sweep (FR-031). Manager.DiscoverToolsReportCaptured returns one capture per listed server, from that server's own list.
  • Ordered admission (FR-032, FR-033, FR-033a, FR-037). admitInventoryHeld runs under the server's tool-approval lock, in the same hold as every write of the pass, in all inventory paths: sweep, single-server discovery (connect, tools/list_changed, refresh), quarantined review capture, lenient-empty observation, and the snapshot reconciliations (approval reindex, sweep fallback).
    • An older capture writes nothing (no re-list).
    • A capture from a retired or reconnected client writes nothing; the caller re-lists the current client.
    • A seq-0 (fixture) inventory is applied only while nothing ordered was applied.
    • A lenient empty result is an observation fence: it advances applied and writes nothing else.
    • Reconciliation re-applies the retained snapshot only while its capture is current and is the newest one with definitions. Otherwise the reindex re-lists and the fallback skips.
    • lastGoodTools gets a parallel lastGoodCapture and is replaced only by a newer-or-equal capture.

Design decisions and deviations from the spec

Main already had a lot of the original design when this was written. Spec 116 D15 already runs the eligibility check, decisions, deletes, eviction, index writes, last-good snapshot and StateView publish in one approval-lock hold. Every ineligible writer (quarantine, disable, PATCH, reload, restart persist) is a Runtime.Commit that stores the row and purges the index under that lock, which closed G8 and G9. Details are in specs/117-review-bound-approvals/research.md → "PR-3 implementation notes".

  • No separate published counter. The StateView publish already runs inside the admitted hold, so applied gates it.

  • applied and definitions advance at admission. A newer capture whose apply later fails still fences older ones, and the retained snapshot is not re-applied over its partial writes (the reindex re-lists instead). This is the fence half of FR-018.

  • No Manager.WithCaptureCurrent. Currency is a lock-free atomic check under the approval lock. A reconnect or replacement after the check produces a newer capture, and that capture has to take the same lock. Holding epochMu across a 320-tool apply would block connect/disconnect. The quarantined capture keeps main's outer WithCurrentClientOnEpoch wrapper. No new lock edge is added in either direction.

  • Not in this PR (follow-up):

    • FR-018 review-dirty flag, with its dispatch refusal and ErrReviewNotRecorded/503;
    • FR-032a record-derived removal workset;
    • FR-034's supervisor change that drops retained tools of disabled or quarantined servers.

    These cover storage-failure modes and do not depend on ordering. FR-034/FR-035 writer routing (persistServerIneligibleLocked, the CI guard script) is superseded by Spec 116's single commit pipeline.

Lock order

Unchanged: configCommitMu (Spec 116) → captureSnapMu → per-server approval lock → storage / index / supervisor state. The new code takes no lock of its own. Inside the approval lock it only reads two client atomics (retired, connectionEpoch). Retire is an atomic store made under the manager's existing captureMu+mu section.

Compatibility

  • No wire, config or storage change. No new dependencies.
  • Behaviour change: after a reconnect, the approval reindex lists the server again (one tools/list) instead of re-applying the old connection's snapshot.

Verification

  • Failing first on main (942afe6): 4 tests in internal/runtime/inventory_capture_order_test.go:

    • an older capture reverts a newer changed hold;
    • an older capture resurrects a removed tool;
    • an older capture lands after a lenient empty result;
    • the reindex after a reconnect re-applies the stale snapshot.

    All pass on the fix.

  • Other new tests (pass on the fix):

    • sweep vs reactive ordering;
    • the seq-0 rule;
    • a retired client's capture is discarded;
    • quarantined review capture ordering;
    • approval during a paused pass;
    • managed capture and retire unit tests;
    • manager retire test;
    • a 2 s -race stress test (refresh, sweeps, reindex, approve/block/enable, quarantine-toggle commits, upstream flips) with a goroutine dump on timeout.
  • Test lanes:

    • go test -race -tags server -timeout 30m -skip "E2E|Binary|MCPProtocol|TestInfoEndpoint|TestGracefulShutdownNoPanic|TestSocketInfoEndpoint" ./internal/...: green.
    • ./scripts/test-api-e2e.sh (scratch port): 70/70.
    • go test ./tests/tpa-attack-lab/: ok.
    • make build: ok.
    • golangci-lint v2, bare and --build-tags server: no finding in changed files.
  • Live reproduction on main, without test hooks:

    1. The periodic sweep lists a fast server and then a slow one.
    2. While the slow list runs, the upstream turns read_note destructive and a refresh holds it as changed.
    3. The sweep then applies its older read-only capture. Main reverts the hold to approved and re-indexes the tool, and a read-scoped call_tool_read reaches the upstream.

    The fixed binary drops the stale capture ("Tool inventory dropped: a newer capture was already applied"). read_note stays held and unindexed, and call_tool_read is refused with 0 upstream calls. After operator approval, the index and describe_tool carry the destructive hints. A restart keeps this state.

  • SC-005: 320-tool refresh, median ~49 ms on main vs ~48 ms on the fix.

  • Concurrency loop: 50 iterations of refresh + approve + quarantine toggle. Status latency is ≤10 ms, and the review state and the index agree at the end.

Cross-model review (zcode / Opus concurrency review per T313) is left to the lead.

Fixes #1565

🤖 Generated with Claude Code

Every upstream tools/list now carries a managed.InventoryCapture
{Seq, Epoch, Client}: a process-global sequence stamped by the flight
leader before the upstream request and shared with coalesced waiters.
The manager retires replaced and removed clients, and the sweep gets one
capture per server (DiscoverToolsReportCaptured).

The runtime admits each inventory under the server's tool-approval lock,
in the same hold as its record, index, last-good snapshot and StateView
writes (Spec 116 D15): a capture older than one already applied, or from
a retired or reconnected client, writes nothing; a lenient empty result
is an observation fence; the approval reindex and the sweep fallback
re-apply the retained snapshot only while its capture is still current,
and otherwise re-list or skip.

Related #1565
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

📦 Build Artifacts

Workflow Run: View Run
Branch: fix/117-pr3-capture-ordering

Available Artifacts

  • archive-darwin-amd64 (31 MB)
  • archive-darwin-arm64 (28 MB)
  • archive-linux-amd64 (19 MB)
  • archive-linux-arm64 (17 MB)
  • archive-windows-amd64 (31 MB)
  • archive-windows-arm64 (28 MB)
  • frontend-dist-pr (0 MB)
  • installer-dmg-darwin-amd64 (27 MB)
  • installer-dmg-darwin-arm64 (25 MB)
  • smart-mcp-proxymcpproxy-goYB5ED2.dockerbuild (0 MB)

How to Download

Option 1: GitHub Web UI (easiest)

  1. Go to the workflow run page linked above
  2. Scroll to the bottom "Artifacts" section
  3. Click on the artifact you want to download

Option 2: GitHub CLI

gh run download 38330762638 --repo smart-mcp-proxy/mcpproxy-go

Note: Artifacts expire in 14 days.

@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 83.42857% with 29 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
internal/runtime/lifecycle.go 84.31% 6 Missing and 2 partials ⚠️
internal/runtime/inventory_order.go 88.13% 5 Missing and 2 partials ⚠️
internal/upstream/managed/client.go 65.00% 6 Missing and 1 partial ⚠️
internal/upstream/managed/capture.go 64.28% 5 Missing ⚠️
internal/upstream/manager.go 83.33% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

…nt-empty observation (Spec 117 PR-3 T306(5r))
@Dumbris
Dumbris merged commit 896d935 into main Oct 13, 2026
46 checks passed
Dumbris added a commit that referenced this pull request Oct 13, 2026
…he current instance in the inventory stress test (Spec 116 PR3 resync)

Under Spec 116 PR3 a commit that changes Quarantined unregisters the
instance under captureMu (retiring it) and the commit's connect worker
installs the instance of the new generation asynchronously. The #1609
stress test required GetClient to succeed synchronously after the final
unquarantine, which fails whenever the last toggle left the server
quarantined (5/20 under GOMAXPROCS=2). Wait for the current instance to
be registered and connected; the final capture and the index/approval
consistency check are unchanged.
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.

bug: out-of-order tool-inventory passes overwrite newer approvals, index entries and dispatch metadata

2 participants