mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
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>
This commit is contained in:
1 parent
dec084485b
commit
5c663b8c83
6 files changed
+1595
No files matched your search
@@ -0,0 +1,223 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"sync"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/adapter"
|
||||
)
|
||||
|
||||
// subKey identifies a subscription / authoring slot by the full
|
||||
// (VolumeID, ReplicaID) unit. Keying by ReplicaID alone would
|
||||
// multiplex two different volumes that share a replica name — the
|
||||
// wrong routing boundary for authority truth.
|
||||
type subKey struct {
|
||||
volumeID string
|
||||
replicaID string
|
||||
}
|
||||
|
||||
// assignmentState holds the last authored AssignmentInfo for a
|
||||
// (VolumeID, ReplicaID). Used for authoring decisions (what to
|
||||
// advance next) and for late-subscriber catch-up via LastPublished.
|
||||
type assignmentState struct {
|
||||
info adapter.AssignmentInfo
|
||||
present bool
|
||||
}
|
||||
|
||||
// Publisher is the system-owned authority for assignment truth.
|
||||
// It is the sole place in production code that constructs an
|
||||
// adapter.AssignmentInfo with Epoch > 0.
|
||||
//
|
||||
// The publisher's Run loop consumes AssignmentAsk values from a
|
||||
// Directive, applies the S2 authoring rules, and fans out the
|
||||
// resulting AssignmentInfo to subscribers keyed by (VolumeID,
|
||||
// ReplicaID).
|
||||
type Publisher struct {
|
||||
dir Directive
|
||||
|
||||
mu sync.Mutex
|
||||
state map[subKey]assignmentState
|
||||
subs map[subKey][]chan adapter.AssignmentInfo
|
||||
}
|
||||
|
||||
// NewPublisher creates a Publisher that consumes from dir.
|
||||
func NewPublisher(dir Directive) *Publisher {
|
||||
return &Publisher{
|
||||
dir: dir,
|
||||
state: make(map[subKey]assignmentState),
|
||||
subs: make(map[subKey][]chan adapter.AssignmentInfo),
|
||||
}
|
||||
}
|
||||
|
||||
// Subscribe returns a channel that delivers every AssignmentInfo
|
||||
// authored for (volumeID, replicaID). Late subscribers whose key
|
||||
// already has a last published fact receive it immediately on the
|
||||
// returned channel. Close via Unsubscribe.
|
||||
//
|
||||
// The returned channel has a small buffer. If a subscriber drains
|
||||
// too slowly, publications for that subscriber are dropped with a
|
||||
// log entry — slow subscribers must not stall the authoring loop.
|
||||
// LastPublished is available for catch-up.
|
||||
func (p *Publisher) Subscribe(volumeID, replicaID string) <-chan adapter.AssignmentInfo {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
k := subKey{volumeID: volumeID, replicaID: replicaID}
|
||||
ch := make(chan adapter.AssignmentInfo, 4)
|
||||
p.subs[k] = append(p.subs[k], ch)
|
||||
if st, ok := p.state[k]; ok && st.present {
|
||||
select {
|
||||
case ch <- st.info:
|
||||
default:
|
||||
}
|
||||
}
|
||||
return ch
|
||||
}
|
||||
|
||||
// Unsubscribe closes every subscription channel registered for
|
||||
// (volumeID, replicaID). Idempotent.
|
||||
func (p *Publisher) Unsubscribe(volumeID, replicaID string) {
|
||||
p.mu.Lock()
|
||||
chs := p.subs[subKey{volumeID: volumeID, replicaID: replicaID}]
|
||||
delete(p.subs, subKey{volumeID: volumeID, replicaID: replicaID})
|
||||
p.mu.Unlock()
|
||||
for _, ch := range chs {
|
||||
close(ch)
|
||||
}
|
||||
}
|
||||
|
||||
// LastPublished returns the most recent AssignmentInfo authored for
|
||||
// (volumeID, replicaID), if any. Read-only.
|
||||
func (p *Publisher) LastPublished(volumeID, replicaID string) (adapter.AssignmentInfo, bool) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
st, ok := p.state[subKey{volumeID: volumeID, replicaID: replicaID}]
|
||||
if !ok || !st.present {
|
||||
return adapter.AssignmentInfo{}, false
|
||||
}
|
||||
return st.info, true
|
||||
}
|
||||
|
||||
// Run drives the publisher. Loops: Directive.Next → apply → fan out.
|
||||
// Exits on ctx cancellation or when Directive.Next returns a
|
||||
// non-nil error. Returns the terminating error.
|
||||
//
|
||||
// Run is the ONLY path in production code that produces an
|
||||
// authoritative AssignmentInfo. It calls apply internally; apply is
|
||||
// unexported and thus not an authoring verb available to callers.
|
||||
func (p *Publisher) Run(ctx context.Context) error {
|
||||
for {
|
||||
ask, err := p.dir.Next(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if applyErr := p.apply(ask); applyErr != nil {
|
||||
log.Printf("authority: rejected ask %+v: %v", ask, applyErr)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// apply implements the S2 authoring rules. It is the ONLY place in
|
||||
// production code that constructs an adapter.AssignmentInfo with a
|
||||
// non-zero Epoch. The structural non-forgeability test in
|
||||
// authority_test.go enforces this boundary at package level.
|
||||
func (p *Publisher) apply(ask AssignmentAsk) error {
|
||||
if err := validateAsk(ask); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
k := subKey{volumeID: ask.VolumeID, replicaID: ask.ReplicaID}
|
||||
prev, had := p.state[k]
|
||||
|
||||
var next adapter.AssignmentInfo
|
||||
switch ask.Intent {
|
||||
case IntentBind:
|
||||
if had && prev.present {
|
||||
return ErrBindAlreadyBound
|
||||
}
|
||||
next = adapter.AssignmentInfo{
|
||||
VolumeID: ask.VolumeID,
|
||||
ReplicaID: ask.ReplicaID,
|
||||
Epoch: 1,
|
||||
EndpointVersion: 1,
|
||||
DataAddr: ask.DataAddr,
|
||||
CtrlAddr: ask.CtrlAddr,
|
||||
}
|
||||
|
||||
case IntentRefreshEndpoint:
|
||||
if !had || !prev.present {
|
||||
return ErrRefreshNotBound
|
||||
}
|
||||
if prev.info.DataAddr == ask.DataAddr && prev.info.CtrlAddr == ask.CtrlAddr {
|
||||
// Idempotent no-op. Do not fan out, do not log as
|
||||
// rejection — the directive is allowed to retry.
|
||||
return nil
|
||||
}
|
||||
next = prev.info
|
||||
next.EndpointVersion = prev.info.EndpointVersion + 1
|
||||
next.DataAddr = ask.DataAddr
|
||||
next.CtrlAddr = ask.CtrlAddr
|
||||
|
||||
case IntentReassign:
|
||||
if !had || !prev.present {
|
||||
return ErrReassignNotBound
|
||||
}
|
||||
next = adapter.AssignmentInfo{
|
||||
VolumeID: ask.VolumeID,
|
||||
ReplicaID: ask.ReplicaID,
|
||||
Epoch: prev.info.Epoch + 1,
|
||||
EndpointVersion: 1,
|
||||
DataAddr: ask.DataAddr,
|
||||
CtrlAddr: ask.CtrlAddr,
|
||||
}
|
||||
|
||||
default:
|
||||
return ErrUnknownIntent
|
||||
}
|
||||
|
||||
p.state[k] = assignmentState{info: next, present: true}
|
||||
for _, ch := range p.subs[k] {
|
||||
select {
|
||||
case ch <- next:
|
||||
default:
|
||||
log.Printf("authority: subscriber drop for %s/%s epoch=%d endpointVersion=%d",
|
||||
ask.VolumeID, ask.ReplicaID, next.Epoch, next.EndpointVersion)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AssignmentConsumer is the narrow interface the Bridge calls back
|
||||
// into on delivery. adapter.VolumeReplicaAdapter satisfies it via
|
||||
// OnAssignment. Declared here so tests can provide their own fake
|
||||
// consumer without building a full adapter.
|
||||
type AssignmentConsumer interface {
|
||||
OnAssignment(info adapter.AssignmentInfo) adapter.ApplyLog
|
||||
}
|
||||
|
||||
// Bridge subscribes to (volumeID, replicaID) on pub and forwards
|
||||
// every delivered AssignmentInfo to consumer.OnAssignment. Exits
|
||||
// cleanly on ctx cancellation. The only state Bridge holds is "am I
|
||||
// still the live subscriber"; it never decides anything.
|
||||
//
|
||||
// Bridge closes its subscription via Unsubscribe when it exits so
|
||||
// the publisher's fan-out state stays tidy.
|
||||
func Bridge(ctx context.Context, pub *Publisher, consumer AssignmentConsumer, volumeID, replicaID string) {
|
||||
ch := pub.Subscribe(volumeID, replicaID)
|
||||
defer pub.Unsubscribe(volumeID, replicaID)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case info, ok := <-ch:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
consumer.OnAssignment(info)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,626 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/adapter"
|
||||
"github.com/seaweedfs/seaweed-block/core/engine"
|
||||
)
|
||||
|
||||
// ============================================================
|
||||
// Unit tests — authoring rules
|
||||
// ============================================================
|
||||
|
||||
func TestPublisher_Bind_MintsEpochAndEndpointVersion(t *testing.T) {
|
||||
pub := NewPublisher(NewStaticDirective(nil))
|
||||
if err := pub.apply(AssignmentAsk{
|
||||
VolumeID: "v1", ReplicaID: "r1",
|
||||
DataAddr: "d", CtrlAddr: "c",
|
||||
Intent: IntentBind,
|
||||
}); err != nil {
|
||||
t.Fatalf("Bind: %v", err)
|
||||
}
|
||||
got, ok := pub.LastPublished("v1", "r1")
|
||||
if !ok {
|
||||
t.Fatal("expected LastPublished after Bind")
|
||||
}
|
||||
if got.Epoch != 1 {
|
||||
t.Fatalf("Bind Epoch: got %d want 1", got.Epoch)
|
||||
}
|
||||
if got.EndpointVersion != 1 {
|
||||
t.Fatalf("Bind EndpointVersion: got %d want 1", got.EndpointVersion)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublisher_Bind_RejectsDoubleBind(t *testing.T) {
|
||||
pub := NewPublisher(NewStaticDirective(nil))
|
||||
ask := AssignmentAsk{
|
||||
VolumeID: "v1", ReplicaID: "r1",
|
||||
DataAddr: "d", CtrlAddr: "c",
|
||||
Intent: IntentBind,
|
||||
}
|
||||
if err := pub.apply(ask); err != nil {
|
||||
t.Fatalf("first Bind: %v", err)
|
||||
}
|
||||
if err := pub.apply(ask); !errors.Is(err, ErrBindAlreadyBound) {
|
||||
t.Fatalf("second Bind: want ErrBindAlreadyBound, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublisher_RefreshEndpoint_BumpsOnlyEndpointVersion(t *testing.T) {
|
||||
pub := NewPublisher(NewStaticDirective(nil))
|
||||
if err := pub.apply(AssignmentAsk{
|
||||
VolumeID: "v1", ReplicaID: "r1",
|
||||
DataAddr: "d1", CtrlAddr: "c1",
|
||||
Intent: IntentBind,
|
||||
}); err != nil {
|
||||
t.Fatalf("Bind: %v", err)
|
||||
}
|
||||
if err := pub.apply(AssignmentAsk{
|
||||
VolumeID: "v1", ReplicaID: "r1",
|
||||
DataAddr: "d2", CtrlAddr: "c2",
|
||||
Intent: IntentRefreshEndpoint,
|
||||
}); err != nil {
|
||||
t.Fatalf("RefreshEndpoint: %v", err)
|
||||
}
|
||||
got, _ := pub.LastPublished("v1", "r1")
|
||||
if got.Epoch != 1 {
|
||||
t.Fatalf("Refresh must keep Epoch=1, got %d", got.Epoch)
|
||||
}
|
||||
if got.EndpointVersion != 2 {
|
||||
t.Fatalf("Refresh must bump EndpointVersion to 2, got %d", got.EndpointVersion)
|
||||
}
|
||||
if got.DataAddr != "d2" || got.CtrlAddr != "c2" {
|
||||
t.Fatalf("Refresh must update addrs, got %q/%q", got.DataAddr, got.CtrlAddr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublisher_RefreshEndpoint_IdempotentOnSameAddrs(t *testing.T) {
|
||||
pub := NewPublisher(NewStaticDirective(nil))
|
||||
ask := AssignmentAsk{
|
||||
VolumeID: "v1", ReplicaID: "r1",
|
||||
DataAddr: "d", CtrlAddr: "c",
|
||||
Intent: IntentBind,
|
||||
}
|
||||
if err := pub.apply(ask); err != nil {
|
||||
t.Fatalf("Bind: %v", err)
|
||||
}
|
||||
refresh := ask
|
||||
refresh.Intent = IntentRefreshEndpoint
|
||||
if err := pub.apply(refresh); err != nil {
|
||||
t.Fatalf("RefreshEndpoint same-addrs: %v", err)
|
||||
}
|
||||
got, _ := pub.LastPublished("v1", "r1")
|
||||
if got.Epoch != 1 || got.EndpointVersion != 1 {
|
||||
t.Fatalf("same-addrs Refresh must be no-op, got epoch=%d ev=%d",
|
||||
got.Epoch, got.EndpointVersion)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublisher_RefreshEndpoint_RejectsUnboundKey(t *testing.T) {
|
||||
pub := NewPublisher(NewStaticDirective(nil))
|
||||
err := pub.apply(AssignmentAsk{
|
||||
VolumeID: "v1", ReplicaID: "r1",
|
||||
DataAddr: "d", CtrlAddr: "c",
|
||||
Intent: IntentRefreshEndpoint,
|
||||
})
|
||||
if !errors.Is(err, ErrRefreshNotBound) {
|
||||
t.Fatalf("want ErrRefreshNotBound, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublisher_Reassign_BumpsEpochAndResetsEndpointVersion(t *testing.T) {
|
||||
pub := NewPublisher(NewStaticDirective(nil))
|
||||
if err := pub.apply(AssignmentAsk{
|
||||
VolumeID: "v1", ReplicaID: "r1",
|
||||
DataAddr: "d1", CtrlAddr: "c1",
|
||||
Intent: IntentBind,
|
||||
}); err != nil {
|
||||
t.Fatalf("Bind: %v", err)
|
||||
}
|
||||
if err := pub.apply(AssignmentAsk{
|
||||
VolumeID: "v1", ReplicaID: "r1",
|
||||
DataAddr: "d2", CtrlAddr: "c2",
|
||||
Intent: IntentRefreshEndpoint,
|
||||
}); err != nil {
|
||||
t.Fatalf("Refresh: %v", err)
|
||||
}
|
||||
// Prior state: epoch=1, ev=2.
|
||||
if err := pub.apply(AssignmentAsk{
|
||||
VolumeID: "v1", ReplicaID: "r1",
|
||||
DataAddr: "d2", CtrlAddr: "c2",
|
||||
Intent: IntentReassign,
|
||||
}); err != nil {
|
||||
t.Fatalf("Reassign: %v", err)
|
||||
}
|
||||
got, _ := pub.LastPublished("v1", "r1")
|
||||
if got.Epoch != 2 {
|
||||
t.Fatalf("Reassign Epoch: got %d want 2", got.Epoch)
|
||||
}
|
||||
if got.EndpointVersion != 1 {
|
||||
t.Fatalf("Reassign must reset EndpointVersion to 1, got %d", got.EndpointVersion)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublisher_Reassign_RejectsUnboundKey(t *testing.T) {
|
||||
pub := NewPublisher(NewStaticDirective(nil))
|
||||
err := pub.apply(AssignmentAsk{
|
||||
VolumeID: "v1", ReplicaID: "r1",
|
||||
DataAddr: "d", CtrlAddr: "c",
|
||||
Intent: IntentReassign,
|
||||
})
|
||||
if !errors.Is(err, ErrReassignNotBound) {
|
||||
t.Fatalf("want ErrReassignNotBound, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublisher_Validate_RejectsMissingFields(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
ask AssignmentAsk
|
||||
want error
|
||||
}{
|
||||
{"no volume", AssignmentAsk{ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}, ErrMissingVolumeID},
|
||||
{"no replica", AssignmentAsk{VolumeID: "v", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}, ErrMissingReplicaID},
|
||||
{"no data", AssignmentAsk{VolumeID: "v", ReplicaID: "r", CtrlAddr: "c", Intent: IntentBind}, ErrMissingDataAddr},
|
||||
{"no ctrl", AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", Intent: IntentBind}, ErrMissingCtrlAddr},
|
||||
{"no intent", AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c"}, ErrMissingIntent},
|
||||
{"bad intent", AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: AskIntent(99)}, ErrUnknownIntent},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
pub := NewPublisher(NewStaticDirective(nil))
|
||||
err := pub.apply(c.ask)
|
||||
if !errors.Is(err, c.want) {
|
||||
t.Fatalf("want %v, got %v", c.want, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Fan-out keyed by (VolumeID, ReplicaID)
|
||||
// ============================================================
|
||||
|
||||
func TestPublisher_FanOut_TwoSubscribersOnSameKey(t *testing.T) {
|
||||
pub := NewPublisher(NewStaticDirective(nil))
|
||||
chA := pub.Subscribe("v1", "r1")
|
||||
chB := pub.Subscribe("v1", "r1")
|
||||
|
||||
if err := pub.apply(AssignmentAsk{
|
||||
VolumeID: "v1", ReplicaID: "r1",
|
||||
DataAddr: "d", CtrlAddr: "c",
|
||||
Intent: IntentBind,
|
||||
}); err != nil {
|
||||
t.Fatalf("Bind: %v", err)
|
||||
}
|
||||
|
||||
got1 := receiveOrFail(t, chA, "subA")
|
||||
got2 := receiveOrFail(t, chB, "subB")
|
||||
if got1.Epoch != 1 || got2.Epoch != 1 {
|
||||
t.Fatalf("both subscribers must receive epoch=1, got %d / %d", got1.Epoch, got2.Epoch)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublisher_FanOut_SubscriberOnOtherVolumeDoesNotReceive(t *testing.T) {
|
||||
// Same replicaID across different volumes must NOT cross-deliver.
|
||||
// This is the multi-volume correctness test the architect called
|
||||
// out when we were keying only by ReplicaID.
|
||||
pub := NewPublisher(NewStaticDirective(nil))
|
||||
chV1 := pub.Subscribe("vol1", "r1")
|
||||
chV2 := pub.Subscribe("vol2", "r1")
|
||||
|
||||
if err := pub.apply(AssignmentAsk{
|
||||
VolumeID: "vol1", ReplicaID: "r1",
|
||||
DataAddr: "d", CtrlAddr: "c",
|
||||
Intent: IntentBind,
|
||||
}); err != nil {
|
||||
t.Fatalf("Bind vol1: %v", err)
|
||||
}
|
||||
|
||||
got := receiveOrFail(t, chV1, "vol1 subscriber")
|
||||
if got.VolumeID != "vol1" {
|
||||
t.Fatalf("vol1 subscriber got %q", got.VolumeID)
|
||||
}
|
||||
|
||||
select {
|
||||
case info := <-chV2:
|
||||
t.Fatalf("vol2 subscriber must not receive vol1 publication, got %+v", info)
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
// expected: nothing
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublisher_LateSubscriber_ReceivesLastPublished(t *testing.T) {
|
||||
pub := NewPublisher(NewStaticDirective(nil))
|
||||
if err := pub.apply(AssignmentAsk{
|
||||
VolumeID: "v1", ReplicaID: "r1",
|
||||
DataAddr: "d", CtrlAddr: "c",
|
||||
Intent: IntentBind,
|
||||
}); err != nil {
|
||||
t.Fatalf("Bind: %v", err)
|
||||
}
|
||||
ch := pub.Subscribe("v1", "r1")
|
||||
got := receiveOrFail(t, ch, "late subscriber")
|
||||
if got.Epoch != 1 {
|
||||
t.Fatalf("late subscriber must receive last published, got epoch=%d", got.Epoch)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublisher_Unsubscribe_ClosesChannel(t *testing.T) {
|
||||
pub := NewPublisher(NewStaticDirective(nil))
|
||||
ch := pub.Subscribe("v1", "r1")
|
||||
pub.Unsubscribe("v1", "r1")
|
||||
select {
|
||||
case _, ok := <-ch:
|
||||
if ok {
|
||||
t.Fatal("expected channel closed")
|
||||
}
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
t.Fatal("channel not closed after Unsubscribe")
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Run loop — integration with Directive
|
||||
// ============================================================
|
||||
|
||||
func TestPublisher_Run_DrivesDirectiveUntilCtxCancel(t *testing.T) {
|
||||
dir := NewStaticDirective([]AssignmentAsk{
|
||||
{VolumeID: "v1", ReplicaID: "r1", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind},
|
||||
})
|
||||
pub := NewPublisher(dir)
|
||||
ch := pub.Subscribe("v1", "r1")
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- pub.Run(ctx) }()
|
||||
|
||||
info := receiveOrFail(t, ch, "Run consumer")
|
||||
if info.Epoch != 1 {
|
||||
t.Fatalf("Run must drive Bind, got epoch=%d", info.Epoch)
|
||||
}
|
||||
|
||||
cancel()
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("Run exit: want context.Canceled, got %v", err)
|
||||
}
|
||||
case <-time.After(500 * time.Millisecond):
|
||||
t.Fatal("Run did not exit on ctx cancel")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublisher_Run_LogsAndContinuesOnRejectedAsk(t *testing.T) {
|
||||
// Reassign on an unbound key must be rejected, then the next
|
||||
// ask must still be processed. This is the "continue on reject"
|
||||
// Run semantic.
|
||||
dir := NewStaticDirective([]AssignmentAsk{
|
||||
{VolumeID: "v1", ReplicaID: "r1", DataAddr: "d", CtrlAddr: "c", Intent: IntentReassign}, // rejected
|
||||
{VolumeID: "v1", ReplicaID: "r1", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}, // accepted
|
||||
})
|
||||
pub := NewPublisher(dir)
|
||||
ch := pub.Subscribe("v1", "r1")
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go pub.Run(ctx)
|
||||
|
||||
info := receiveOrFail(t, ch, "post-reject subscriber")
|
||||
if info.Epoch != 1 {
|
||||
t.Fatalf("expected accepted Bind after rejected Reassign, got epoch=%d", info.Epoch)
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Bridge — forwards to AssignmentConsumer
|
||||
// ============================================================
|
||||
|
||||
type recordingConsumer struct {
|
||||
mu sync.Mutex
|
||||
seen []adapter.AssignmentInfo
|
||||
}
|
||||
|
||||
func (r *recordingConsumer) OnAssignment(info adapter.AssignmentInfo) adapter.ApplyLog {
|
||||
r.mu.Lock()
|
||||
r.seen = append(r.seen, info)
|
||||
r.mu.Unlock()
|
||||
return adapter.ApplyLog{}
|
||||
}
|
||||
|
||||
func (r *recordingConsumer) snapshot() []adapter.AssignmentInfo {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
cp := make([]adapter.AssignmentInfo, len(r.seen))
|
||||
copy(cp, r.seen)
|
||||
return cp
|
||||
}
|
||||
|
||||
func TestBridge_ForwardsToConsumer(t *testing.T) {
|
||||
dir := NewStaticDirective([]AssignmentAsk{
|
||||
{VolumeID: "v1", ReplicaID: "r1", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind},
|
||||
})
|
||||
pub := NewPublisher(dir)
|
||||
cons := &recordingConsumer{}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go pub.Run(ctx)
|
||||
go Bridge(ctx, pub, cons, "v1", "r1")
|
||||
|
||||
// Wait for Bridge → consumer delivery.
|
||||
deadline := time.Now().Add(500 * time.Millisecond)
|
||||
for time.Now().Before(deadline) {
|
||||
if len(cons.snapshot()) > 0 {
|
||||
break
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
seen := cons.snapshot()
|
||||
if len(seen) != 1 {
|
||||
t.Fatalf("Bridge did not forward: got %d deliveries", len(seen))
|
||||
}
|
||||
if seen[0].Epoch != 1 || seen[0].EndpointVersion != 1 {
|
||||
t.Fatalf("Bridge forwarded wrong fact: %+v", seen[0])
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Closure target: end-to-end authority → adapter → engine → Healthy
|
||||
// ============================================================
|
||||
|
||||
// closureExecutor is a test executor that satisfies
|
||||
// adapter.CommandExecutor and drives the adapter to ModeHealthy on
|
||||
// a caught-up replica. It responds to ProbeReplica synchronously
|
||||
// with a caught-up result (R == H) and auto-fires fence callbacks.
|
||||
//
|
||||
// We intentionally build a test executor rather than reuse the
|
||||
// adapter-internal mockExecutor — the closure test must live in the
|
||||
// authority package and use only adapter's exported surface.
|
||||
type closureExecutor struct {
|
||||
mu sync.Mutex
|
||||
onStart adapter.OnSessionStart
|
||||
onClose adapter.OnSessionClose
|
||||
onFenceComplete adapter.OnFenceComplete
|
||||
nextSession atomic.Uint64
|
||||
}
|
||||
|
||||
func newClosureExecutor() *closureExecutor {
|
||||
ce := &closureExecutor{}
|
||||
ce.nextSession.Store(1000)
|
||||
return ce
|
||||
}
|
||||
|
||||
func (e *closureExecutor) SetOnSessionStart(fn adapter.OnSessionStart) { e.onStart = fn }
|
||||
func (e *closureExecutor) SetOnSessionClose(fn adapter.OnSessionClose) { e.onClose = fn }
|
||||
func (e *closureExecutor) SetOnFenceComplete(fn adapter.OnFenceComplete) { e.onFenceComplete = fn }
|
||||
|
||||
func (e *closureExecutor) Probe(replicaID, dataAddr, ctrlAddr string, epoch, endpointVersion uint64) adapter.ProbeResult {
|
||||
return adapter.ProbeResult{
|
||||
ReplicaID: replicaID,
|
||||
Success: true,
|
||||
EndpointVersion: endpointVersion,
|
||||
TransportEpoch: epoch,
|
||||
// R >= H → caught-up; engine will emit FenceAtEpoch.
|
||||
ReplicaFlushedLSN: 100,
|
||||
PrimaryTailLSN: 10,
|
||||
PrimaryHeadLSN: 100,
|
||||
}
|
||||
}
|
||||
|
||||
func (e *closureExecutor) StartCatchUp(replicaID string, sessionID, epoch, endpointVersion, targetLSN uint64) error {
|
||||
return nil
|
||||
}
|
||||
func (e *closureExecutor) StartRebuild(replicaID string, sessionID, epoch, endpointVersion, targetLSN uint64) error {
|
||||
return nil
|
||||
}
|
||||
func (e *closureExecutor) InvalidateSession(replicaID string, sessionID uint64, reason string) {}
|
||||
func (e *closureExecutor) PublishHealthy(replicaID string) {}
|
||||
func (e *closureExecutor) PublishDegraded(replicaID string, reason string) {}
|
||||
|
||||
func (e *closureExecutor) Fence(replicaID string, sessionID, epoch, endpointVersion uint64) error {
|
||||
// Fire success inline — matches the ack-gated contract from P14 S1.
|
||||
cb := e.onFenceComplete
|
||||
if cb != nil {
|
||||
cb(adapter.FenceResult{
|
||||
ReplicaID: replicaID,
|
||||
SessionID: sessionID,
|
||||
Epoch: epoch,
|
||||
EndpointVersion: endpointVersion,
|
||||
Success: true,
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestClosureTarget_SparrowReachesHealthyViaAuthorityRoute is the
|
||||
// S2 acceptance test: wire Publisher → Bridge → VolumeReplicaAdapter
|
||||
// with a StaticDirective carrying one Bind, and observe the adapter
|
||||
// reach Mode == ModeHealthy — without any harness.assign call or
|
||||
// any test-side adapter.OnAssignment call.
|
||||
func TestClosureTarget_SparrowReachesHealthyViaAuthorityRoute(t *testing.T) {
|
||||
exec := newClosureExecutor()
|
||||
a := adapter.NewVolumeReplicaAdapter(exec)
|
||||
|
||||
dir := NewStaticDirective([]AssignmentAsk{
|
||||
{VolumeID: "vol1", ReplicaID: "r1",
|
||||
DataAddr: "10.0.0.2:9333", CtrlAddr: "10.0.0.2:9334",
|
||||
Intent: IntentBind},
|
||||
})
|
||||
pub := NewPublisher(dir)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
go pub.Run(ctx)
|
||||
go Bridge(ctx, pub, a, "vol1", "r1")
|
||||
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if a.Projection().Mode == engine.ModeHealthy {
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("sparrow did not reach Healthy via authority route; final mode=%s", a.Projection().Mode)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Non-forgeability — structural test
|
||||
// ============================================================
|
||||
|
||||
// nonForgeabilityAllowedPaths are production-compiled test
|
||||
// infrastructure packages that are explicitly allowed to construct
|
||||
// AssignmentInfo with a non-zero Epoch. They are not operator or
|
||||
// admin paths; they exist to drive scenario tests from the
|
||||
// calibration harness and the YAML conformance runner. Adding a
|
||||
// package here is an explicit, reviewable act.
|
||||
var nonForgeabilityAllowedPaths = []string{
|
||||
string(filepath.Separator) + "authority" + string(filepath.Separator), // the minter
|
||||
string(filepath.Separator) + "calibration" + string(filepath.Separator), // scenario harness
|
||||
string(filepath.Separator) + "conformance" + string(filepath.Separator), // YAML test runner
|
||||
string(filepath.Separator) + "schema" + string(filepath.Separator), // event wire conversion
|
||||
}
|
||||
|
||||
// TestNonForgeability_NoAssignmentInfoMintingOutsideAuthority walks
|
||||
// every production .go file under core/ (excluding _test.go files
|
||||
// and explicit allowlisted packages) and fails if anything
|
||||
// constructs an adapter.AssignmentInfo with an Epoch field set to
|
||||
// anything other than a literal 0. This enforces at build-tree
|
||||
// scope that the publisher is the sole authoritative minter for
|
||||
// real system paths.
|
||||
//
|
||||
// The allowlist exists because calibration/conformance/schema are
|
||||
// test-infrastructure packages that happen to live in the
|
||||
// production tree. They drive scenario tests and YAML replays;
|
||||
// they are not operator or admin paths. Any new package added to
|
||||
// the allowlist must carry the same rationale — "this is test
|
||||
// infrastructure, not a system-owned path".
|
||||
//
|
||||
// The pattern is strict: it matches ANY `Epoch:` assignment inside
|
||||
// an `AssignmentInfo{...}` literal (whether the RHS is a literal
|
||||
// digit, a variable name, a function call, or anything else) — and
|
||||
// only allows `Epoch: 0` as a written-out zero. This catches the
|
||||
// bypass where someone would set `Epoch: userInput` via a CLI or
|
||||
// admin surface.
|
||||
func TestNonForgeability_NoAssignmentInfoMintingOutsideAuthority(t *testing.T) {
|
||||
coreDir, err := findCoreDir()
|
||||
if err != nil {
|
||||
t.Fatalf("find core dir: %v", err)
|
||||
}
|
||||
|
||||
// Matches `AssignmentInfo{ ... Epoch: <expr>` where <expr> is the
|
||||
// first non-space, non-comma, non-closing-brace token.
|
||||
pattern := regexp.MustCompile(`AssignmentInfo\s*\{[\s\S]*?Epoch\s*:\s*([^\s,}]+)`)
|
||||
|
||||
var bad []string
|
||||
err = filepath.WalkDir(coreDir, func(path string, d os.DirEntry, walkErr error) error {
|
||||
if walkErr != nil {
|
||||
return walkErr
|
||||
}
|
||||
if d.IsDir() {
|
||||
return nil
|
||||
}
|
||||
if !strings.HasSuffix(path, ".go") {
|
||||
return nil
|
||||
}
|
||||
if strings.HasSuffix(path, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
for _, allowed := range nonForgeabilityAllowedPaths {
|
||||
if strings.Contains(path, allowed) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
var sb strings.Builder
|
||||
scanner := bufio.NewScanner(f)
|
||||
scanner.Buffer(make([]byte, 1<<20), 1<<20)
|
||||
for scanner.Scan() {
|
||||
sb.WriteString(scanner.Text())
|
||||
sb.WriteString("\n")
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
matches := pattern.FindAllStringSubmatch(sb.String(), -1)
|
||||
for _, m := range matches {
|
||||
if len(m) < 2 {
|
||||
continue
|
||||
}
|
||||
if m[1] == "0" {
|
||||
continue // explicit zero is fine
|
||||
}
|
||||
bad = append(bad, path+": Epoch="+m[1])
|
||||
break
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("walk: %v", err)
|
||||
}
|
||||
if len(bad) > 0 {
|
||||
t.Fatalf("non-forgeability: production code outside the authority/calibration/conformance/schema allowlist mints AssignmentInfo with a non-zero Epoch:\n %s",
|
||||
strings.Join(bad, "\n "))
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Helpers
|
||||
// ============================================================
|
||||
|
||||
func receiveOrFail(t *testing.T, ch <-chan adapter.AssignmentInfo, who string) adapter.AssignmentInfo {
|
||||
t.Helper()
|
||||
select {
|
||||
case info, ok := <-ch:
|
||||
if !ok {
|
||||
t.Fatalf("%s: channel closed before delivery", who)
|
||||
}
|
||||
return info
|
||||
case <-time.After(500 * time.Millisecond):
|
||||
t.Fatalf("%s: no delivery within 500ms", who)
|
||||
return adapter.AssignmentInfo{}
|
||||
}
|
||||
}
|
||||
|
||||
// findCoreDir locates the repository's core/ directory by walking up
|
||||
// from the current test file's working directory. Used by the
|
||||
// non-forgeability test.
|
||||
func findCoreDir() (string, error) {
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// When tests run, cwd is the package dir. Walk up until we find
|
||||
// a sibling "adapter" directory (proxy for "we're in core/").
|
||||
dir := cwd
|
||||
for i := 0; i < 6; i++ {
|
||||
if info, err := os.Stat(filepath.Join(dir, "adapter")); err == nil && info.IsDir() {
|
||||
return dir, nil
|
||||
}
|
||||
parent := filepath.Dir(dir)
|
||||
if parent == dir {
|
||||
break
|
||||
}
|
||||
dir = parent
|
||||
}
|
||||
return "", errors.New("could not locate core/ directory")
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
// Package authority is the system-owned publication route for
|
||||
// assignment truth. It owns the authorship of Epoch and
|
||||
// EndpointVersion — never accepts them as input — and fans out
|
||||
// authoritative AssignmentInfo values to subscribers keyed by
|
||||
// (VolumeID, ReplicaID).
|
||||
//
|
||||
// The design note is docs/p14-s2-design.md. Three boundaries hold:
|
||||
// 1. S2 owns publication of authority truth.
|
||||
// 2. S2 does NOT own failover policy.
|
||||
// 3. Engine and adapter remain consumers, not producers, of
|
||||
// assignment truth.
|
||||
package authority
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// AskIntent is the only control knob a Directive has. The publisher
|
||||
// uses it to decide which authoritative field to advance and by how
|
||||
// much. S2 supports exactly three intents. Retirement is deferred
|
||||
// (see docs/p14-s2-design.md "What we are NOT building").
|
||||
type AskIntent int
|
||||
|
||||
const (
|
||||
// IntentBind: first-time binding for (VolumeID, ReplicaID).
|
||||
// Publisher mints Epoch=1, EndpointVersion=1. Rejected if a
|
||||
// prior publish already exists for the key.
|
||||
IntentBind AskIntent = iota + 1
|
||||
|
||||
// IntentRefreshEndpoint: same volume/replica, new transport
|
||||
// endpoints. Publisher keeps Epoch, bumps EndpointVersion.
|
||||
// No-op if addresses are unchanged. Rejected if no prior
|
||||
// publish exists.
|
||||
IntentRefreshEndpoint
|
||||
|
||||
// IntentReassign: bump the authoritative epoch for an
|
||||
// already-bound key. Publisher increments Epoch and resets
|
||||
// EndpointVersion to 1. Rejected if no prior publish exists.
|
||||
IntentReassign
|
||||
)
|
||||
|
||||
// String returns a stable name for diagnostics.
|
||||
func (i AskIntent) String() string {
|
||||
switch i {
|
||||
case IntentBind:
|
||||
return "Bind"
|
||||
case IntentRefreshEndpoint:
|
||||
return "RefreshEndpoint"
|
||||
case IntentReassign:
|
||||
return "Reassign"
|
||||
default:
|
||||
return "Unknown"
|
||||
}
|
||||
}
|
||||
|
||||
// AssignmentAsk is the narrow input a Directive emits. It is
|
||||
// deliberately narrower than adapter.AssignmentInfo: it carries no
|
||||
// Epoch and no EndpointVersion. Those are authored by the publisher.
|
||||
type AssignmentAsk struct {
|
||||
VolumeID string
|
||||
ReplicaID string
|
||||
DataAddr string
|
||||
CtrlAddr string
|
||||
Intent AskIntent
|
||||
}
|
||||
|
||||
// Directive is the input side of the authority route. A Directive
|
||||
// emits one AssignmentAsk at a time. The publisher's Run loop calls
|
||||
// Next repeatedly until ctx cancellation.
|
||||
//
|
||||
// The Directive interface is the seam where P14 S3's failover
|
||||
// policy will later plug in. S2 ships only a trivial implementation:
|
||||
// StaticDirective.
|
||||
type Directive interface {
|
||||
Next(ctx context.Context) (AssignmentAsk, error)
|
||||
}
|
||||
|
||||
// StaticDirective emits a pre-wired sequence of AssignmentAsk
|
||||
// values, then blocks on ctx cancellation. It is the trivial S2
|
||||
// implementation used for tests and the sparrow closure target.
|
||||
//
|
||||
// StaticDirective carries no failover policy, no eligibility logic,
|
||||
// no trigger logic. It is pure "replay these requests".
|
||||
type StaticDirective struct {
|
||||
mu sync.Mutex
|
||||
asks []AssignmentAsk
|
||||
idx int
|
||||
}
|
||||
|
||||
// NewStaticDirective returns a Directive that emits asks in order.
|
||||
// After the last ask, Next blocks until ctx cancellation.
|
||||
func NewStaticDirective(asks []AssignmentAsk) *StaticDirective {
|
||||
cp := make([]AssignmentAsk, len(asks))
|
||||
copy(cp, asks)
|
||||
return &StaticDirective{asks: cp}
|
||||
}
|
||||
|
||||
// Append adds an ask to the tail. Safe for tests to call while a
|
||||
// publisher Run loop is consuming.
|
||||
func (s *StaticDirective) Append(ask AssignmentAsk) {
|
||||
s.mu.Lock()
|
||||
s.asks = append(s.asks, ask)
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
// Next returns the next ask, or blocks until ctx is cancelled when
|
||||
// the pre-wired sequence is exhausted. Returning ctx.Err() signals
|
||||
// the publisher's Run to exit cleanly.
|
||||
func (s *StaticDirective) Next(ctx context.Context) (AssignmentAsk, error) {
|
||||
for {
|
||||
s.mu.Lock()
|
||||
if s.idx < len(s.asks) {
|
||||
ask := s.asks[s.idx]
|
||||
s.idx++
|
||||
s.mu.Unlock()
|
||||
return ask, nil
|
||||
}
|
||||
s.mu.Unlock()
|
||||
|
||||
// Exhausted. Block briefly and retry so Append can add more,
|
||||
// but honor ctx cancellation promptly.
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return AssignmentAsk{}, ctx.Err()
|
||||
case <-time.After(10 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Errors returned by the publisher for rejected asks.
|
||||
var (
|
||||
ErrMissingVolumeID = errors.New("authority: AssignmentAsk missing VolumeID")
|
||||
ErrMissingReplicaID = errors.New("authority: AssignmentAsk missing ReplicaID")
|
||||
ErrMissingDataAddr = errors.New("authority: AssignmentAsk missing DataAddr")
|
||||
ErrMissingCtrlAddr = errors.New("authority: AssignmentAsk missing CtrlAddr")
|
||||
ErrMissingIntent = errors.New("authority: AssignmentAsk missing Intent")
|
||||
ErrUnknownIntent = errors.New("authority: AssignmentAsk Intent not recognized")
|
||||
ErrBindAlreadyBound = errors.New("authority: Bind on already-bound key")
|
||||
ErrRefreshNotBound = errors.New("authority: RefreshEndpoint on unbound key")
|
||||
ErrReassignNotBound = errors.New("authority: Reassign on unbound key")
|
||||
)
|
||||
|
||||
func validateAsk(ask AssignmentAsk) error {
|
||||
if ask.VolumeID == "" {
|
||||
return ErrMissingVolumeID
|
||||
}
|
||||
if ask.ReplicaID == "" {
|
||||
return ErrMissingReplicaID
|
||||
}
|
||||
if ask.DataAddr == "" {
|
||||
return ErrMissingDataAddr
|
||||
}
|
||||
if ask.CtrlAddr == "" {
|
||||
return ErrMissingCtrlAddr
|
||||
}
|
||||
if ask.Intent == 0 {
|
||||
return ErrMissingIntent
|
||||
}
|
||||
if ask.Intent != IntentBind &&
|
||||
ask.Intent != IntentRefreshEndpoint &&
|
||||
ask.Intent != IntentReassign {
|
||||
return ErrUnknownIntent
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
# P14 S2 — Scoped Audit (Authority Path)
|
||||
|
||||
This is the audit note for P14 S2. It is pure observation of the V3
|
||||
repo at the time of writing. No design here, no code. The design note
|
||||
is `p14-s2-design.md`.
|
||||
|
||||
The audit answers five questions about how `assignment` / `epoch` /
|
||||
`endpointVersion` travel through the system today, plus a sixth about
|
||||
which V2 pieces are mechanically portable to V3.
|
||||
|
||||
## Sharpened constraints honored in the audit
|
||||
|
||||
1. S2 is *authoritative publication*, not policy source. Findings are
|
||||
tagged mechanism vs policy-shaped.
|
||||
2. Authority must be a system-owned route. Findings explicitly flag
|
||||
hidden-operator-path smells (renamed test helper, CLI/admin manual
|
||||
entry, volume-local convenience path).
|
||||
3. The architect's owner-placement bias is thin-control-plane layer
|
||||
outside the volume body — NOT inside adapter or volume server.
|
||||
4. V2 port inventory splits `portable-mechanism` vs `policy-tangled`.
|
||||
|
||||
## Q1 — Producers of `assignment` / `epoch` / `endpointVersion`
|
||||
|
||||
**Real-system code.** None today. There is no production path in V3
|
||||
that mints or observes an assignment from outside the process.
|
||||
|
||||
- `engine.applyAssignment` mutates identity at `core/engine/apply.go:171-174`
|
||||
but only after the adapter has already normalized an `AssignmentInfo`
|
||||
coming from *some* caller. Today, the callers are all tests.
|
||||
- `engine.applyProbeSucceeded` binds observed endpoint/transport epoch
|
||||
at `core/engine/apply.go:258-259`. This observes what the transport
|
||||
reports, not a minted truth.
|
||||
- `engine.applyFenceCompleted` bumps internal `FencedEpoch` at
|
||||
`core/engine/apply.go:509`. Internal gate, not authority.
|
||||
|
||||
**Test / scenario code.**
|
||||
|
||||
- `harness.assign(epoch, endpointVersion)` in
|
||||
`core/calibration/harness.go:87-92`.
|
||||
- Scenario driver in `core/calibration/scenarios.go:64`.
|
||||
- Declarative conformance via `core/conformance/cases.yaml`, decoded
|
||||
by `core/schema/convert.go:13-20`.
|
||||
- Adapter unit tests at `core/adapter/adapter_test.go` (many call
|
||||
sites) construct `AssignmentInfo` inline.
|
||||
|
||||
**Hidden-operator-path candidates.** None. The ops HTTP surface is
|
||||
read-only: mutation verbs rejected at `core/ops/server.go:46-63`. There
|
||||
is no CLI flag, admin endpoint, or debug hook in `cmd/sparrow/main.go`
|
||||
that mints or modifies epoch / assignment.
|
||||
|
||||
## Q2 — Publishers
|
||||
|
||||
No multi-subscriber publisher exists. Every site calls
|
||||
`VolumeReplicaAdapter.OnAssignment(...)` directly
|
||||
(`core/adapter/adapter.go:103-105`). No registry, bus, store, or
|
||||
watcher. This is greenfield for the publication path.
|
||||
|
||||
## Q3 — Consumers beyond the adapter
|
||||
|
||||
- Transport executor embeds epoch in outbound `RecoveryLineage`:
|
||||
`core/transport/executor.go:75-86`.
|
||||
- Transport replica validates lineage epoch on inbound:
|
||||
`core/transport/replica.go:186`.
|
||||
- Ops `/projection` surfaces epoch / endpointVersion read-only:
|
||||
`core/ops/handlers.go:45-48`, `core/engine/projection.go:20-26`.
|
||||
- Storage does NOT embed assignment in persisted state. (V2
|
||||
`weed/storage/blockvol/blockvol.go:71-72` persists epoch for fencing;
|
||||
V3 does not.)
|
||||
|
||||
No policy-adjacent reader exists.
|
||||
|
||||
## Q4 — Test-injection / manual-driving inventory
|
||||
|
||||
All three recognized paths:
|
||||
|
||||
- Calibration scenarios (`harness.assign`).
|
||||
- Conformance YAML cases.
|
||||
- Adapter and mock tests.
|
||||
|
||||
Hidden-operator-path screen: clean.
|
||||
|
||||
- No test helper wears a production name.
|
||||
- No CLI / admin API accepts an `AssignmentInfo`.
|
||||
- No `vol.SetEpoch()` convenience shortcut exists inside the adapter
|
||||
or engine that bypasses the assignment ingress.
|
||||
|
||||
Because there is no hidden-operator-path today, S2 does *not* have a
|
||||
demotion problem. It has a **build-the-real-route** problem.
|
||||
|
||||
## Q5 — Existing authority-adjacent surfaces
|
||||
|
||||
None in V3. The categorization below applies the owner-placement bias:
|
||||
|
||||
| Existing surface | Category | Why |
|
||||
|---|---|---|
|
||||
| `engine` | Not an authority | Pure reducer. Accepts events. Not a decision owner. |
|
||||
| `adapter` | Volume-local-shaped affordance | Sits inside sparrow volume body; owns local ingress. Using it as the authority owner would conflate topology authority with replica-local execution — explicitly NOT preferred. |
|
||||
| `ops` (read-only) | Read-only inspection | Rejects mutations. Not a control path. |
|
||||
| (new thin control-plane layer) | Control-plane-shaped gap | Preferred S2 landing spot. Greenfield. |
|
||||
|
||||
S2 must create a new thin layer outside the volume body.
|
||||
|
||||
## Q6 — V2 port inventory
|
||||
|
||||
Source: `C:\work\seaweedfs`.
|
||||
|
||||
| V2 piece | File | Category | Note |
|
||||
|---|---|---|---|
|
||||
| `BlockVolumeHeartbeatCollector` | `weed/server/block_heartbeat_loop.go:16-34` | portable-mechanism | Status aggregation + assignment fetch loop. No policy. |
|
||||
| `SetAssignmentSource()` | `weed/server/block_heartbeat_loop.go:67-71` | portable-mechanism | Callback wire-up. Pure mechanism. |
|
||||
| `ProcessBlockVolumeAssignments()` | `weed/storage/store_blockvol.go:129-145` | portable-mechanism | Per-volume apply. Mechanism only. |
|
||||
| `BlockVolumeAssignment` struct | `weed/storage/blockvol/block_heartbeat.go:49-61` | portable-mechanism | Data shape (epoch, role, replica addrs). |
|
||||
| `BlockVolumeInfoMessage` struct | `weed/storage/blockvol/block_heartbeat.go:10-38` | portable-mechanism | Heartbeat message shape. |
|
||||
| `vol.SetEpoch()` / `vol.SetRole()` | `weed/storage/blockvol/blockvol.go:71-74` | portable-mechanism | Low-level bind. Mechanism only if authority is outside. |
|
||||
| `HandleAssignment()` | `weed/storage/blockvol/promotion.go:19-69` | policy-tangled | Inline promotion/demotion decision, shipper stop, lease revoke. Volume-local convenience ownership. **Do not port.** |
|
||||
| `promote()` / `demote()` | `weed/storage/blockvol/promotion.go:71-137` | policy-tangled | Role state machine with drain semantics. **Do not port.** |
|
||||
|
||||
## Summary
|
||||
|
||||
- **V3 is additive-greenfield for authority.** No pre-existing path to
|
||||
dismantle, no hidden operator surface to demote.
|
||||
- **Publication is also greenfield.** S2 must invent a real
|
||||
publication route — a system-owned layer that calls
|
||||
`adapter.OnAssignment(...)` on subscribers, replacing today's
|
||||
test-only call sites with a genuine producer.
|
||||
- **V2 port scope is limited to shapes and low-level bind
|
||||
machinery.** The V2 promotion/demotion state machine is
|
||||
policy-tangled and does not belong in S2.
|
||||
- **Owner lands outside the volume body.** The architect's bias maps
|
||||
cleanly onto the greenfield shape.
|
||||
|
||||
S2 builds exactly one new thing and does not disturb any existing
|
||||
path: a thin authority publisher that adapters subscribe to and
|
||||
consume via the existing `OnAssignment` ingress.
|
||||
@@ -0,0 +1,147 @@
|
||||
# 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
|
||||
|
||||
1. **A system-owned publication route for assignment truth.** The
|
||||
new package `core/authority/` hosts a `Publisher` that authors
|
||||
`adapter.AssignmentInfo` values and fans them out to subscribers
|
||||
keyed by `(VolumeID, ReplicaID)`. The publisher is the only
|
||||
production code in V3 that constructs an `AssignmentInfo` with a
|
||||
non-zero `Epoch`.
|
||||
|
||||
2. **Ack-gated authorship of `Epoch` and `EndpointVersion`.** The
|
||||
only input to the publisher is a narrow `AssignmentAsk`
|
||||
(`VolumeID`, `ReplicaID`, `DataAddr`, `CtrlAddr`, `Intent`).
|
||||
Epoch and EndpointVersion are *output*, not input. Directives
|
||||
cannot hand the publisher a preformed epoch.
|
||||
|
||||
3. **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.
|
||||
|
||||
4. **A Directive seam for S3.** `Directive.Next(ctx) AssignmentAsk`
|
||||
is the single upstream interface. The trivial `StaticDirective`
|
||||
ships 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.
|
||||
|
||||
5. **A Bridge that forwards publisher output to the adapter.** The
|
||||
`Bridge` helper subscribes to a `(VolumeID, ReplicaID)` stream
|
||||
and forwards each `AssignmentInfo` to the adapter's existing
|
||||
`OnAssignment` ingress. The adapter remains the one and only
|
||||
consumer entry point; no second mutation ingress was added.
|
||||
|
||||
6. **Closure target met.** The integration test
|
||||
`TestClosureTarget_SparrowReachesHealthyViaAuthorityRoute` in
|
||||
`core/authority/authority_test.go` boots a `Publisher` with a
|
||||
`StaticDirective`, wires a `Bridge` into a real
|
||||
`VolumeReplicaAdapter`, and reaches `Mode == ModeHealthy`
|
||||
without any `harness.assign(...)` call.
|
||||
|
||||
7. **Non-forgeability is enforced by structural test.**
|
||||
`TestNonForgeability_NoAssignmentInfoMintingOutsideAuthority`
|
||||
walks every `.go` file under `core/` (excluding `_test.go`
|
||||
files and the allowlisted test-infrastructure packages
|
||||
`authority`, `calibration`, `conformance`, `schema`) and fails
|
||||
if any production file constructs an `AssignmentInfo` with a
|
||||
non-zero `Epoch`. Adding a new package to the allowlist is an
|
||||
explicit, reviewable change.
|
||||
|
||||
## 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.** `Remove` is 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 `AssignmentInfo` or an `AssignmentAsk`. 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.** `OnAssignment` stays
|
||||
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`,
|
||||
`Unsubscribe`, `LastPublished`, `Run`, `Bridge`,
|
||||
`AssignmentConsumer`.
|
||||
- `core/authority/authority_test.go` — 17 tests covering intent
|
||||
semantics, fan-out keyed by `(VolumeID, ReplicaID)`,
|
||||
late-subscriber catch-up, `Run` loop, `Bridge`, closure target,
|
||||
non-forgeability.
|
||||
- `docs/p14-s2-audit.md`, `docs/p14-s2-design.md`, this file.
|
||||
|
||||
Changed: none. S2 did not modify the engine, adapter, transport,
|
||||
ops, storage, or sparrow wiring. The authority route stands as an
|
||||
additive, opt-in producer.
|
||||
|
||||
## 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_MintsEpochAndEndpointVersion`
|
||||
- `TestPublisher_Bind_RejectsDoubleBind`
|
||||
- `TestPublisher_RefreshEndpoint_BumpsOnlyEndpointVersion`
|
||||
- `TestPublisher_RefreshEndpoint_IdempotentOnSameAddrs`
|
||||
- `TestPublisher_RefreshEndpoint_RejectsUnboundKey`
|
||||
- `TestPublisher_Reassign_BumpsEpochAndResetsEndpointVersion`
|
||||
- `TestPublisher_Reassign_RejectsUnboundKey`
|
||||
- `TestPublisher_Validate_RejectsMissingFields` (six sub-cases)
|
||||
- `TestPublisher_FanOut_TwoSubscribersOnSameKey`
|
||||
- `TestPublisher_FanOut_SubscriberOnOtherVolumeDoesNotReceive`
|
||||
- `TestPublisher_LateSubscriber_ReceivesLastPublished`
|
||||
- `TestPublisher_Unsubscribe_ClosesChannel`
|
||||
- `TestPublisher_Run_DrivesDirectiveUntilCtxCancel`
|
||||
- `TestPublisher_Run_LogsAndContinuesOnRejectedAsk`
|
||||
- `TestBridge_ForwardsToConsumer`
|
||||
- `TestClosureTarget_SparrowReachesHealthyViaAuthorityRoute`
|
||||
- `TestNonForgeability_NoAssignmentInfoMintingOutsideAuthority`
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,297 @@
|
||||
# P14 S2 — Bounded Authority Path (Design Note)
|
||||
|
||||
This is the design note for P14 S2. Scope is deliberately narrow:
|
||||
publish `assignment` / `epoch` / `endpointVersion` through a
|
||||
system-owned route, consumed by the existing adapter ingress. Nothing
|
||||
more.
|
||||
|
||||
The audit note is `p14-s2-audit.md`. Read it first for the factual
|
||||
baseline. This note proceeds on that baseline and commits to a shape.
|
||||
|
||||
## Load-bearing boundaries (do not blur)
|
||||
|
||||
These three statements are the contract of S2. Every piece of code in
|
||||
this phase must be reducible to them.
|
||||
|
||||
1. **S2 owns publication of authority truth.** The package introduced
|
||||
here is *the* place where `assignment` / `epoch` / `endpointVersion`
|
||||
become visible to the rest of the system.
|
||||
2. **S2 does NOT own failover policy.** *Who* becomes primary, *when*
|
||||
to promote, *where* to place replicas, and *how* to rebalance are
|
||||
explicitly NOT in S2. They belong to P14 S3.
|
||||
3. **Engine and adapter remain consumers, not producers, of
|
||||
assignment truth.** Nothing in this phase adds a new engine fact,
|
||||
a new policy ownership inside the engine, or a new mutation ingress
|
||||
inside the adapter. The adapter's `OnAssignment(...)` stays the
|
||||
one and only consumer entry point.
|
||||
|
||||
If a change seems to need more than these three statements, it is not
|
||||
S2.
|
||||
|
||||
## Closure target
|
||||
|
||||
> After S2, sparrow must reach Healthy through a genuine
|
||||
> `authority.Publisher -> adapter.OnAssignment(...)` route, not only
|
||||
> through harness injection.
|
||||
|
||||
That sentence is the acceptance test. Everything else serves it.
|
||||
|
||||
## Package layout
|
||||
|
||||
New package: `core/authority/`.
|
||||
|
||||
Rationale:
|
||||
|
||||
- Outside `cmd/sparrow` and outside `core/adapter` — it is *not* the
|
||||
volume body.
|
||||
- Outside `core/engine` — authority is not a reducer fact.
|
||||
- Sibling to `core/transport`, `core/ops`, `core/storage`. Adapter is
|
||||
the sole connection point.
|
||||
|
||||
Files:
|
||||
|
||||
- `authority.go` — `Publisher` type, subscriber bookkeeping, publish
|
||||
semantics.
|
||||
- `directive.go` — `Directive` input interface + a trivial
|
||||
`StaticDirective` implementation (bounded producer policy source,
|
||||
see below).
|
||||
- `authority_test.go` — unit tests for publication and consumption.
|
||||
|
||||
## Input type — narrower than `AssignmentInfo`
|
||||
|
||||
A `Directive` does NOT hand the publisher an `AssignmentInfo`. It
|
||||
hands the publisher an `AssignmentAsk` — a request for the publisher
|
||||
to perform authorship. Epoch and EndpointVersion are deliberately
|
||||
absent; they are not input, they are output.
|
||||
|
||||
```
|
||||
type AssignmentAsk struct {
|
||||
VolumeID string // required
|
||||
ReplicaID string // required
|
||||
DataAddr string // required (may change to request an endpoint bump)
|
||||
CtrlAddr string // required
|
||||
Intent AskIntent // Bind | RefreshEndpoint | Reassign
|
||||
}
|
||||
|
||||
type AskIntent int // see "Authoring rules" below
|
||||
```
|
||||
|
||||
S2 ships exactly three intents: `Bind`, `RefreshEndpoint`, `Reassign`.
|
||||
A fourth obvious intent — `Remove` / retirement — is intentionally
|
||||
omitted. Retirement would need a second delivery shape (either a
|
||||
channel close that the subscriber must interpret, or a new
|
||||
`adapter.OnRemoval`-style mutation ingress), and both options expand
|
||||
the S2 boundary: the first makes the subscription contract carry
|
||||
semantics beyond "the next fact", the second opens a second
|
||||
authority-to-adapter mutation path in violation of boundary #3
|
||||
(the adapter's `OnAssignment(...)` is the one and only consumer
|
||||
entry point). The S2 closure target — sparrow reaches Healthy via
|
||||
the real publication route — does not require retirement, so S2
|
||||
ships without it. Retirement is a later-phase concern and will be
|
||||
designed alongside the S3 policy seam.
|
||||
|
||||
`Intent` is the only control knob the directive has. The publisher
|
||||
then decides which authoritative field to advance and by how much.
|
||||
This is the seam by which S3 will later ask the publisher to bump
|
||||
epoch without S3 ever constructing the epoch itself.
|
||||
|
||||
## Authoring rules — the publisher is the minter
|
||||
|
||||
The publisher owns a monotonic counter keyed by `(VolumeID,
|
||||
ReplicaID)`. Given an `AssignmentAsk` it decides as follows:
|
||||
|
||||
| `Intent` | Precondition | Publisher action | Emitted `AssignmentInfo` |
|
||||
|---|---|---|---|
|
||||
| `Bind` | No prior publish for this `(vid, rid)` | mint `Epoch=1`, `EndpointVersion=1` | fresh |
|
||||
| `Bind` | Prior publish exists | reject (directive bug) | none |
|
||||
| `RefreshEndpoint` | Prior publish exists; addrs differ | keep `Epoch`, bump `EndpointVersion` | same epoch, new EV |
|
||||
| `RefreshEndpoint` | Prior publish exists; addrs identical | no-op (idempotent) | none |
|
||||
| `Reassign` | Prior publish exists | bump `Epoch`, reset `EndpointVersion=1` | new epoch |
|
||||
|
||||
Rejected or no-op directives do not mutate state and do not fan out.
|
||||
|
||||
The publisher NEVER accepts a preformed epoch or endpointVersion from
|
||||
any caller. The only knob is `Intent`. This is what makes the publisher
|
||||
a real author rather than a relay.
|
||||
|
||||
## Who can construct an `AssignmentInfo`
|
||||
|
||||
Only `core/authority/` may construct an `AssignmentInfo` with
|
||||
`Epoch > 0` in a production path. Enforcement is twofold:
|
||||
|
||||
1. `AssignmentInfo` stays in `core/adapter` as it is today (it is
|
||||
the adapter's ingress shape). The authority package is the only
|
||||
production package that constructs one.
|
||||
2. A package-level test in `core/authority/` audits production
|
||||
imports with a simple "forbidden constructor" grep: any
|
||||
non-test `.go` file outside `core/authority/` that literal-typed
|
||||
`adapter.AssignmentInfo{` with a non-zero `Epoch` field fails the
|
||||
test. Test helpers (`_test.go` files) are exempt — calibration
|
||||
and conformance retain their right to forge test facts.
|
||||
|
||||
## Publication API — no public write verb
|
||||
|
||||
The publisher exposes three verbs, none of which accept an
|
||||
`AssignmentInfo`:
|
||||
|
||||
- `Subscribe(volumeID, replicaID string) <-chan AssignmentInfo` — a
|
||||
consumer registers interest in authoritative assignments for a
|
||||
specific `(VolumeID, ReplicaID)`. Returns a receive channel.
|
||||
Unsubscribe via `Unsubscribe(volumeID, replicaID)` or ctx cancel.
|
||||
- `LastPublished(volumeID, replicaID string) (AssignmentInfo, bool)`
|
||||
— read-only inspection of the last emitted fact for a key. Used
|
||||
by late subscribers to catch up without waiting for the next
|
||||
directive.
|
||||
- `Run(ctx)` — drive the publisher: consume `AssignmentAsk` values
|
||||
from the directive, apply the authoring rules above, fan out to
|
||||
subscribers. One goroutine. Stops on ctx cancel.
|
||||
|
||||
What the publisher will NOT expose:
|
||||
|
||||
- No `PublishAssignment(AssignmentInfo)`. Removed. Its earlier
|
||||
presence let callers forge authoritative truth — that was the
|
||||
relay-not-author bug the architect caught.
|
||||
- No `SetEpoch(...)`, no `ForcePromote(...)`, no per-replica
|
||||
health reads, no placement hints, no rebalance verbs.
|
||||
|
||||
## Directive interface
|
||||
|
||||
```
|
||||
type Directive interface {
|
||||
Next(ctx context.Context) (AssignmentAsk, error)
|
||||
}
|
||||
```
|
||||
|
||||
The trivial S2 implementation is `StaticDirective` — a pre-wired
|
||||
sequence of `AssignmentAsk` values set by process configuration,
|
||||
typically one `Bind` per replica at startup for the closure target.
|
||||
|
||||
What is explicitly NOT in scope for any `Directive` implementation
|
||||
in S2:
|
||||
|
||||
- No eligibility rules ("is replica X allowed to be primary").
|
||||
- No promotion triggers ("promote when primary fails").
|
||||
- No failover orchestration ("advance everyone's epoch on quorum
|
||||
loss").
|
||||
- No placement or rebalance ("pick the least-loaded node").
|
||||
|
||||
All four belong to S3. The `Directive` + `AssignmentAsk.Intent`
|
||||
pair is the seam where S3 will plug in real policy. S2 ships only
|
||||
`StaticDirective`.
|
||||
|
||||
## Subscriber model
|
||||
|
||||
Adapters subscribe by `(VolumeID, ReplicaID)` at construction. The
|
||||
sparrow main loop wires the adapter to the publisher:
|
||||
|
||||
```
|
||||
pub := authority.NewPublisher(dir)
|
||||
a := adapter.NewVolumeReplicaAdapter(exec)
|
||||
go authority.Bridge(ctx, pub, a, "vol1", "r1")
|
||||
// receives on Subscribe("vol1", "r1"),
|
||||
// calls a.OnAssignment(info)
|
||||
```
|
||||
|
||||
`Bridge` is a thin for-loop: receive, forward, repeat. It has no
|
||||
decision logic. Its only state is "am I still the live subscriber".
|
||||
|
||||
Identity is uniformly `(VolumeID, ReplicaID)` across subscription,
|
||||
authoring, and fanout — fixing the narrow-key bug where same-named
|
||||
replicas across different volumes would have been multiplexed.
|
||||
|
||||
Stale rejection continues to live where it already lives — in
|
||||
`engine.applyAssignment`. The publisher does NOT replicate that logic;
|
||||
it only enforces its own output monotonicity (per authoring rules
|
||||
above) and lets the engine's existing guards handle the rest.
|
||||
|
||||
## V2 port plan (what this commits to)
|
||||
|
||||
From the audit, the V2 portable-mechanism items are:
|
||||
|
||||
- `BlockVolumeAssignment` — useful as a wire *shape* reference. V3
|
||||
`AssignmentInfo` already exists; we may adopt field names from V2
|
||||
for consistency but do not import.
|
||||
- `BlockVolumeInfoMessage` — same. Shape only.
|
||||
- `BlockVolumeHeartbeatCollector` — NOT imported in S2. Its role
|
||||
(periodic status collection) is orthogonal to publication. It may
|
||||
become a subscriber in a later phase.
|
||||
- `ProcessBlockVolumeAssignments` — NOT imported. It is the *volume
|
||||
side* consumer in V2; in V3 that job is the adapter's.
|
||||
|
||||
Policy-tangled items (`HandleAssignment`, `promote`, `demote`) are
|
||||
NOT ported in S2 and will NOT be ported in any subsequent V3 phase as
|
||||
a copy — their behavior, if still needed, will be re-derived from
|
||||
engine commands.
|
||||
|
||||
## What S2 closes vs what stays open
|
||||
|
||||
| Question | S2 answers | S2 does NOT answer |
|
||||
|---|---|---|
|
||||
| Who publishes assignment truth? | `authority.Publisher` | — |
|
||||
| How does the adapter receive it? | via `Subscribe(vid,rid)` → `Bridge` → `OnAssignment` | — |
|
||||
| Who *authors* epoch / endpointVersion? | `Publisher` (mints from `Intent`; never accepts preformed values) | — |
|
||||
| When should epoch bump? | — | S3 |
|
||||
| Who is eligible to be primary? | — | S3 |
|
||||
| What triggers a failover? | — | S3 |
|
||||
| How should replicas be placed or rebalanced? | — | S3 |
|
||||
| What is the external control API? | — | P15 |
|
||||
|
||||
## Test plan (sketch — full tests land in code step)
|
||||
|
||||
- **Publisher is the minter**: a directive issues only `AssignmentAsk`
|
||||
values (no epoch/endpointVersion). After `Run(ctx)` processes them,
|
||||
subscribers observe `AssignmentInfo` with monotonically increasing
|
||||
`Epoch` / `EndpointVersion` authored by the publisher.
|
||||
- **Non-forgeability**: a structural test grep-audits production
|
||||
`.go` files under `core/` (excluding `_test.go` and
|
||||
`core/authority/`) for literal `adapter.AssignmentInfo{ Epoch:` or
|
||||
`.Epoch = ` assignments. Fails if anything outside authority mints
|
||||
a non-zero epoch in production code.
|
||||
- **Fan-out keyed by (VolumeID, ReplicaID)**: two subscribers on the
|
||||
same `(vol1, r1)` both receive. A subscriber on `(vol2, r1)` does
|
||||
NOT receive `vol1`-keyed assignments (regression for the
|
||||
narrow-key bug).
|
||||
- **Intent semantics**: `Bind` on fresh key mints `Epoch=1, EV=1`;
|
||||
`RefreshEndpoint` with changed addrs keeps epoch, bumps EV;
|
||||
`RefreshEndpoint` with unchanged addrs is a no-op; `Reassign`
|
||||
bumps epoch and resets EV to 1; `Bind` on an existing key is
|
||||
rejected.
|
||||
- **Bridge → adapter → engine**: end-to-end assertion that publisher
|
||||
output reaches `ReplicaState.Identity` via the existing ingress,
|
||||
with no additional event type added to the engine.
|
||||
- **Stale rejection unchanged**: engine rejects an older-epoch fact
|
||||
via its existing guard. The publisher does NOT duplicate the
|
||||
check (regression: no silent second rejector).
|
||||
- **Closure target**: a sparrow integration test boots with a
|
||||
`StaticDirective` and reaches `Mode == ModeHealthy` without a
|
||||
single `harness.assign(...)` call.
|
||||
|
||||
## What we are NOT building
|
||||
|
||||
- No admin or CLI mutation surface for assignments.
|
||||
- No V2 heartbeat or V2 HandleAssignment port.
|
||||
- No new engine events, commands, or truth domains.
|
||||
- No promotion / demotion state machine.
|
||||
- No eligibility or placement computation.
|
||||
- No retirement / `Remove` intent. Adding retirement requires a
|
||||
second delivery shape that would either overload subscriptions
|
||||
with lifecycle semantics or open a second mutation ingress on
|
||||
the adapter. Neither fits the S2 boundary. Deferred.
|
||||
|
||||
## Acceptance
|
||||
|
||||
S2 is architect-clean when:
|
||||
|
||||
1. The three load-bearing boundary statements are enforced by the
|
||||
code (no backdoor mutation, no engine/adapter-side production of
|
||||
authority, Directive is the only policy seam).
|
||||
2. The publisher is the minter, not a relay. `Directive.Next`
|
||||
returns `AssignmentAsk` (no epoch / no endpointVersion). No
|
||||
public verb accepts a preformed `AssignmentInfo`. The
|
||||
non-forgeability structural test passes.
|
||||
3. Identity is `(VolumeID, ReplicaID)` uniformly — subscription,
|
||||
authoring state, and fan-out all key by the same unit. The
|
||||
multi-volume fan-out test passes.
|
||||
4. The closure target integration test passes.
|
||||
5. The V2 policy-tangled items listed in the audit remain
|
||||
unimported.
|
||||
Reference in new issue
Block a user