Addresses five architect findings across two review rounds, all on
the authority package introduced in 5c663b8. The core S2 boundary
(Publisher is the sole minter, identity keyed by (VolumeID,
ReplicaID), Directive is the only policy seam) stays unchanged;
this commit tightens correctness of delivery and the strength of
the non-forgeability proof.
1. Close-safe delivery (High). apply()'s fan-out ran outside
pub.mu and could race with cancel()/Run-exit closing the same
channel. The former deliverLatest free function was not
close-aware — a concurrent close would produce send-on-closed
panics, and its drain-retry loop on a closed channel (where
receive is permanently ready with zero value) would spin
forever.
Fix: subscription now owns a sync.Mutex + closed flag. New
methods subscription.deliver() and subscription.close() both
acquire s.mu; deliver() returns early if closed, and close()
is idempotent. The deliverLatest free function is gone;
apply() calls s.deliver(next). cancelSubscription and
closeAllSubscriptions call target.close() instead of closing
target.ch directly.
Regression: TestPublisher_CancelDuringDeliveryDoesNotPanic
stress-runs 50 concurrent subscribe/cancel goroutines against
200 concurrent Refresh asks on the same (vid, rid). Asserts no
panic and no hang within 5 s.
2. Catch-up ordering race (High). Subscribe() registered the new
subscriber in p.subs under pub.mu, then released the lock and
did a blocking sub.ch <- st.info. A concurrent apply() could
deliver a newer fact first; the delayed catch-up would then
enqueue the older fact, producing stale/out-of-order delivery
on a route that must converge to current authority truth.
Fix: the catch-up send now happens INSIDE the pub.mu critical
section, immediately after the subs-map insert. Because sub.ch
is cap=1 and the fresh subscription is invisible to any other
goroutine until pub.mu is released, the catch-up send is
guaranteed non-blocking. Any later apply() either runs before
us (catch-up state IS current) or sees us in the subs map and
drains our stale catch-up via deliver(). Strict ordering.
Regression:
TestPublisher_LateSubscriberReceivesLatestUnderConcurrentPublish
runs 200 iterations of (concurrent Reassign + fresh Subscribe +
drain); asserts drained epoch <= current authoritative epoch
every iteration.
3. AST non-forgeability proof gap — deferred-mutation bypass
(Medium). The earlier AST walker explicitly skipped short
declarations (x := adapter.AssignmentInfo{}), so the pattern
x := adapter.AssignmentInfo{}
x.Epoch = userInput
bypassed both checks: the literal is zero-valued so check (a)
did not trigger, and the short-decl path was ignored in (b).
Fix: auditNonForgeability now handles the AssignStmt branch
with Tok == token.DEFINE; any RHS that is a composite literal
of AssignmentInfo type is flagged as the deferred-mutation
bypass shape, regardless of field values. Also added the
long-decl-with-value case: var x = adapter.AssignmentInfo{}.
Regression (two synthetic-source tests that exercise the audit
function directly):
- TestNonForgeability_CatchesShortDeclBypass
- TestNonForgeability_CatchesVarDeclBypass
4. AST non-forgeability proof gap — pointer form (Medium,
subsequent round). After the short-decl fix, the architect
noted the same bypass in pointer form was still outside the
proof:
x := &adapter.AssignmentInfo{}
x.Epoch = userInput
The AST walker only recognized a bare *ast.CompositeLit on the
RHS, missing the UnaryExpr(&, CompositeLit) wrapper.
Fix: new helper unwrapAddrOfCompositeLit recognizes both
X{...} and &X{...}. Both GenDecl-with-value and AssignStmt
branches use it.
Regression:
- TestNonForgeability_CatchesPointerShortDeclBypass
- TestNonForgeability_CatchesPointerVarDeclBypass
5. Doc drift (Low). Two doc blocks still described the pre-fix²
state: docs/p14-s2-design.md said "simple 'forbidden
constructor' grep" and docs/p14-s2-closure.md listed
Unsubscribe as a Publisher method. Both updated to reflect the
AST-based whole-repo walker (covering value and pointer
forms) and the per-subscription cancel API with no key-wide
unsubscribe verb. Test count in closure.md bumped to 26 and
pointer-form test names added to the verification list.
No changes to engine, adapter, transport, ops, storage, or
sparrow. Authority tests: 26 pass. Full module: 12 packages pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
9.1 KiB
P14 S2 — Closure (what S2 closed, what belongs to S3)
This note records exactly what landed in S2, exactly what stayed out, and where the boundary with S3 sits. It is intended to be stable: future phases must not quietly widen S2's scope after the fact.
The audit note is p14-s2-audit.md. The design note is
p14-s2-design.md. They are unchanged by this closure.
What S2 closed
-
A system-owned publication route for assignment truth. The new package
core/authority/hosts aPublisherthat authorsadapter.AssignmentInfovalues and fans them out to subscribers keyed by(VolumeID, ReplicaID). The publisher is the only production code in V3 that constructs anAssignmentInfowith a non-zeroEpoch. -
Ack-gated authorship of
EpochandEndpointVersion. The only input to the publisher is a narrowAssignmentAsk(VolumeID,ReplicaID,DataAddr,CtrlAddr,Intent). Epoch and EndpointVersion are output, not input. Directives cannot hand the publisher a preformed epoch. -
Three explicit authoring intents.
Bind,RefreshEndpoint,Reassign. Each has a pinned, table-specified publisher action. Rejected and no-op cases are explicit. Retirement (Remove) is deliberately deferred. -
A Directive seam for S3.
Directive.Next(ctx) AssignmentAskis the single upstream interface. The trivialStaticDirectiveships in S2. S3's failover policy will plug in behind the same interface when it arrives — it will not need to reach into the publisher. -
A Bridge that forwards publisher output to the adapter. The
Bridgehelper subscribes to a(VolumeID, ReplicaID)stream viaSubscribe(which returns a per-subscription cancel) and forwards eachAssignmentInfoto the adapter's existingOnAssignmentingress. The adapter remains the one and only consumer entry point; no second mutation ingress was added. Per-subscription cancel ensures one Bridge exiting never disconnects other consumers on the same stream.
5a. Lossless-for-current-fact delivery. Per-subscription channels have capacity 1 with overwrite-latest semantics: if a new publication arrives before the subscriber drains the prior one, the publisher replaces the pending stale value with the latest. The subscriber therefore never silently loses the current authoritative state. Intermediate states may be coalesced; for authority truth that is correct (the engine cares about current identity, not interstitial history).
-
Closure target met. The integration test
TestClosureTarget_SparrowReachesHealthyViaAuthorityRouteincore/authority/authority_test.goboots aPublisherwith aStaticDirective, wires aBridgeinto a realVolumeReplicaAdapter, and reachesMode == ModeHealthywithout anyharness.assign(...)call. -
Non-forgeability is enforced by AST-based structural test.
TestNonForgeability_NoAssignmentInfoMintingOutsideAuthorityparses every production.gofile in the whole repo (NOT justcore/— also coverscmd/and any future production packages) usinggo/ast. It fails if a file outside the allowlist either (a) constructsAssignmentInfovia composite literal with a non-zeroEpochorEndpointVersionfield, or (b) declares a local variable of typeAssignmentInfo(the classic bypass shape:var x AssignmentInfo; x.Epoch = input). Allowlist:core/authority/,core/calibration/,core/conformance/,core/schema/. Adding a new package to the allowlist is an explicit, reviewable change. -
Sparrow demos migrated to authority route. The three pre-existing demos in
cmd/sparrow/main.go(healthy / catch_up / rebuild) previously mintedAssignmentInfowith hard-coded epochs directly. After S2 they all route assignment truth through a sharedauthority.Publisher: thehealthydemo issues anIntentBind, thecatch_upandrebuilddemos issueIntentReassign. No demo code incmd/sparrow/main.goconstructsAssignmentInfodirectly — the non-forgeability test enforces this.
What S2 did NOT close
Explicit non-goals, to avoid future scope drift:
- No failover policy. S2 does not decide who becomes primary, when to promote, when to reassign, or under what conditions. Those are S3.
- No eligibility rules. S2 does not reason about which replicas are allowed to serve at an epoch.
- No placement or rebalance. S2 does not choose where replicas go or move them.
- No retirement intent.
Removeis deferred. Neither of the possible retirement delivery shapes (channel close vs. a new adapter mutation ingress) fit the S2 boundary. - No external control API. There is no HTTP or CLI endpoint
that accepts an
AssignmentInfoor anAssignmentAsk. That surface belongs to P15. - No V2 port of policy-tangled units.
HandleAssignment(),promote(),demote()are NOT imported and will not be ported as copies in any future V3 phase. - No new engine fact, no new engine command, no new truth domain. The engine is untouched by S2.
- No new mutation ingress on the adapter.
OnAssignmentstays the sole consumer entry point.
S2 / S3 boundary (table)
| Question | Owned by | Notes |
|---|---|---|
| Who publishes assignment truth? | S2 (authority.Publisher) |
|
| How does the adapter receive it? | S2 (Bridge → OnAssignment) |
|
Who authors Epoch / EndpointVersion? |
S2 (Publisher mints from Intent) |
Never accepts preformed values. |
| When should epoch bump? | S3 | S2's Directive is the seam. |
| Who is eligible to be primary? | S3 | |
| What triggers a failover? | S3 | |
| How should replicas be placed or rebalanced? | S3 | |
| What retirement looks like on the wire? | S3 / P15 | Deferred. |
| What is the external control API? | P15 |
Files added / changed in S2
Added:
core/authority/directive.go—AskIntent,AssignmentAsk,Directive,StaticDirective, validation errors.core/authority/authority.go—Publisher,Subscribe(returns per-subscription cancel func),LastPublished,Run,Bridge,AssignmentConsumer. No key-wide unsubscribe verb — per- subscription cancel is the only teardown path.core/authority/authority_test.go— 26 tests covering intent semantics, fan-out keyed by(VolumeID, ReplicaID), independent-unsubscribe, lossless-for-current-fact delivery, cancel-vs-delivery race (stress test), late-subscriber-under-concurrent-publish ordering, late-subscriber catch-up,Runloop,RunClosesLiveSubscriptionsOnExit,Bridge, closure target, AST-based non-forgeability including direct bypass-coverage tests forvar x AssignmentInfo,x := adapter.AssignmentInfo{}, and the pointer-form variantsvar x = &adapter.AssignmentInfo{}andx := &adapter.AssignmentInfo{}.docs/p14-s2-audit.md,docs/p14-s2-design.md, this file.
Changed:
cmd/sparrow/main.go: the three demo sites (healthy / catch_up / rebuild) migrated from directadpt.OnAssignment(...)to the authority route via a sharedPublisher+ per-demoBridge. This surfaced and fixed the pre-existing "hidden operator path" smell where sparrow was minting epochs outside authority. The non-forgeability test now passes oncmd/sparrow/main.go.
Engine, adapter, transport, ops, and storage are unchanged.
How to verify S2 is still closed in a future session
Run these tests. All must pass. All must continue to pass:
go test ./core/authority/ -count=1
Specifically:
TestPublisher_Bind_MintsEpochAndEndpointVersionTestPublisher_Bind_RejectsDoubleBindTestPublisher_RefreshEndpoint_BumpsOnlyEndpointVersionTestPublisher_RefreshEndpoint_IdempotentOnSameAddrsTestPublisher_RefreshEndpoint_RejectsUnboundKeyTestPublisher_Reassign_BumpsEpochAndResetsEndpointVersionTestPublisher_Reassign_RejectsUnboundKeyTestPublisher_Validate_RejectsMissingFields(six sub-cases)TestPublisher_FanOut_TwoSubscribersOnSameKeyTestPublisher_IndependentUnsubscribe_OtherPeersUnaffectedTestPublisher_FanOut_SubscriberOnOtherVolumeDoesNotReceiveTestPublisher_LateSubscriber_ReceivesLastPublishedTestPublisher_Cancel_ClosesOnlyThisSubscriptionTestPublisher_DeliveryConvergesToLatestOnSlowConsumerTestPublisher_CancelDuringDeliveryDoesNotPanicTestPublisher_LateSubscriberReceivesLatestUnderConcurrentPublishTestPublisher_RunClosesLiveSubscriptionsOnExitTestPublisher_Run_DrivesDirectiveUntilCtxCancelTestPublisher_Run_LogsAndContinuesOnRejectedAskTestBridge_ForwardsToConsumerTestClosureTarget_SparrowReachesHealthyViaAuthorityRouteTestNonForgeability_NoAssignmentInfoMintingOutsideAuthorityTestNonForgeability_CatchesShortDeclBypassTestNonForgeability_CatchesVarDeclBypassTestNonForgeability_CatchesPointerShortDeclBypassTestNonForgeability_CatchesPointerVarDeclBypass
If the non-forgeability test starts failing because some new
production package wants to construct AssignmentInfo{Epoch: ...},
the correct response is to route that new site through the
authority publisher, not to add a path to the allowlist by reflex.