fix: judge managed publication freshness on a fresh clock reading
Task 2 review round 1 (Astra P1-1, P2-1, P2-2). - Freshness: a pass's time is anchored to a clock reading at pass start (Server.managedClock, nil means time.Now). Publication judges the age of its checks on the pass time plus elapsed clock time, after the ready-object GET and again immediately before a new PUT, and dates refreshed checks and the attempt stamp by when the observation finished. Deadlines still use ReadyAt and launch times. Matching objects complete ready without readiness reads. - Launch gate: an operation whose preparation failed in a pass (for example unusable credentials on a prepared fleet) dispatches none of its never-launched reservations in that pass; dispatched boxes keep their recovery and cleanup. - Readiness reads the registry through the store's managed registry seam with GetFleetContext/ListFleetBoxesContext, so cancellation and the 30 s timeout end a blocked read.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+251
−13
internal/console/managedhistory_test.go+4 −0internal/console/managedready.go+13 −9internal/console/managedready_test.go+129 −0internal/console/managedrecovery_test.go+50 −0internal/console/managedworker.go+53 −3internal/console/managedworker_test.go+1 −1internal/console/server.go+1 −0
diff --git a/internal/console/managedhistory_test.go b/internal/console/managedhistory_test.go| index b367dc521..c179fb317 100644 |
| --- a/internal/console/managedhistory_test.go |
| +++ b/internal/console/managedhistory_test.go |
| @@ -32,6 +32,10 @@ func managedPreparationFixture(t *testing.T) (*Server, consoleRegistry) { |
| s.managed.watch = &managedTestWatch{ok: true} |
| s.managed.snapshot = managedConfigSnapshot{Config: validManagedConfig()} |
| s.managed.read = true |
| + // A frozen clock: no wall time elapses inside a pass, so stamps equal |
| + // the pass time. Clock-sensitive tests install a controlled one. |
| + fixed := time.Now() |
| + s.managedClock = func() time.Time { return fixed } |
| return s, reg |
| } |
| func setManagedHistory(t *testing.T, s *Server, st provision.HostsState) { |
diff --git a/internal/console/managedready.go b/internal/console/managedready.go| index 2a904f3df..c04ab08df 100644 |
| --- a/internal/console/managedready.go |
| +++ b/internal/console/managedready.go |
| @@ -87,18 +87,20 @@ func (s *Server) observeManagedReadiness(ctx context.Context, b managedBox, now |
| } |
| ctx, cancel := context.WithTimeout(ctx, managedCallTimeout) |
| defer cancel() |
| - reg, err := openRegistry(s.cfg.Registry) |
| - if err != nil { |
| - return checks, "", err |
| + // The managed registry reads honour ctx: cancellation or the timeout |
| + // ends a blocked call (production resolves it through openRegistry). |
| + reg := s.store.managedRegistry |
| + if reg == nil { |
| + return checks, "", errManagedWorker |
| } |
| - fleet, err := reg.GetFleet(b.Fleet) |
| + fleet, err := reg.GetFleetContext(ctx, b.Fleet) |
| if err != nil { |
| return checks, "", err |
| } |
| if fleet == nil || fleet.Account != b.Account || !fleet.Managed { |
| return checks, "", nil |
| } |
| - boxes, err := reg.ListFleetBoxes(b.Fleet) |
| + boxes, err := reg.ListFleetBoxesContext(ctx, b.Fleet) |
| if err != nil { |
| return checks, "", err |
| } |
| @@ -198,7 +200,8 @@ func (s *Server) checkManagedReadiness(ctx context.Context, b managedBox, now ti |
| if !all && managedChecksEqual(b.Checks, checks) && b.ObservedVersion == version { |
| return nil |
| } |
| - next.ReadinessCheckedAt = now |
| + // The checks are dated by when the observation finished. |
| + next.ReadinessCheckedAt = s.managedCurrentTime(ctx, now) |
| if err := s.saveManagedBox(ctx, b, next, now); err != nil { |
| return err |
| } |
| @@ -218,10 +221,11 @@ func (s *Server) checkManagedReadiness(ctx context.Context, b managedBox, now ti |
| // a failed read never dates older passes as fresh. ok means the six current |
| // checks authorize a new create-only PUT; ReadyAt never changes. |
| func (s *Server) refreshManagedPublication(ctx context.Context, b managedBox, now time.Time) (managedBox, bool, error) { |
| - if !b.LastHeartbeatAt.IsZero() && now.Before(b.LastHeartbeatAt.Add(time.Minute)) { |
| + at := s.managedCurrentTime(ctx, now) |
| + if !b.LastHeartbeatAt.IsZero() && at.Before(b.LastHeartbeatAt.Add(time.Minute)) { |
| return b, false, nil |
| } |
| - b, obs, err := s.observeManagedAttempt(ctx, b, now) |
| + b, obs, err := s.observeManagedAttempt(ctx, b, at) |
| if err != nil || obs.err != nil { |
| return b, false, err |
| } |
| @@ -233,7 +237,7 @@ func (s *Server) refreshManagedPublication(ctx context.Context, b managedBox, no |
| } |
| } |
| next.ObservedVersion = obs.version |
| - next.ReadinessCheckedAt = now |
| + next.ReadinessCheckedAt = s.managedCurrentTime(ctx, now) |
| if err = s.saveManagedBox(ctx, b, next, now); err != nil { |
| return b, false, err |
| } |
diff --git a/internal/console/managedready_test.go b/internal/console/managedready_test.go| index 872e25800..6f5f9435e 100644 |
| --- a/internal/console/managedready_test.go |
| +++ b/internal/console/managedready_test.go |
| @@ -614,3 +614,132 @@ func TestManagedDelayedPublicationFreshness(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +// managedClockStore advances a controlled clock while a ready-object GET is |
| +// outstanding, as a slow store call would. |
| +type managedClockStore struct { |
| + release.Store |
| + clock *time.Time |
| + slow time.Duration |
| +} |
| + |
| +func (st *managedClockStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if strings.HasSuffix(key, "/ready.json") { |
| + *st.clock = st.clock.Add(st.slow) |
| + } |
| + return st.Store.Get(ctx, key) |
| +} |
| + |
| +// TestManagedDelayedPublicationClock: freshness is judged on a clock reading |
| +// taken after the slow GET, not on the pass's start time. Checks 50 s old at |
| +// the start of the pass and 70 s old after the GET grant nothing. |
| +func TestManagedDelayedPublicationClock(t *testing.T) { |
| + for _, kind := range []string{"crossing", "within"} { |
| + t.Run(kind, func(t *testing.T) { |
| + s, b, now := readyFixture(t) |
| + clock := now |
| + s.managedClock = func() time.Time { return clock } |
| + st := countReadiness(s) |
| + st.failPut = true |
| + b = workerStep(t, s, now) |
| + st.failPut = false |
| + if b.State != "publishing" || !b.ReadinessCheckedAt.Equal(now) { |
| + t.Fatalf("fixture: %+v", b) |
| + } |
| + // A refresh, if one runs, cannot authorize: the router check is pending. |
| + s.managedExtra = readyExtras{managedCheck{State: "pass"}, managedCheck{State: "pending"}} |
| + slow := 20 * time.Second |
| + if kind == "within" { |
| + slow = 5 * time.Second |
| + } |
| + s.cfg.Releases = &managedClockStore{Store: st, clock: &clock, slow: slow} |
| + at := now.Add(50 * time.Second) |
| + b = workerStep(t, s, at) |
| + if kind == "crossing" { |
| + if st.puts != 1 || b.State != "publishing" { |
| + t.Fatalf("70 s old checks authorized a PUT: puts=%d %+v", st.puts, b) |
| + } |
| + if !b.ReadinessCheckedAt.Equal(at.Add(slow)) || !b.LastHeartbeatAt.Equal(at.Add(slow)) { |
| + t.Fatalf("refresh not dated by the fresh reading: %+v", b) |
| + } |
| + return |
| + } |
| + if st.puts != 2 || b.State != "ready" || !b.ReadyAt.Equal(now) { |
| + t.Fatalf("55 s old checks did not publish: puts=%d %+v", st.puts, b) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// blockingManagedRegistry parks one managed registry read until its context |
| +// ends. |
| +type blockingManagedRegistry struct { |
| + inner interface { |
| + GetFleetContext(context.Context, string) (*registry.Fleet, error) |
| + ListFleetBoxesContext(context.Context, string) ([]registry.FleetBox, error) |
| + } |
| + park string |
| + entered chan struct{} |
| +} |
| + |
| +func (r *blockingManagedRegistry) block(ctx context.Context, call string) error { |
| + if r.park != call { |
| + return nil |
| + } |
| + select { |
| + case r.entered <- struct{}{}: |
| + default: |
| + } |
| + <-ctx.Done() |
| + return ctx.Err() |
| +} |
| +func (r *blockingManagedRegistry) GetFleetContext(ctx context.Context, name string) (*registry.Fleet, error) { |
| + if err := r.block(ctx, "get"); err != nil { |
| + return nil, err |
| + } |
| + return r.inner.GetFleetContext(ctx, name) |
| +} |
| +func (r *blockingManagedRegistry) ListFleetBoxesContext(ctx context.Context, name string) ([]registry.FleetBox, error) { |
| + if err := r.block(ctx, "list"); err != nil { |
| + return nil, err |
| + } |
| + return r.inner.ListFleetBoxesContext(ctx, name) |
| +} |
| + |
| +// TestManagedReadinessRegistryCancel: a blocked registry read during |
| +// readiness observation honours cancellation; the pass ends and the box does |
| +// not advance toward publication. |
| +func TestManagedReadinessRegistryCancel(t *testing.T) { |
| + for _, park := range []string{"get", "list"} { |
| + t.Run(park, func(t *testing.T) { |
| + s, b, now := readyFixture(t) |
| + reg := &blockingManagedRegistry{inner: s.store.managedRegistry, park: park, entered: make(chan struct{}, 1)} |
| + s.store.managedRegistry = reg |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + done := make(chan error, 1) |
| + go func() { done <- s.RunManagedFleetsPass(ctx, now) }() |
| + select { |
| + case <-reg.entered: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("readiness did not read the managed registry") |
| + } |
| + cancel() |
| + select { |
| + case err := <-done: |
| + if err == nil { |
| + t.Fatal("cancelled pass reported success") |
| + } |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("cancellation did not reach the registry read") |
| + } |
| + got := workerBox(t, s) |
| + if got.State != "enrolled" || !got.ReadyAt.IsZero() || !got.ReadinessCheckedAt.IsZero() { |
| + t.Fatalf("cancelled observation advanced the box: %+v", got) |
| + } |
| + if _, _, err := s.cfg.Releases.Get(context.Background(), managedReadyKey(b)); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal("ready object written", err) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/console/managedrecovery_test.go b/internal/console/managedrecovery_test.go| index ed731786e..e14e9d65b 100644 |
| --- a/internal/console/managedrecovery_test.go |
| +++ b/internal/console/managedrecovery_test.go |
| @@ -592,3 +592,53 @@ func TestManagedDeliveredKeySet(t *testing.T) { |
| } |
| }) |
| } |
| + |
| +type managedRotationSpy struct { |
| + *managedStorageSpy |
| + failRotate bool |
| +} |
| + |
| +func (p *managedRotationSpy) RotateFleetCredentials(ctx context.Context, fleet, keep string, delivered []string) (fleetstore.Credentials, error) { |
| + if p.failRotate { |
| + p.rotations++ |
| + return fleetstore.Credentials{}, errors.New("provider unavailable") |
| + } |
| + return p.managedStorageSpy.RotateFleetCredentials(ctx, fleet, keep, delivered) |
| +} |
| + |
| +// TestManagedCredentialFailureHoldsLaunch: an add to a prepared fleet gets |
| +// storage at reservation, but while its credential preparation fails no |
| +// reservation dispatches. Recovery then launches it. |
| +func TestManagedCredentialFailureHoldsLaunch(t *testing.T) { |
| + s, p, _ := managedE2E(t, 1) |
| + clock := func() time.Time { return time.Now().UTC() } |
| + spy := &managedRotationSpy{managedStorageSpy: &managedStorageSpy{Fake: s.cfg.ManagedStorage.(*fleetstore.Fake)}} |
| + s.cfg.ManagedStorage = spy |
| + e2ePass(t, s, clock()) |
| + e2eEnrol(t, s, e2eBoxes(t, s)[0]) |
| + e2eReady(t, s, clock()) |
| + if _, err := s.store.db.Exec(`UPDATE managed_fleet_storage SET credential_sealed=X'00'`); err != nil { |
| + t.Fatal(err) |
| + } |
| + spy.failRotate = true |
| + managedAPIReply(t, managedAPICall(s, "add", "abc", "production", fmt.Sprintf(`{"boxes":1,"request_id":%q}`, strings.Repeat("b", 22)))) |
| + launches := p.Calls()["Launch"] |
| + for i := 0; i < 3; i++ { |
| + s.wakeManagedFleets() |
| + e2ePass(t, s, clock()) |
| + } |
| + if p.Calls()["Launch"] != launches || spy.rotations < 3 { |
| + t.Fatalf("launched without usable credentials: %v rotations=%d", p.Calls(), spy.rotations) |
| + } |
| + for _, b := range e2eBoxes(t, s) { |
| + if b.Label == "box-2" && (b.State != "reserved" || !b.LaunchStartedAt.IsZero()) { |
| + t.Fatalf("reservation dispatched: %+v", b) |
| + } |
| + } |
| + spy.failRotate = false |
| + s.wakeManagedFleets() |
| + e2ePass(t, s, clock()) |
| + if p.Calls()["Launch"] != launches+1 { |
| + t.Fatal("recovered credentials did not launch", p.Calls()) |
| + } |
| +} |
diff --git a/internal/console/managedworker.go b/internal/console/managedworker.go| index 6e92366d7..966586c2b 100644 |
| --- a/internal/console/managedworker.go |
| +++ b/internal/console/managedworker.go |
| @@ -119,8 +119,47 @@ func (s *Server) RunManagedFleetsPass(ctx context.Context, now time.Time) error |
| } |
| return result |
| } |
| + |
| +// managedClockKey anchors a pass's time, now, to a clock reading taken when |
| +// the pass began. managedCurrentTime adds the clock time elapsed since, so |
| +// decisions that depend on age see slow calls earlier in the pass. |
| +type managedClockKey struct{} |
| +type managedClockAnchor struct{ now, started time.Time } |
| + |
| +func (s *Server) managedClockNow() time.Time { |
| + if s.managedClock != nil { |
| + return s.managedClock() |
| + } |
| + return time.Now() |
| +} |
| + |
| +// managedPassClock anchors ctx once; a step inside a pass keeps the pass's. |
| +func (s *Server) managedPassClock(ctx context.Context, now time.Time) context.Context { |
| + if _, ok := ctx.Value(managedClockKey{}).(managedClockAnchor); ok { |
| + return ctx |
| + } |
| + return context.WithValue(ctx, managedClockKey{}, managedClockAnchor{now: now, started: s.managedClockNow()}) |
| +} |
| + |
| +// managedCurrentTime is the pass time plus the clock time elapsed since the |
| +// pass began: a fresh reading in the pass's own time frame. Deadlines keep |
| +// using the persisted ReadyAt and launch times. |
| +func (s *Server) managedCurrentTime(ctx context.Context, now time.Time) time.Time { |
| + a, ok := ctx.Value(managedClockKey{}).(managedClockAnchor) |
| + if !ok { |
| + return now |
| + } |
| + return a.now.Add(s.managedClockNow().Sub(a.started)) |
| +} |
| + |
| +// managedUnpreparedKey carries the operations whose preparation failed in |
| +// this pass; their never-dispatched reservations do not launch in it. |
| +type managedUnpreparedKey struct{} |
| + |
| func (s *Server) managedFleetsPass(ctx context.Context, now time.Time) error { |
| ctx = context.WithValue(ctx, managedReadinessPassKey{}, &managedReadinessPass{}) |
| + ctx = s.managedPassClock(ctx, now) |
| + unprepared := map[string]bool{} |
| ops, boxes, err := s.store.ManagedWork(ctx) |
| if err != nil { |
| return errManagedWorker |
| @@ -155,6 +194,9 @@ func (s *Server) managedFleetsPass(ctx context.Context, now time.Time) error { |
| e = s.prepareManagedFleet(call, op, owned) |
| cancel() |
| if e != nil { |
| + // Credentials, for one, may be unusable: no reservation of this |
| + // operation dispatches until a later preparation succeeds. |
| + unprepared[op.ID] = true |
| continue |
| } |
| if len(owned) == 0 { |
| @@ -177,6 +219,7 @@ func (s *Server) managedFleetsPass(ctx context.Context, now time.Time) error { |
| if err != nil { |
| return errManagedWorker |
| } |
| + ctx = context.WithValue(ctx, managedUnpreparedKey{}, unprepared) |
| for _, b := range boxes { |
| if ctx.Err() != nil { |
| return ctx.Err() |
| @@ -314,6 +357,7 @@ func (s *Server) stepManagedBox(ctx context.Context, b managedBox, now time.Time |
| } |
| held := &managedHeldLock{fleet: b.Fleet, unlock: s.lockFleet(b.Fleet)} |
| defer func() { held.unlock() }() |
| + ctx = s.managedPassClock(ctx, now) |
| err := s.stepManagedBoxHeld(context.WithValue(ctx, managedHeldLockKey{}, held), b, now) |
| if errors.Is(err, errManagedStale) { |
| return nil |
| @@ -357,7 +401,11 @@ func (s *Server) stepManagedBoxHeld(ctx context.Context, b managedBox, now time. |
| if s.cfg.ManagedCompute == nil || b.Storage.Bucket == "" || b.Storage.Region == "" { |
| return nil |
| } |
| - // A fleet waiting for an operator launches nothing. |
| + // Nothing launches after this pass failed to prepare the operation, |
| + // nor for a fleet waiting for an operator. |
| + if unprepared, _ := ctx.Value(managedUnpreparedKey{}).(map[string]bool); unprepared[b.OpID] { |
| + return nil |
| + } |
| if waiting, err := s.managedFleetNeedsOperator(ctx, b); err != nil || waiting { |
| return err |
| } |
| @@ -705,13 +753,15 @@ func (s *Server) verifyManagedPublication(ctx context.Context, b managedBox, now |
| return err |
| } |
| if errors.Is(getErr, os.ErrNotExist) && !b.ReadyAt.IsZero() && b.ReadyAt.Before(b.LaunchStartedAt.Add(20*time.Minute)) { |
| - authorized := managedChecksFresh(b, now) |
| + // Age is judged on a fresh reading, after the GET, not the pass time. |
| + authorized := managedChecksFresh(b, s.managedCurrentTime(ctx, now)) |
| if !authorized { |
| if b, authorized, err = s.refreshManagedPublication(ctx, b, now); err != nil { |
| return err |
| } |
| } |
| - if authorized { |
| + // Judge again immediately before granting authority. |
| + if authorized && managedChecksFresh(b, s.managedCurrentTime(ctx, now)) { |
| body, marshalErr := json.Marshal(managedReadyObject{Fleet: b.Fleet, Label: b.Label, ReadyAt: b.ReadyAt, Op: b.OpID}) |
| if marshalErr != nil { |
| return errManagedWorker |
diff --git a/internal/console/managedworker_test.go b/internal/console/managedworker_test.go| index 2fc99d3a1..5fbd93fe0 100644 |
| --- a/internal/console/managedworker_test.go |
| +++ b/internal/console/managedworker_test.go |
| @@ -641,7 +641,7 @@ func restartManagedWorker(t *testing.T, s *Server) *Server { |
| } |
| t.Cleanup(func() { db.Close() }) |
| db.managedRegistry = managedRegistryPath(s.cfg.Registry) |
| - return &Server{store: db, cfg: s.cfg} |
| + return &Server{store: db, cfg: s.cfg, managedClock: s.managedClock} |
| } |
| func TestManagedPartialFailureSiblings(t *testing.T) { |
diff --git a/internal/console/server.go b/internal/console/server.go| index 3639f5299..cdb7cd490 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1018,6 +1018,7 @@ type Server struct { |
| managed managedConfigState |
| managedWorker managedWorkerState |
| managedExtra managedExtraChecks |
| + managedClock func() time.Time // nil: time.Now; tests inject a controlled clock |
| pdfTimeout time.Duration |
| pdfIdleTimeout time.Duration |
| pdfLimiter *pdfLimiter |