Commit Graph
3 Commits
Author SHA1 Message Date
wzcheng99andClaude Opus 4.7 63ea717a75 P14 S2 fix²: close-safe delivery, catch-up ordering, pointer-form bypass
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>
2026-04-18 22:29:47 -07:00
wzcheng99andClaude Opus 4.7 3d53563ca9 P14 S2 fix: per-subscription cancel, lossless-latest delivery, AST non-forgeability
Addresses three architect findings on the first S2 drop:

1. High: Unsubscribe(vid, rid) was key-wide — one Bridge exiting
   silently closed channels for all other peers on the same
   (VolumeID, ReplicaID). Replaced with per-subscription cancel:
   Subscribe now returns (ch, cancel func). Each cancel closes only
   its own subscription. Publisher owns a nextSubID counter and
   tracks subscriptions as []*subscription per key. Cancel is
   idempotent and safe against concurrent Run-exit teardown via a
   "whoever finds it closes it" protocol.

   Regression test: TestPublisher_IndependentUnsubscribe_OtherPeersUnaffected.

2. High: silent drop on full subscriber buffer could leave the
   adapter on stale authority truth until an unrelated later ask
   happened — unacceptable for an authority route. Per-subscription
   channels are capacity 1 with overwrite-latest semantics: on full,
   the publisher drains the stale pending value and retries send,
   so the subscriber always reads the LATEST authoritative state
   next. Intermediate states may be coalesced (correct for authority
   truth; the engine cares about current identity, not interstitial
   history).

   Regression test: TestPublisher_DeliveryConvergesToLatestOnSlowConsumer.

3. Medium: the non-forgeability structural test was a regex-based
   grep over core/ only, and caught only composite-literal Epoch
   assignments. Rewritten as an AST-based walker that (a) covers
   the whole repo (cmd/ and future production packages included,
   not just core/) and (b) catches both composite-literal mints
   with non-zero Epoch/EndpointVersion AND local variable
   declarations of type AssignmentInfo — the classic bypass shape
   for deferred mutation: `var x AssignmentInfo; x.Epoch = input`.

   The stronger check surfaced three pre-existing hidden operator
   paths in cmd/sparrow/main.go that minted AssignmentInfo with
   hard-coded epochs 1/2/3 directly. All three demo sites are now
   routed through a shared authority.Publisher: healthy demo issues
   IntentBind, catch_up and rebuild demos issue IntentReassign.
   No sparrow demo code constructs AssignmentInfo directly anymore.

Other:
  * Run now closes every live subscription channel on exit, so
    Bridges observe end-of-stream cleanly. Tested by
    TestPublisher_RunClosesLiveSubscriptionsOnExit.
  * Publisher.apply() releases the publisher lock before fan-out,
    preventing a slow consumer from stalling the authoring loop.

Docs updated:
  * docs/p14-s2-design.md — Publication API now documents
    per-subscription cancel, removes the stale Unsubscribe(vid,rid)
    verb, adds the "lossless for current fact" delivery semantic.
  * docs/p14-s2-closure.md — test list updated (20 tests), Changed
    section records the sparrow migration.

No changes to engine, adapter, transport, ops, storage.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 21:20:09 -07:00
wzcheng99andClaude Opus 4.7 5c663b8c83 P14 S2: bounded authority publication route for assignment truth
Introduces the core/authority/ package — the system-owned publication
route where Epoch and EndpointVersion are authored, not relayed. The
publisher is the only production code that constructs an
adapter.AssignmentInfo with a non-zero Epoch.

Contract boundaries (load-bearing):
  * S2 owns publication of authority truth.
  * S2 does NOT own failover policy.
  * Engine and adapter remain consumers, not producers.

Design:
  * Publisher.Run consumes AssignmentAsk values from an injected
    Directive and fans out AssignmentInfo to subscribers keyed by
    (VolumeID, ReplicaID) — not by ReplicaID alone, which would
    multiplex different volumes that share a replica name.
  * AssignmentAsk carries no Epoch and no EndpointVersion. The
    publisher mints both from the intent enum (Bind | RefreshEndpoint
    | Reassign). Retirement (Remove) is deliberately deferred.
  * No public verb accepts a preformed AssignmentInfo. The former
    PublishAssignment relay verb was removed from the design before
    code — the publisher is a minter, not a pass-through.
  * Directive is the seam where P14 S3's failover policy will later
    plug in without reaching into the publisher. S2 ships only
    StaticDirective.
  * Bridge forwards publisher output to adapter.OnAssignment — the
    adapter remains the one and only consumer entry point; no second
    mutation ingress was added.

Tests (core/authority/authority_test.go):
  * Intent semantics: Bind mints epoch=1 ev=1; RefreshEndpoint keeps
    epoch and bumps ev (no-op on unchanged addrs); Reassign bumps
    epoch and resets ev=1; each invalid precondition is rejected.
  * Fan-out keyed by (VolumeID, ReplicaID): two subs on the same key
    both receive; a sub on a different volume for the same replica
    name does NOT receive — regression for the narrow-key bug.
  * Late-subscriber catch-up via LastPublished.
  * Run loop drives Directive until ctx cancel; rejected asks are
    logged and loop continues.
  * Bridge forwards to AssignmentConsumer.
  * Closure target integration test: Publisher -> Bridge -> real
    VolumeReplicaAdapter reaches Mode == ModeHealthy without any
    harness.assign call.
  * Non-forgeability structural test walks core/ and fails if any
    production file outside an explicit allowlist (authority /
    calibration / conformance / schema) constructs an AssignmentInfo
    with a non-zero Epoch.

Docs:
  * docs/p14-s2-audit.md — scoped audit of existing producers /
    publishers / consumers / hidden-operator-path smells / V2 port
    candidates.
  * docs/p14-s2-design.md — bounded design: load-bearing boundaries,
    closure target, package layout, AssignmentAsk shape, authoring
    rules table, publication API, Bridge model, V2 port plan,
    explicit non-goals and acceptance criteria.
  * docs/p14-s2-closure.md — what S2 closed, what stayed out, S2/S3
    boundary table, verification recipe.

No changes to engine, adapter, transport, ops, storage, or sparrow
wiring. The authority route is additive.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 17:13:12 -07:00