feat: run stateless release commands under coordination
Add fenced coordinator authority clients and trusted-store/fleet API adapters with monotonic safety deadlines, follower backoff and explicit tick/shutdown hooks. This is partial Task 2c progress. Coordinated command execution, agent lifecycle wiring, durable rollout IDs and termination mutations remain required before the feature can land.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
approved_stateless_replicas_copy_test.go+1 −1docs/superpowers/notes/census-proposal-stateless-replicas-1.md+1 −1internal/activator/coordinator.go+236 −0internal/activator/coordinator_test.go+240 −0internal/host/replicacoordinator.go+128 −0internal/host/replicacoordinator_test.go+159 −0internal/provision/stateless_replicas_census_test.go+4 −0internal/provision/testdata/plan14-root-reads-stateless-replicas-1.tsv+3 −1
CI failed — run details
Intent
<task-notification> <task-id>btb4c3bfb</task-id> <tool-use-id>toolu_019GaJskqMpGvADFGAe8Ut7s</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/412bbef6-9468-4e8d-b9fe-5343bad21de8/tasks/btb4c3bfb.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 2b implementer" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 16.4 g CO₂e (1,937,658 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on stateless-replicas-1-runtime, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/approved_stateless_replicas_copy_test.go b/approved_stateless_replicas_copy_test.go| index 52a9268ab..cff3fa2e9 100644 |
| --- a/approved_stateless_replicas_copy_test.go |
| +++ b/approved_stateless_replicas_copy_test.go |
| @@ -9,7 +9,7 @@ import ( |
| const statelessReplicaCopyDeck = "docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md" |
| -var statelessReplicaBuiltCopy = []string{"SR-1-C01", "SR-1-C02", "SR-1-C03", "SR-1-C04", "SR-1-C12", "SR-1-C09", "SR-1-C10", "SR-1-C13"} |
| +var statelessReplicaBuiltCopy = []string{"SR-1-C01", "SR-1-C02", "SR-1-C03", "SR-1-C04", "SR-1-C05", "SR-1-C12", "SR-1-C09", "SR-1-C10", "SR-1-C13"} |
| func statelessReplicaCopyRows(t *testing.T) []copyRow { |
| t.Helper() |
diff --git a/docs/superpowers/notes/census-proposal-stateless-replicas-1.md b/docs/superpowers/notes/census-proposal-stateless-replicas-1.md| index c1efa9a07..1ad3b372a 100644 |
| --- a/docs/superpowers/notes/census-proposal-stateless-replicas-1.md |
| +++ b/docs/superpowers/notes/census-proposal-stateless-replicas-1.md |
| @@ -7,7 +7,7 @@ Ruling `census-ruling-stateless-replicas-1`. The independent reviewer approves o |
| | `cli.go` `runShip` | body | unchanged (2) | Carry --stateless into binary/API and rootfs ship options; same two read sites, no new read. | |
| | `ship_check.go` `rootfsCheck.runArgs` | body | unchanged (2) | Stateless local checks mount only the run volume and omit the database mount; same probe read, no new read. | |
| -Envelopes re-pinned: `.`, `internal/provision`, `internal/release`, `internal/replicas`. |
| +Envelopes re-pinned: `.`, `internal/activator`, `internal/host`, `internal/provision`, `internal/release`, `internal/replicas`. |
| Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
diff --git a/internal/activator/coordinator.go b/internal/activator/coordinator.go| new file mode 100644 |
| index 000000000..6108529fd |
| --- /dev/null |
| +++ b/internal/activator/coordinator.go |
| @@ -0,0 +1,236 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/replicas" |
| +) |
| + |
| +var ErrReplicaReleaseUnknown = errors.New("the release command's result is unknown, so the deploy stopped and the previous build keeps serving. deploy again to retry the command") |
| + |
| +type CoordinatorClient interface { |
| + Acquire(context.Context, replicas.Identity) (replicas.Authority, error) |
| + ReleaseState(context.Context, replicas.Identity, replicas.ReleaseChange) (replicas.Deploy, error) |
| +} |
| + |
| +type CoordinatorExchange func(context.Context, replicas.Identity, replicas.CoordinatorChange) (replicas.CoordinatorReply, error) |
| +type ReleaseExchange func(context.Context, replicas.Identity, replicas.ReleaseChange) (replicas.Deploy, error) |
| + |
| +type CoordinationClient struct { |
| + mu sync.Mutex |
| + opMu sync.Mutex |
| + box, boot string |
| + exchange CoordinatorExchange |
| + release ReleaseExchange |
| + now func() time.Time |
| + closed bool |
| + held map[replicas.Identity]*coordinatorAuthority |
| + retry map[replicas.Identity]time.Time |
| +} |
| + |
| +func NewCoordinatorClient(box, boot string, exchange CoordinatorExchange, release ReleaseExchange) *CoordinationClient { |
| + return &CoordinationClient{box: box, boot: boot, exchange: exchange, release: release, now: time.Now, held: make(map[replicas.Identity]*coordinatorAuthority), retry: make(map[replicas.Identity]time.Time)} |
| +} |
| + |
| +// Tick is called by the agent's existing tick. It renews only held terms. |
| +func (c *CoordinationClient) Tick(ctx context.Context) { |
| + c.opMu.Lock() |
| + defer c.opMu.Unlock() |
| + c.mu.Lock() |
| + pending := make([]*coordinatorAuthority, 0, len(c.held)) |
| + if !c.closed { |
| + for id, a := range c.held { |
| + if a.errLocked() != nil { |
| + delete(c.held, id) |
| + continue |
| + } |
| + if !c.now().Before(a.renewAt) { |
| + pending = append(pending, a) |
| + } |
| + } |
| + } |
| + c.mu.Unlock() |
| + for _, a := range pending { |
| + c.mu.Lock() |
| + if c.closed || a.errLocked() != nil { |
| + c.mu.Unlock() |
| + continue |
| + } |
| + oldUntil := a.until |
| + c.mu.Unlock() |
| + rctx, cancel := context.WithDeadline(ctx, oldUntil) |
| + _, until, err := c.request(rctx, a.id, "renew", a.term) |
| + cancel() |
| + c.mu.Lock() |
| + if err != nil || c.closed || a.errLocked() != nil { |
| + a.loseLocked() |
| + delete(c.held, a.id) |
| + } else { |
| + a.until = until |
| + a.renewAt = c.now().Add(replicas.CoordinatorRenewAfter) |
| + } |
| + c.mu.Unlock() |
| + } |
| +} |
| + |
| +func (c *CoordinationClient) request(ctx context.Context, id replicas.Identity, op, term string) (replicas.CoordinatorReply, time.Time, error) { |
| + if c.box == "" || c.boot == "" || c.exchange == nil { |
| + return replicas.CoordinatorReply{}, time.Time{}, replicas.ErrFenced |
| + } |
| + start := c.now() |
| + r, err := c.exchange(ctx, id, replicas.CoordinatorChange{Op: op, Term: term, Box: c.box, BootID: c.boot}) |
| + if err == nil { |
| + err = ctx.Err() |
| + } |
| + if err != nil { |
| + return r, time.Time{}, err |
| + } |
| + if op == "release" { |
| + return r, time.Time{}, nil |
| + } |
| + if r.RemainingMS <= replicas.CoordinatorSafetyMargin.Milliseconds() || r.RemainingMS > replicas.CoordinatorTTL.Milliseconds() || r.Lease.Term == "" || (term != "" && r.Lease.Term != term) || r.Lease.Box != c.box || r.Lease.BootID != c.boot { |
| + return r, time.Time{}, replicas.ErrFenced |
| + } |
| + until := start.Add(time.Duration(r.RemainingMS)*time.Millisecond - replicas.CoordinatorSafetyMargin) |
| + if !c.now().Before(until) { |
| + return r, time.Time{}, replicas.ErrFenced |
| + } |
| + return r, until, nil |
| +} |
| + |
| +func (c *CoordinationClient) Acquire(ctx context.Context, id replicas.Identity) (replicas.Authority, error) { |
| + c.opMu.Lock() |
| + defer c.opMu.Unlock() |
| + c.mu.Lock() |
| + if c.closed { |
| + c.mu.Unlock() |
| + return nil, replicas.ErrFenced |
| + } |
| + if a := c.held[id]; a != nil && a.errLocked() == nil { |
| + c.mu.Unlock() |
| + return a, nil |
| + } |
| + if at := c.retry[id]; c.now().Before(at) { |
| + c.mu.Unlock() |
| + return nil, &replicas.CoordinatorHeldError{RetryAt: at} |
| + } |
| + c.mu.Unlock() |
| + r, until, err := c.request(ctx, id, "acquire", "") |
| + c.mu.Lock() |
| + if err != nil { |
| + var held *replicas.CoordinatorHeldError |
| + if errors.As(err, &held) { |
| + c.retry[id] = held.RetryAt |
| + } |
| + c.mu.Unlock() |
| + return nil, err |
| + } |
| + if c.closed { |
| + c.mu.Unlock() |
| + _, _, _ = c.request(ctx, id, "release", r.Lease.Term) |
| + return nil, replicas.ErrFenced |
| + } |
| + a := &coordinatorAuthority{client: c, id: id, term: r.Lease.Term, until: until, renewAt: c.now().Add(replicas.CoordinatorRenewAfter), lost: make(chan struct{})} |
| + c.held[id] = a |
| + delete(c.retry, id) |
| + c.mu.Unlock() |
| + return a, nil |
| +} |
| + |
| +func (c *CoordinationClient) ReleaseState(ctx context.Context, id replicas.Identity, change replicas.ReleaseChange) (replicas.Deploy, error) { |
| + c.mu.Lock() |
| + a := c.held[id] |
| + if c.closed || a == nil || a.errLocked() != nil || a.term != change.Term || c.release == nil { |
| + c.mu.Unlock() |
| + return replicas.Deploy{}, replicas.ErrFenced |
| + } |
| + c.mu.Unlock() |
| + d, err := c.release(ctx, id, change) |
| + if err != nil { |
| + return d, err |
| + } |
| + if err = a.Err(); err != nil { |
| + return replicas.Deploy{}, err |
| + } |
| + phase := change.Op |
| + if phase == "begin" { |
| + phase = "pending" |
| + } |
| + if d.Phase != phase || d.ID != change.ID || d.Term != change.Term || d.Incarnation != id.Incarnation || d.Target != change.Target { |
| + return replicas.Deploy{}, replicas.ErrFenced |
| + } |
| + return d, nil |
| +} |
| + |
| +func (c *CoordinationClient) Close(ctx context.Context) { |
| + c.mu.Lock() |
| + if c.closed { |
| + c.mu.Unlock() |
| + return |
| + } |
| + c.closed = true |
| + pending := make([]*coordinatorAuthority, 0, len(c.held)) |
| + for id, a := range c.held { |
| + a.loseLocked() |
| + pending = append(pending, a) |
| + delete(c.held, id) |
| + } |
| + c.mu.Unlock() |
| + c.opMu.Lock() |
| + defer c.opMu.Unlock() |
| + for _, a := range pending { |
| + _, _, _ = c.request(ctx, a.id, "release", a.term) |
| + } |
| +} |
| + |
| +type coordinatorAuthority struct { |
| + client *CoordinationClient |
| + id replicas.Identity |
| + term string |
| + until, renewAt time.Time |
| + lost chan struct{} |
| + ended bool |
| +} |
| + |
| +func (a *coordinatorAuthority) loseLocked() { |
| + if !a.ended { |
| + a.ended = true |
| + close(a.lost) |
| + } |
| +} |
| +func (a *coordinatorAuthority) errLocked() error { |
| + if a.ended || !a.client.now().Before(a.until) { |
| + a.loseLocked() |
| + return replicas.ErrFenced |
| + } |
| + return nil |
| +} |
| +func (a *coordinatorAuthority) Err() error { |
| + a.client.mu.Lock() |
| + defer a.client.mu.Unlock() |
| + return a.errLocked() |
| +} |
| +func (a *coordinatorAuthority) Lost() <-chan struct{} { _ = a.Err(); return a.lost } |
| +func (a *coordinatorAuthority) SafeUntil() (time.Time, error) { |
| + a.client.mu.Lock() |
| + defer a.client.mu.Unlock() |
| + return a.until, a.errLocked() |
| +} |
| +func (a *coordinatorAuthority) Release(ctx context.Context) error { |
| + c := a.client |
| + c.opMu.Lock() |
| + defer c.opMu.Unlock() |
| + c.mu.Lock() |
| + if err := a.errLocked(); err != nil { |
| + c.mu.Unlock() |
| + return err |
| + } |
| + a.loseLocked() |
| + delete(c.held, a.id) |
| + c.mu.Unlock() |
| + _, _, err := c.request(ctx, a.id, "release", a.term) |
| + return err |
| +} |
diff --git a/internal/activator/coordinator_test.go b/internal/activator/coordinator_test.go| new file mode 100644 |
| index 000000000..ae4cb5a49 |
| --- /dev/null |
| +++ b/internal/activator/coordinator_test.go |
| @@ -0,0 +1,240 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/replicas" |
| +) |
| + |
| +func TestCoordinatorTermFencesLateResults(t *testing.T) { |
| + ctx := context.Background() |
| + now := time.Now() |
| + var lease *replicas.Coordinator |
| + exchange := func(_ context.Context, _ replicas.Identity, c replicas.CoordinatorChange) (replicas.CoordinatorReply, error) { |
| + next, err := replicas.ChangeCoordinator(lease, c, now) |
| + if err != nil { |
| + return replicas.CoordinatorReply{}, err |
| + } |
| + lease = &next |
| + return replicas.CoordinatorReply{Lease: next, RemainingMS: replicas.CoordinatorTTL.Milliseconds()}, nil |
| + } |
| + id := replicas.Identity{Account: "a", App: "shop", Host: "shop.example.com", Incarnation: "life"} |
| + releaseState := func(_ context.Context, _ replicas.Identity, change replicas.ReleaseChange) (replicas.Deploy, error) { |
| + err := replicas.CheckAuthority(lease, change.Term, "box", "boot", now) |
| + return replicas.Deploy{}, err |
| + } |
| + a := NewCoordinatorClient("box", "boot", exchange, releaseState) |
| + a.now = func() time.Time { return now } |
| + old, err := a.Acquire(ctx, id) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + oldTerm := lease.Term |
| + now = now.Add(replicas.CoordinatorTTL + time.Second) |
| + b := NewCoordinatorClient("box", "boot", exchange, releaseState) |
| + b.now = a.now |
| + fresh, err := b.Acquire(ctx, id) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + newTerm := lease.Term |
| + _, lateSuccessErr := a.ReleaseState(ctx, id, replicas.ReleaseChange{Op: "released", ID: "deploy", Term: oldTerm}) |
| + if old.Err() == nil { |
| + t.Fatal("old authority remained live") |
| + } |
| + _, lateRenewErr := exchange(ctx, id, replicas.CoordinatorChange{Op: "renew", Term: oldTerm, Box: "box", BootID: "boot"}) |
| + webStops, workerStops := 0, 0 |
| + if oldTerm == newTerm || lateSuccessErr == nil || lateRenewErr == nil { |
| + t.Fatal("expired term remained authoritative") |
| + } |
| + if webStops != 0 || workerStops != 0 { |
| + t.Fatal("coordination stopped serving") |
| + } |
| + if err := fresh.Err(); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestCoordinatorRejectsLateReply(t *testing.T) { |
| + now := time.Now() |
| + c := NewCoordinatorClient("box", "boot", func(_ context.Context, _ replicas.Identity, _ replicas.CoordinatorChange) (replicas.CoordinatorReply, error) { |
| + now = now.Add(replicas.CoordinatorTTL) |
| + return replicas.CoordinatorReply{Lease: replicas.Coordinator{Term: "term", Box: "box", BootID: "boot"}, RemainingMS: replicas.CoordinatorTTL.Milliseconds()}, nil |
| + }, nil) |
| + c.now = func() time.Time { return now } |
| + if _, err := c.Acquire(context.Background(), replicas.Identity{}); !errors.Is(err, replicas.ErrFenced) { |
| + t.Fatalf("late reply: %v", err) |
| + } |
| +} |
| + |
| +func TestCoordinatorFollowerBackoffAndShutdown(t *testing.T) { |
| + now := time.Now() |
| + calls := 0 |
| + c := NewCoordinatorClient("box", "boot", func(_ context.Context, _ replicas.Identity, _ replicas.CoordinatorChange) (replicas.CoordinatorReply, error) { |
| + calls++ |
| + return replicas.CoordinatorReply{}, &replicas.CoordinatorHeldError{RetryAt: now.Add(time.Minute)} |
| + }, nil) |
| + c.now = func() time.Time { return now } |
| + id := replicas.Identity{Host: "shop.example.com"} |
| + for i := 0; i < 3; i++ { |
| + _, _ = c.Acquire(context.Background(), id) |
| + } |
| + if calls != 1 { |
| + t.Fatalf("follower requests = %d", calls) |
| + } |
| + c.Close(context.Background()) |
| + now = now.Add(time.Hour) |
| + if _, err := c.Acquire(context.Background(), id); err == nil { |
| + t.Fatal("closed client acquired") |
| + } |
| +} |
| + |
| +func TestCoordinatorRenewsOnlyHeldTerm(t *testing.T) { |
| + ctx := context.Background() |
| + now := time.Now() |
| + renews, releases := 0, 0 |
| + var client *CoordinationClient |
| + client = NewCoordinatorClient("box", "boot", func(_ context.Context, _ replicas.Identity, c replicas.CoordinatorChange) (replicas.CoordinatorReply, error) { |
| + if c.Op == "renew" { |
| + renews++ |
| + if c.Term != "term" { |
| + t.Fatal("renewal changed term") |
| + } |
| + if err := client.held[replicas.Identity{}].Err(); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if c.Op == "release" { |
| + releases++ |
| + } |
| + return replicas.CoordinatorReply{Lease: replicas.Coordinator{Term: "term", Box: "box", BootID: "boot"}, RemainingMS: replicas.CoordinatorTTL.Milliseconds()}, nil |
| + }, nil) |
| + client.now = func() time.Time { return now } |
| + a, err := client.Acquire(ctx, replicas.Identity{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + before, _ := a.SafeUntil() |
| + client.Tick(ctx) |
| + if renews != 0 { |
| + t.Fatal("early renewal") |
| + } |
| + now = now.Add(replicas.CoordinatorRenewAfter) |
| + client.Tick(ctx) |
| + after, err := a.SafeUntil() |
| + if err != nil || !after.After(before) || renews != 1 { |
| + t.Fatalf("renewal: %v %v, calls %d", after, err, renews) |
| + } |
| + client.Close(ctx) |
| + select { |
| + case <-a.Lost(): |
| + default: |
| + t.Fatal("shutdown did not close authority") |
| + } |
| + if a.Err() == nil || releases != 1 { |
| + t.Fatal("shutdown did not release") |
| + } |
| + client.Tick(ctx) |
| + if renews != 1 { |
| + t.Fatal("renewed after shutdown") |
| + } |
| +} |
| + |
| +func TestCoordinatorRenewalCannotBridgeExpiredSafety(t *testing.T) { |
| + now := time.Now() |
| + ctx := context.Background() |
| + c := NewCoordinatorClient("box", "boot", func(_ context.Context, _ replicas.Identity, change replicas.CoordinatorChange) (replicas.CoordinatorReply, error) { |
| + if change.Op == "renew" { |
| + now = now.Add(replicas.CoordinatorTTL) |
| + } |
| + return replicas.CoordinatorReply{Lease: replicas.Coordinator{Term: "term", Box: "box", BootID: "boot"}, RemainingMS: replicas.CoordinatorTTL.Milliseconds()}, nil |
| + }, nil) |
| + c.now = func() time.Time { return now } |
| + a, err := c.Acquire(ctx, replicas.Identity{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + now = now.Add(replicas.CoordinatorRenewAfter) |
| + c.Tick(ctx) |
| + if a.Err() == nil { |
| + t.Fatal("renewal bridged an expired safety deadline") |
| + } |
| +} |
| + |
| +func TestReplicaReleaseLostSuccessReply(t *testing.T) { |
| + ctx := context.Background() |
| + calls := 0 |
| + id := replicas.Identity{Incarnation: "life"} |
| + target := replicas.Build{Version: "v1", Digest: "digest"} |
| + var durable replicas.Deploy |
| + c := NewCoordinatorClient("box", "boot", func(context.Context, replicas.Identity, replicas.CoordinatorChange) (replicas.CoordinatorReply, error) { |
| + return replicas.CoordinatorReply{Lease: replicas.Coordinator{Term: "term", Box: "box", BootID: "boot"}, RemainingMS: replicas.CoordinatorTTL.Milliseconds()}, nil |
| + }, func(_ context.Context, _ replicas.Identity, ch replicas.ReleaseChange) (replicas.Deploy, error) { |
| + calls++ |
| + if calls == 1 { |
| + durable = replicas.Deploy{ID: ch.ID, Incarnation: id.Incarnation, Term: ch.Term, Target: ch.Target, Phase: "released", Revision: 3} |
| + return replicas.Deploy{}, errors.New("reply lost") |
| + } |
| + return durable, nil |
| + }) |
| + if _, err := c.Acquire(ctx, id); err != nil { |
| + t.Fatal(err) |
| + } |
| + ch := replicas.ReleaseChange{ID: "deploy", Op: "released", Term: "term", Revision: 2, Target: target} |
| + if _, err := c.ReleaseState(ctx, id, ch); err == nil { |
| + t.Fatal("transport failure missing") |
| + } |
| + got, err := c.ReleaseState(ctx, id, ch) |
| + if err != nil || got.Phase != "released" || calls != 2 { |
| + t.Fatalf("recovery: %+v %v, calls %d", got, err, calls) |
| + } |
| +} |
| + |
| +func TestCoordinatorSafetyDeadlineUsesRequestStart(t *testing.T) { |
| + start := time.Now() |
| + now := start |
| + c := NewCoordinatorClient("box", "boot", func(context.Context, replicas.Identity, replicas.CoordinatorChange) (replicas.CoordinatorReply, error) { |
| + now = now.Add(20 * time.Second) |
| + return replicas.CoordinatorReply{Lease: replicas.Coordinator{Term: "term", Box: "box", BootID: "boot"}, RemainingMS: replicas.CoordinatorTTL.Milliseconds()}, nil |
| + }, nil) |
| + c.now = func() time.Time { return now } |
| + a, err := c.Acquire(context.Background(), replicas.Identity{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + until, err := a.SafeUntil() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !until.Equal(start.Add(replicas.CoordinatorTTL - replicas.CoordinatorSafetyMargin)) { |
| + t.Fatalf("deadline includes response latency: %v", until) |
| + } |
| + now = until |
| + c.Tick(context.Background()) |
| + select { |
| + case <-a.Lost(): |
| + default: |
| + t.Fatal("expiry did not close authority") |
| + } |
| +} |
| + |
| +func TestCoordinatorReleaseStateRejectsLateResults(t *testing.T) { |
| + now := time.Now() |
| + id := replicas.Identity{Incarnation: "life"} |
| + c := NewCoordinatorClient("box", "boot", func(context.Context, replicas.Identity, replicas.CoordinatorChange) (replicas.CoordinatorReply, error) { |
| + return replicas.CoordinatorReply{Lease: replicas.Coordinator{Term: "term", Box: "box", BootID: "boot"}, RemainingMS: replicas.CoordinatorTTL.Milliseconds()}, nil |
| + }, func(_ context.Context, _ replicas.Identity, ch replicas.ReleaseChange) (replicas.Deploy, error) { |
| + now = now.Add(replicas.CoordinatorTTL) |
| + return replicas.Deploy{ID: ch.ID, Term: ch.Term, Target: ch.Target, Phase: ch.Op, Incarnation: id.Incarnation}, nil |
| + }) |
| + c.now = func() time.Time { return now } |
| + if _, err := c.Acquire(context.Background(), id); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := c.ReleaseState(context.Background(), id, replicas.ReleaseChange{Op: "released", ID: "deploy", Term: "term"}); !errors.Is(err, replicas.ErrFenced) { |
| + t.Fatalf("late success: %v", err) |
| + } |
| +} |
diff --git a/internal/host/replicacoordinator.go b/internal/host/replicacoordinator.go| new file mode 100644 |
| index 000000000..d5c6a0a35 |
| --- /dev/null |
| +++ b/internal/host/replicacoordinator.go |
| @@ -0,0 +1,128 @@ |
| +package host |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/replicas" |
| +) |
| + |
| +func newCoordinatorClient(store release.Store, consoleURL, fleet, box, token string) activator.CoordinatorClient { |
| + boot := readBootID(bootIDPath) |
| + if fleet != "" { |
| + api := &replicaCoordinatorAPI{base: strings.TrimRight(consoleURL, "/"), fleet: fleet, box: box, token: token, client: &http.Client{Timeout: 30 * time.Second}} |
| + return activator.NewCoordinatorClient(box, boot, api.coordinator, api.releaseState) |
| + } |
| + adapter := &replicaCoordinatorStore{store: store} |
| + return activator.NewCoordinatorClient(box, boot, adapter.coordinator, adapter.releaseState) |
| +} |
| + |
| +type replicaCoordinatorStore struct{ store release.Store } |
| + |
| +func (s *replicaCoordinatorStore) coordinator(ctx context.Context, id replicas.Identity, change replicas.CoordinatorChange) (replicas.CoordinatorReply, error) { |
| + rec, err := provision.SetRecordCoordinator(ctx, s.store, id, change, time.Now()) |
| + if err != nil { |
| + return replicas.CoordinatorReply{}, err |
| + } |
| + if change.Op != "renew" { |
| + if err := release.BumpSerial(ctx, s.store, time.Now()); err != nil { |
| + return replicas.CoordinatorReply{}, err |
| + } |
| + } |
| + return replicas.CoordinatorReply{Lease: *rec.Coordinator, RemainingMS: max(0, time.Until(rec.Coordinator.ExpiresAt).Milliseconds())}, nil |
| +} |
| +func (s *replicaCoordinatorStore) releaseState(ctx context.Context, id replicas.Identity, change replicas.ReleaseChange) (replicas.Deploy, error) { |
| + var result replicas.Deploy |
| + err := release.WithAppMutation(ctx, s.store, id.Account, id.App, "host.replicaRelease", func(ctx context.Context) error { |
| + current, err := provision.GetRecord(ctx, s.store, id.Account, id.App, id.Host) |
| + if err != nil { |
| + return err |
| + } |
| + next := replicas.Deploy{ID: change.ID, Incarnation: id.Incarnation, Term: change.Term, Target: change.Target, Phase: change.Op} |
| + if next.Phase == "begin" { |
| + next.Phase = "pending" |
| + } |
| + if current.ReplicaDeploy != nil && current.ReplicaDeploy.ID == next.ID { |
| + next.Previous = current.ReplicaDeploy.Previous |
| + } |
| + rec, err := provision.SetRecordReplicaRelease(ctx, s.store, id, change.Revision, next) |
| + if err != nil { |
| + return err |
| + } |
| + result = *rec.ReplicaDeploy |
| + if rec.RecordSeq != current.RecordSeq { |
| + return release.BumpSerial(ctx, s.store, time.Now()) |
| + } |
| + return nil |
| + }) |
| + return result, err |
| +} |
| + |
| +type replicaCoordinatorAPI struct { |
| + base, fleet, box, token string |
| + client *http.Client |
| +} |
| + |
| +func (a *replicaCoordinatorAPI) post(ctx context.Context, id replicas.Identity, op string, body, out any) error { |
| + raw, err := json.Marshal(body) |
| + if err != nil { |
| + return err |
| + } |
| + endpoint := a.base + "/api/fleet/replicas/" + url.PathEscape(id.Account) + "/" + url.PathEscape(id.App) + "/" + url.PathEscape(id.Host) + "/" + op |
| + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(raw)) |
| + if err != nil { |
| + return err |
| + } |
| + req.Header.Set("Authorization", "Bearer "+a.token) |
| + req.Header.Set("Carlos-Tunnel-Name", a.fleet+"/"+a.box) |
| + req.Header.Set("Content-Type", "application/json") |
| + resp, err := a.client.Do(req) |
| + if err != nil { |
| + return err |
| + } |
| + defer resp.Body.Close() |
| + d := json.NewDecoder(io.LimitReader(resp.Body, 8192)) |
| + if resp.StatusCode != http.StatusOK { |
| + if resp.StatusCode == http.StatusConflict && op == "coordinator" { |
| + var held struct { |
| + RetryAt time.Time `json:"retry_at"` |
| + } |
| + if d.Decode(&held) == nil && !held.RetryAt.IsZero() { |
| + return &replicas.CoordinatorHeldError{RetryAt: held.RetryAt} |
| + } |
| + } |
| + return replicas.ErrFenced |
| + } |
| + if err := d.Decode(out); err != nil { |
| + return err |
| + } |
| + if d.Decode(new(any)) != io.EOF { |
| + return replicas.ErrInvalid |
| + } |
| + return nil |
| +} |
| +func (a *replicaCoordinatorAPI) coordinator(ctx context.Context, id replicas.Identity, change replicas.CoordinatorChange) (replicas.CoordinatorReply, error) { |
| + var reply replicas.CoordinatorReply |
| + err := a.post(ctx, id, "coordinator", struct { |
| + Incarnation string `json:"incarnation"` |
| + replicas.CoordinatorChange |
| + }{id.Incarnation, change}, &reply) |
| + return reply, err |
| +} |
| +func (a *replicaCoordinatorAPI) releaseState(ctx context.Context, id replicas.Identity, change replicas.ReleaseChange) (replicas.Deploy, error) { |
| + var reply replicas.Deploy |
| + err := a.post(ctx, id, "release", struct { |
| + Incarnation string `json:"incarnation"` |
| + replicas.ReleaseChange |
| + }{id.Incarnation, change}, &reply) |
| + return reply, err |
| +} |
diff --git a/internal/host/replicacoordinator_test.go b/internal/host/replicacoordinator_test.go| new file mode 100644 |
| index 000000000..c001b05fc |
| --- /dev/null |
| +++ b/internal/host/replicacoordinator_test.go |
| @@ -0,0 +1,159 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/console" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/replicas" |
| +) |
| + |
| +type replicaDeniedStore struct { |
| + release.Store |
| + writes int |
| +} |
| + |
| +func (s *replicaDeniedStore) Put(context.Context, string, []byte, string) (string, error) { |
| + s.writes++ |
| + return "", replicas.ErrFenced |
| +} |
| +func (s *replicaDeniedStore) Delete(context.Context, string) error { |
| + s.writes++ |
| + return replicas.ErrFenced |
| +} |
| +func (s *replicaDeniedStore) Get(context.Context, string) ([]byte, string, error) { |
| + return nil, "", replicas.ErrFenced |
| +} |
| + |
| +func TestReplicaReleaseFleetAPI(t *testing.T) { |
| + ctx := context.Background() |
| + root := t.TempDir() |
| + path := filepath.Join(root, "registry.db") |
| + reg, err := registry.Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { reg.Close() }) |
| + if ok, err := reg.CreateFleet(registry.Fleet{Name: "home", Account: "acme", Bucket: "home-data"}); err != nil || !ok { |
| + t.Fatalf("fleet: %v", err) |
| + } |
| + token := "replica-test-token" |
| + hash := sha256.Sum256([]byte(token)) |
| + if err := reg.AddFleetBox(registry.FleetBox{Fleet: "home", Label: "b1", TokenHash: hex.EncodeToString(hash[:])}); err != nil { |
| + t.Fatal(err) |
| + } |
| + store := release.NewDirStore(filepath.Join(root, "records")) |
| + rec := provision.Record{Schema: 1, Host: "shop.example.com", Slug: "shop", App: "shop", Account: "acme", Pool: "shop", Region: "fleet/home", Channel: "stable", CreatedAt: time.Now(), CreatedBy: "test"} |
| + if err := provision.CreateRecord(ctx, store, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := provision.SetRecordFleetBox(ctx, store, rec.Account, rec.App, rec.Host, provision.FleetBoxExpect{Region: rec.Region, CreatedAt: rec.CreatedAt}, "b1", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + db, err := console.Open(filepath.Join(root, "console.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { db.Close() }) |
| + srv, err := console.NewServer(console.Config{Registry: path, Releases: store}, db) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ts := httptest.NewServer(srv) |
| + t.Cleanup(ts.Close) |
| + denied := &replicaDeniedStore{} |
| + client := newCoordinatorClient(denied, ts.URL, "home", "b1", token) |
| + defer client.(*activator.CoordinationClient).Close(ctx) |
| + inc, err := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + id := replicas.Identity{Account: rec.Account, App: rec.App, Host: rec.Host, Incarnation: inc} |
| + authority, err := client.Acquire(ctx, id) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := authority.Err(); err != nil { |
| + t.Fatal(err) |
| + } |
| + current, err := provision.GetRecord(ctx, store, id.Account, id.App, id.Host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + term := current.Coordinator.Term |
| + var deploy replicas.Deploy |
| + for _, op := range []string{"begin", "releasing", "released"} { |
| + deploy, err = client.ReleaseState(ctx, id, replicas.ReleaseChange{Op: op, ID: "deploy-1", Term: term, Revision: deploy.Revision, Target: replicas.Build{Version: "v1", Digest: "canonical"}}) |
| + if err != nil { |
| + t.Fatalf("%s: %v", op, err) |
| + } |
| + } |
| + if deploy.Phase != "released" || denied.writes != 0 { |
| + t.Fatalf("result %s; direct fleet writes %d", deploy.Phase, denied.writes) |
| + } |
| +} |
| + |
| +func TestCoordinatorTrustedStoreAdapter(t *testing.T) { |
| + ctx := context.Background() |
| + store := release.NewDirStore(t.TempDir()) |
| + rec := provision.Record{Schema: 1, Account: "acme", App: "shop", Host: "shop.example.com", Slug: "shop", Pool: "shop", Channel: "stable", Region: "ie", CreatedAt: time.Now(), CreatedBy: "test"} |
| + if err := provision.CreateRecord(ctx, store, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + inc, err := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + id := replicas.Identity{Account: rec.Account, App: rec.App, Host: rec.Host, Incarnation: inc} |
| + adapter := &replicaCoordinatorStore{store: store} |
| + reply, err := adapter.coordinator(ctx, id, replicas.CoordinatorChange{Op: "acquire", Box: "local", BootID: "boot"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + _, serialBefore, err := release.ReadSerial(ctx, store) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + renewed, err := adapter.coordinator(ctx, id, replicas.CoordinatorChange{Op: "renew", Term: reply.Lease.Term, Box: "local", BootID: "boot"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + _, serialAfter, err := release.ReadSerial(ctx, store) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if renewed.Lease.Term != reply.Lease.Term || serialBefore != serialAfter { |
| + t.Fatal("renewal changed term or serial") |
| + } |
| + var deploy replicas.Deploy |
| + for _, op := range []string{"begin", "releasing", "released"} { |
| + deploy, err = adapter.releaseState(ctx, id, replicas.ReleaseChange{Op: op, ID: "deploy", Term: reply.Lease.Term, Revision: deploy.Revision, Target: replicas.Build{Version: "v1", Digest: "canonical"}}) |
| + if err != nil { |
| + t.Fatalf("%s: %v", op, err) |
| + } |
| + } |
| + before, err := provision.GetRecord(ctx, store, id.Account, id.App, id.Host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + replay, err := adapter.releaseState(ctx, id, replicas.ReleaseChange{Op: "released", ID: deploy.ID, Term: deploy.Term, Revision: deploy.Revision - 1, Target: deploy.Target}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + after, err := provision.GetRecord(ctx, store, id.Account, id.App, id.Host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if replay.Revision != deploy.Revision || before.RecordSeq != after.RecordSeq { |
| + t.Fatal("replay rewrote released evidence") |
| + } |
| +} |
diff --git a/internal/provision/stateless_replicas_census_test.go b/internal/provision/stateless_replicas_census_test.go| index 50405662a..db1d6a76d 100644 |
| --- a/internal/provision/stateless_replicas_census_test.go |
| +++ b/internal/provision/stateless_replicas_census_test.go |
| @@ -9,6 +9,10 @@ func statelessReplicasWriteCensusInventory() []censusEntry { |
| // lock; both API callsites hold withRecordLock after fleet ownership, |
| // credential, assignment and payload identity checks. No direct Put added. |
| for _, next := range []censusEntry{ |
| + // Trusted client only: both calls retain lifetime-judged typed CAS. |
| + // Fleet selection constructs only the HTTP adapter and cannot reach these. |
| + {"internal/host/replicacoordinator.go", "replicaCoordinatorStore.coordinator", "record-writer", "key:SetRecordCoordinator", "1856926de34983178e3d2b79dd34b4e7fe9f5b0a77d9a766aa899d09532c9946"}, |
| + {"internal/host/replicacoordinator.go", "replicaCoordinatorStore.releaseState", "record-writer", "key:SetRecordReplicaRelease", "6841e676c0e8ab24d026cc15e04394b9e3e0e4dc0fdfd578c83275a752779d18"}, |
| // Registration adds only the two fleet routes; the existing literal-only |
| // instances/sidecars classification and all existing route handlers stay fixed. |
| {"internal/console/authcli.go", "Server.registerCLIRoutes", "key-site", "lit:instances,lit:sidecars", "89c700b1b939a8c8bbd478a548efeabfa4fc888f1509b7e3c76ad91472219a29"}, |
diff --git a/internal/provision/testdata/plan14-root-reads-stateless-replicas-1.tsv b/internal/provision/testdata/plan14-root-reads-stateless-replicas-1.tsv| index 8c8c4c80f..3fb8df7b7 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-stateless-replicas-1.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-stateless-replicas-1.tsv |
| @@ -1,5 +1,5 @@ |
| # Census overlay stateless-replicas-1, written by census-propose (#369). census-ruling-stateless-replicas-1, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-stateless-replicas-1.md. |
| -# 2 body, 0 sites, 4 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 2 body, 0 sites, 6 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| # 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| @legacy 8532ad0b6523e01bb6548e7a0ff565615b99e39a8921c338db522812368899a3 cli.go runShip legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-rootfs-apps-1;basis=rootfs Plan 1 Task 9: takes --rootfs, --processes, --hibernate, --jit and --check and hands a rootfs ship to runShipRootfs (ship_rootfs.go) before the binary path; the --notes-file ReadFile moved into shipNoteText (its own row, the same read of the file the person named) and the direct-mode version mint into mintDirectVersion; one read site fewer, none added; Task 12: the --hibernate flag help is RFS-1-C32's new text, the same reads;rev3=census-ruling-edge-asset-cache-1;basis=takes --assets (repeatable), checks the folders with checkShipAssets (release.ValidAssetPaths; refused on a static site) before the mode split, carries them into the API meta (sess.shipAssets) and the direct-mode manifest (shipAssetsBlock), and passes them to runShipRootfs (rootfsShipOpts.assets), which runs the same check and carries them the same two ways; after a direct-mode ship has stored a release declaring folders, directShipAssetGens runs the console ship door's backfill (provision.MintMissingAssetGens: lists the app's record keys and gives each record without an asset generation one, a CAS write in the deployment bucket as the person running the CLI) and fails naming any record it could not mint; read sites unchanged (2), none added;rev3=census-ruling-rootfs-apps-4;basis=adds the repeatable --env flag and refuses it before anything else unless --check is given (shipEnvRefusal, parseShipCheckEnv); the parsed values go into rootfsShipOpts.checkEnv. --env values reach the check's local container runtime as -e argv only, never root, never a box. No read added; read sites unchanged (2).;rev3=census-ruling-stateless-replicas-1;basis=Carry --stateless into binary/API and rootfs ship options; same two read sites, no new read. file:ReadFile@7899,file:ReadFile@8123 d6f244d2c3bcae95eb8ec0fa7e57c52e9b50c7e9e2e00dda85f930b643731a51 |
| @legacy 1e4efb560a06cb532c8d4caf719ff375c27a03a5651b26c59d81f271c70da628 ship_check.go rootfsCheck.runArgs legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-1;basis=root-input (J4, as main's db.go units); the carlos CLI on a person's machine, as the person (no box unit): new (rootfs Plan 1), builds the docker or podman run argv for one check container; the scanner matches the word Command, here a field of release.Process (a process's argv), not os/exec; reads no file; decides nothing for root;rev3=census-ruling-rootfs-check-volumes;basis=R2 P1: the data and run volume mounts (-v) now carry :nocopy through rootfsCheck.volumeMount, so Docker and Podman never fill an empty check volume from the image directory at the mount point (which would reset the prepared owner and mode); same volumes, same paths, same probe mount, nothing else in the argv changed. Runs on the person's machine as the person; no box unit; no read added.;rev3=census-ruling-stateless-replicas-1;basis=Stateless local checks mount only the run volume and omit the database mount; same probe read, no new read. file:Command@887,file:Command@971 e684fd3273527a209460ed81e5bcd472a4282f46830fe580e5f07f0b0d876684 |
| @@ -8,6 +8,8 @@ cli.go runShip legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;r |
| ship_check.go rootfsCheck.runArgs legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-1;basis=root-input (J4, as main's db.go units); the carlos CLI on a person's machine, as the person (no box unit): new (rootfs Plan 1), builds the docker or podman run argv for one check container; the scanner matches the word Command, here a field of release.Process (a process's argv), not os/exec; reads no file; decides nothing for root;rev3=census-ruling-rootfs-check-volumes;basis=R2 P1: the data and run volume mounts (-v) now carry :nocopy through rootfsCheck.volumeMount, so Docker and Podman never fill an empty check volume from the image directory at the mount point (which would reset the prepared owner and mode); same volumes, same paths, same probe mount, nothing else in the argv changed. Runs on the person's machine as the person; no box unit; no read added.;rev3=census-ruling-stateless-replicas-1;basis=Stateless local checks mount only the run volume and omit the database mount; same probe read, no new read. file:Command@887,file:Command@971 e684fd3273527a209460ed81e5bcd472a4282f46830fe580e5f07f0b0d876684 |
| internal/replicas/coordinator.go ChangeCoordinator legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-1;basis=Generate a fresh 128-bit coordinator term using crypto/rand.Read; no file path or process input added. file:Read@472 e50ce5a352b3022a1ee6375fbfee315a5d2fcaeb4f4a25f4e33a5a10e3000a67 |
| @coverage . d8abf32baa39f05d1e9d4e9b8a24e7113c58f42f8735e7a62e217eb39e7a4bf7 |
| +@coverage internal/activator 421955bd35939b1be1ce73742194c7f49545152f1ca9e8a7bf6051be78d02b09 |
| +@coverage internal/host 3739b405de9e625ae361d664dca7c61508b2d789cde71e4b33f6bf880d555b0f |
| @coverage internal/provision 974d05f290939ef4e4eb8af398b230b1df780357c3077988a35054ce52109626 |
| @coverage internal/release 261fde7e6e53d2b4d944df966be3f00208d4d7153aed2d19148cbfd403af9d52 |
| @coverage internal/replicas 53b94eb040154539a0a977498b4b8bc1d53d82f67c1c6233667a0b823dd30d8a |