activator: held-leg admission, registry and synchronous cancellation (#432)
Human
Prompt
Task 1 of edge-held streams (#432): the activator half. Admit held legs with BeginSidecarRequest's decisions, register them per entry and generation under a.mu, cancel them synchronously at stop, generation switch and entry removal, and signal hosts that become admissible.
From this commit's own message. The prompt ledger has no entries for it — which is what a squashed, rebased or amended commit looks like, and what every commit looks like in a repo without a ledger.
Summary
new internal/activator/heldlegs.go with AdmitHeldLeg, HeldAdmissible, SetHeldWakeHook, the one predicate heldAdmissibleLocked and cancelHeldLegsLocked. BeginSidecarRequest and AdmitHeldLeg now share one loop (admitPassThrough) that admits exactly when the predicate holds. beginStopLocked cancels every leg first; installProcLocked cancels the outgoing generation's legs; every delete(a.entries, ...) cancels the removed entry's legs. The hook fires off a.mu after a successful wake, a recovery probe's release and every fence lift (LiftFence, LiftFenceAs, SeedExclusion.Release). New internal/edge/heldleg.go declares HeldLeg.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+736
−72
internal/activator/activator.go+30 −69internal/activator/heldlegs.go+251 −0internal/activator/heldlegs_test.go+419 −0internal/activator/maintenance.go+6 −2internal/activator/recoveryprobe.go+11 −0internal/activator/seed_exclusion.go+3 −1internal/activator/swaphold.go+2 −0internal/edge/heldleg.go+14 −0
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index 7440e30d1..7a06f7b55 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -533,6 +533,11 @@ type actEntry struct { |
| probeReviewing bool |
| probeObsolete bool |
| probeFence uint64 |
| + // heldLegs are the edge-held stream legs admitted on this entry |
| + // (heldlegs.go), by leg id. A stop, a generation switch and the |
| + // entry's removal cancel them (cancelHeldLegsLocked); a leg leaves at |
| + // its Done. Under a.mu. |
| + heldLegs map[uint64]*heldLeg |
| // bounceAfterWake is a Bounce that arrived while this INSTANCE was still |
| // waking. The wake had already read its config and execed its build, so |
| // the bounce's reason has not reached the child; wake() spends it the |
| @@ -1274,6 +1279,11 @@ type Service struct { |
| // a lapse turned off, which is never woken and does not stay running. |
| // A move's probe wake is never asked. |
| disabledFor atomic.Pointer[func(registry.Route) bool] |
| + // heldWakeHook is SetHeldWakeHook's function, called outside a.mu when |
| + // a host may have become admissible for held legs; heldLegSeq numbers |
| + // the legs (heldlegs.go). |
| + heldWakeHook atomic.Pointer[func(string)] |
| + heldLegSeq atomic.Uint64 |
| cfg Config |
| backend Backend |
| @@ -1895,75 +1905,9 @@ var errSidecarAsleep = errors.New("instance asleep; sidecar requests do not wake |
| // sleep) — and refuse, rather than wake, when the instance is asleep or |
| // stopping. |
| func (a *Service) BeginSidecarRequest(ctx context.Context, rt registry.Route) error { |
| - deadline := time.NewTimer(wakeWaitBound) |
| - defer deadline.Stop() |
| - if err := a.awaitStartup(ctx, deadline.C); err != nil { |
| - return err |
| - } |
| - for { |
| - a.mu.Lock() |
| - if a.fences[rt.Host] != 0 { |
| - a.mu.Unlock() |
| - return ErrFenced |
| - } |
| - e := a.entries[rt.Host] |
| - if e == nil || a.shuttingDown { |
| - // Shutting down: the stop is Shutdown's, and an exited child is |
| - // not recycled here (#292). |
| - a.mu.Unlock() |
| - return errSidecarAsleep |
| - } |
| - if e.probeHeld { |
| - a.mu.Unlock() |
| - return ErrFenced |
| - } |
| - switch e.state { |
| - case actAwake: |
| - // Same dead-child / lost-lease detection as a member request, but |
| - // the recovery stops at the stop: the loop then finds a stopping |
| - // (or absent) entry and turns this request away instead of |
| - // chaining into a re-wake. |
| - if repErr := servingError(e); repErr != nil || e.proc.Exited() { |
| - why := StopExited |
| - if repErr != nil { |
| - log.Printf("activator: LEASE LOST for %s (%v) — standing down", e.host, repErr) |
| - why = StopLeaseLost |
| - } else { |
| - log.Printf("activator: instance %s exited unexpectedly — recycling", e.host) |
| - e.unexpectedExit = true // the build's failure inside a first wake's observation (spec §6.4) |
| - } |
| - a.beginStopLocked(e, why) |
| - a.mu.Unlock() |
| - continue |
| - } |
| - a.mu.Unlock() |
| - return nil |
| - |
| - case actWaking: |
| - // Joining a wake someone else started is fine — the co-spawned |
| - // sidecar boots moments before its entry flips awake, so its first |
| - // dial can land in that sliver; joining can't initiate anything. |
| - // A failed wake just reads as asleep (the member path already |
| - // logged it). |
| - ready := e.ready |
| - a.mu.Unlock() |
| - select { |
| - case <-ready: |
| - if e.err != nil { |
| - return errSidecarAsleep |
| - } |
| - continue |
| - case <-ctx.Done(): |
| - return ctx.Err() |
| - case <-deadline.C: |
| - return errWakeTimeout |
| - } |
| - |
| - default: // actStopping — the stop exists to shed exactly this connection |
| - a.mu.Unlock() |
| - return errSidecarAsleep |
| - } |
| - } |
| + // The loop is shared with AdmitHeldLeg (heldlegs.go), whose admission |
| + // is this one plus a registered leg. |
| + return a.admitPassThrough(ctx, rt, nil) |
| } |
| // mesh seam: Eleven exposed hasLiveEntry(host) here — the mesh's "already |
| @@ -2120,6 +2064,7 @@ func (a *Service) wake(e *actEntry) { |
| outcome = w.stopOutcome |
| } |
| a.rememberStopLocked(e.host, outcome) |
| + a.cancelHeldLegsLocked(e, 0) |
| delete(a.entries, e.host) // next request retries from scratch |
| } else { |
| e.state = actAwake |
| @@ -2253,6 +2198,10 @@ func (a *Service) wake(e *actEntry) { |
| } |
| } |
| close(e.ready) |
| + if err == nil { |
| + // Held streams waiting on this host may open their legs now. |
| + a.noteHeldAdmissible(e.host) |
| + } |
| // A planned wake's outcome, for the scheduler: off a.mu, since OnGen |
| // reaches its goodMu, which calls back into Current. |
| a.afterWake(e, w, err) |
| @@ -3288,6 +3237,10 @@ const actStopTimeout = 20 * time.Second |
| // why (the Stop* reasons in cmd.go): a run the stop interrupts tells the |
| // member (run spec §5.3). |
| func (a *Service) beginStopLocked(e *actEntry, why string) { |
| + // Held legs end with the stop, in this critical section, before the |
| + // stop goroutine starts (edge-held streams spec §3.2): a leg is either |
| + // registered now and cancelled here, or admitted later and refused. |
| + a.cancelHeldLegsLocked(e, 0) |
| // A hold canary's settle ends with an intentional stop, before anything |
| // is stopped (zero-downtime spec §6.4). A process that already exited |
| // died of its build, and its stop must not hide that. |
| @@ -3338,6 +3291,13 @@ func (a *Service) installProcLocked(e *actEntry, rep Rep, proc Proc, g Gen) { |
| if rep != nil { |
| e.rep = rep |
| } |
| + if e.gen.N != g.N { |
| + // The generation that stops being current takes its held legs with |
| + // it, before the switch returns: a swap's successor installs here, |
| + // ahead of genRetired and the retiring generation's drain |
| + // (edge-held streams spec §3.2). |
| + a.cancelHeldLegsLocked(e, e.gen.N) |
| + } |
| e.proc = proc |
| e.gen = g |
| if e.lifecycleDone == nil { |
| @@ -5137,6 +5097,7 @@ func (a *Service) finishStop(e *actEntry, outcome *stopObservation) { |
| e.stopOutcome = outcome |
| a.rememberStopLocked(e.host, outcome) |
| republish := e.worker || a.publishesLocked(e) |
| + a.cancelHeldLegsLocked(e, 0) |
| delete(a.entries, e.host) |
| // A resident's stop, as it is forgotten (Plan 3 Task 8): a crash or a |
| // lost lease backs off; any other stop is restarted on the next tick. |
diff --git a/internal/activator/heldlegs.go b/internal/activator/heldlegs.go| new file mode 100644 |
| index 000000000..c52cff6ec |
| --- /dev/null |
| +++ b/internal/activator/heldlegs.go |
| @@ -0,0 +1,251 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "log" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// Held legs (edge-held streams spec §3.2, §3.5). The edge holds a client's |
| +// event stream open across the instance's sleep and swaps, and opens one |
| +// upstream leg at a time to whichever process is current. The activator |
| +// admits every leg, and registers it against the entry and the generation |
| +// it was admitted on, under a.mu, in the same step that decides it may run. |
| +// A stop (beginStopLocked), a generation switch (installProcLocked) and an |
| +// entry's removal cancel the registered legs under the same lock, so a leg |
| +// is either registered before the stop and cancelled by it, or admitted |
| +// after it and refused. A held leg is never activity: it does not count in |
| +// flight, does not stamp lastActive, and never starts a wake. |
| + |
| +// ErrHeldAsleep refuses a held leg for a host with no admissible instance: |
| +// asleep, stopping, or its child dead. Nothing was woken. |
| +var ErrHeldAsleep = errSidecarAsleep |
| + |
| +// heldLeg is one admitted leg. gen is the generation number it was admitted |
| +// on; ctx is derived from the admitting request's context and cancel ends it. |
| +type heldLeg struct { |
| + gen uint64 |
| + ctx context.Context |
| + cancel context.CancelFunc |
| + a *Service |
| + host string |
| + id uint64 |
| +} |
| + |
| +func (l *heldLeg) Context() context.Context { return l.ctx } |
| + |
| +// Done deregisters the leg and ends its context. Safe to call more than once. |
| +func (l *heldLeg) Done() { |
| + a := l.a |
| + a.mu.Lock() |
| + if e := a.entries[l.host]; e != nil && e.heldLegs[l.id] == l { |
| + delete(e.heldLegs, l.id) |
| + } |
| + a.mu.Unlock() |
| + l.cancel() |
| +} |
| + |
| +var _ edge.HeldLeg = (*heldLeg)(nil) |
| + |
| +// AdmitHeldLeg admits one upstream leg of a held stream for rt's host. Its |
| +// decisions are BeginSidecarRequest's (admitPassThrough): an admissible host |
| +// admits; a waking one is joined and decided again; asleep, stopping, |
| +// fenced, probe-held, shutting down or a dead child refuse with no wake. On |
| +// admit, under a.mu, the leg is registered on the entry with the current |
| +// generation number. It never calls begin and never touches inflight or |
| +// lastActive. |
| +func (a *Service) AdmitHeldLeg(ctx context.Context, rt registry.Route) (edge.HeldLeg, error) { |
| + var leg *heldLeg |
| + err := a.admitPassThrough(ctx, rt, func(e *actEntry) error { |
| + // awaitStartup answers nil without looking at ctx when there is no |
| + // startup gate; a leg is never registered on a context already done. |
| + if err := ctx.Err(); err != nil { |
| + return err |
| + } |
| + leg = a.registerHeldLegLocked(e, ctx) |
| + return nil |
| + }) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return leg, nil |
| +} |
| + |
| +// HeldAdmissible reports whether AdmitHeldLeg would admit a leg for host |
| +// without waiting (spec §3.5). In memory, under a.mu. |
| +func (a *Service) HeldAdmissible(host string) bool { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + return a.heldAdmissibleLocked(a.entries[host]) |
| +} |
| + |
| +// SetHeldWakeHook sets the function called, outside a.mu, when a host may |
| +// have become admissible: a wake completes, a recovery probe releases its |
| +// hold, a fence lifts. nil removes it. The hook must not block; a dropped |
| +// signal costs only latency. |
| +func (a *Service) SetHeldWakeHook(f func(host string)) { |
| + if f == nil { |
| + a.heldWakeHook.Store(nil) |
| + return |
| + } |
| + a.heldWakeHook.Store(&f) |
| +} |
| + |
| +// noteHeldAdmissible calls the held wake hook for host. The caller holds no |
| +// lock. |
| +func (a *Service) noteHeldAdmissible(host string) { |
| + if f := a.heldWakeHook.Load(); f != nil { |
| + (*f)(host) |
| + } |
| +} |
| + |
| +// heldAdmissibleLocked is the one admissibility predicate (spec §3.5): |
| +// startup recovery has finished, e is present and awake, its child alive, |
| +// its lease serving, the host unfenced, not probe-held, and the service not |
| +// shutting down. AdmitHeldLeg (and BeginSidecarRequest) admit exactly when |
| +// it is true; the stop a lost lease or a dead child starts is theirs, not |
| +// this predicate's. The caller holds a.mu. |
| +func (a *Service) heldAdmissibleLocked(e *actEntry) bool { |
| + if e == nil || !a.startupDone() || a.shuttingDown { |
| + return false |
| + } |
| + if a.fences[e.host] != 0 || e.probeHeld || e.state != actAwake { |
| + return false |
| + } |
| + if e.proc == nil || e.proc.Exited() || servingError(e) != nil { |
| + return false |
| + } |
| + return true |
| +} |
| + |
| +// startupDone reports, without waiting, what awaitStartup would: true when |
| +// it would return at once without error. |
| +func (a *Service) startupDone() bool { |
| + if a.Startup == nil { |
| + return true |
| + } |
| + select { |
| + case <-a.Startup: |
| + return a.lifeCtx == nil || a.lifeCtx.Err() == nil |
| + default: |
| + return false |
| + } |
| +} |
| + |
| +// registerHeldLegLocked records a leg on e, on e's current generation. The |
| +// caller holds a.mu. |
| +func (a *Service) registerHeldLegLocked(e *actEntry, ctx context.Context) *heldLeg { |
| + legCtx, cancel := context.WithCancel(ctx) |
| + l := &heldLeg{gen: e.gen.N, ctx: legCtx, cancel: cancel, a: a, host: e.host, id: a.heldLegSeq.Add(1)} |
| + if e.heldLegs == nil { |
| + e.heldLegs = make(map[uint64]*heldLeg) |
| + } |
| + e.heldLegs[l.id] = l |
| + return l |
| +} |
| + |
| +// cancelHeldLegsLocked cancels the legs registered on e: every leg when gen |
| +// is 0, otherwise only those admitted on generation gen. It only calls |
| +// cancel functions, so it never blocks; a leg leaves the registry at its |
| +// Done. The caller holds a.mu. |
| +func (a *Service) cancelHeldLegsLocked(e *actEntry, gen uint64) { |
| + for _, l := range e.heldLegs { |
| + if gen == 0 || l.gen == gen { |
| + l.cancel() |
| + } |
| + } |
| +} |
| + |
| +// admitPassThrough is the admission loop for traffic that passes through |
| +// to an awake instance without registering activity: sidecar-marked |
| +// requests (BeginSidecarRequest) and held legs (AdmitHeldLeg). It admits |
| +// exactly when heldAdmissibleLocked holds, calling onAdmit (when non-nil) |
| +// under a.mu before it unlocks; onAdmit's error refuses. Otherwise a lost |
| +// lease or a dead child starts a stop and the loop decides again (it then |
| +// finds a stopping or absent entry and refuses rather than chaining into a |
| +// re-wake), a waking entry is joined, and everything else is refused with |
| +// no wake. |
| +func (a *Service) admitPassThrough(ctx context.Context, rt registry.Route, onAdmit func(*actEntry) error) error { |
| + deadline := time.NewTimer(wakeWaitBound) |
| + defer deadline.Stop() |
| + if err := a.awaitStartup(ctx, deadline.C); err != nil { |
| + return err |
| + } |
| + for { |
| + a.mu.Lock() |
| + e := a.entries[rt.Host] |
| + if a.heldAdmissibleLocked(e) { |
| + var err error |
| + if onAdmit != nil { |
| + err = onAdmit(e) |
| + } |
| + a.mu.Unlock() |
| + return err |
| + } |
| + if a.fences[rt.Host] != 0 { |
| + a.mu.Unlock() |
| + return ErrFenced |
| + } |
| + if e == nil || a.shuttingDown { |
| + // Shutting down: the stop is Shutdown's, and an exited child is |
| + // not recycled here (#292). |
| + a.mu.Unlock() |
| + return errSidecarAsleep |
| + } |
| + if e.probeHeld { |
| + a.mu.Unlock() |
| + return ErrFenced |
| + } |
| + switch e.state { |
| + case actAwake: |
| + // Same dead-child / lost-lease detection as a member request, but |
| + // the recovery stops at the stop: the loop then finds a stopping |
| + // (or absent) entry and turns this request away instead of |
| + // chaining into a re-wake. |
| + if repErr := servingError(e); repErr != nil || e.proc == nil || e.proc.Exited() { |
| + why := StopExited |
| + if repErr != nil { |
| + log.Printf("activator: LEASE LOST for %s (%v) — standing down", e.host, repErr) |
| + why = StopLeaseLost |
| + } else { |
| + log.Printf("activator: instance %s exited unexpectedly — recycling", e.host) |
| + e.unexpectedExit = true // the build's failure inside a first wake's observation (spec §6.4) |
| + } |
| + a.beginStopLocked(e, why) |
| + a.mu.Unlock() |
| + continue |
| + } |
| + // Awake, serving, unfenced and not held, yet not admissible: |
| + // the service's lifetime ended after startup was awaited. |
| + a.mu.Unlock() |
| + return errStartupStopped |
| + |
| + case actWaking: |
| + // Joining a wake someone else started is fine — the co-spawned |
| + // sidecar boots moments before its entry flips awake, so its first |
| + // dial can land in that sliver; joining can't initiate anything. |
| + // A failed wake just reads as asleep (the member path already |
| + // logged it). |
| + ready := e.ready |
| + a.mu.Unlock() |
| + select { |
| + case <-ready: |
| + if e.err != nil { |
| + return errSidecarAsleep |
| + } |
| + continue |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + case <-deadline.C: |
| + return errWakeTimeout |
| + } |
| + |
| + default: // actStopping — the stop exists to shed exactly this connection |
| + a.mu.Unlock() |
| + return errSidecarAsleep |
| + } |
| + } |
| +} |
diff --git a/internal/activator/heldlegs_test.go b/internal/activator/heldlegs_test.go| new file mode 100644 |
| index 000000000..68db738d7 |
| --- /dev/null |
| +++ b/internal/activator/heldlegs_test.go |
| @@ -0,0 +1,419 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hostclaim" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// Held legs (edge-held streams spec §3.2, §3.5): the activator admits every |
| +// upstream leg of a held stream, registers it against the entry and the |
| +// generation it was admitted on, and cancels it synchronously with the stop |
| +// or the generation switch that would otherwise leave it running. |
| + |
| +func heldEntry(a *Service, host string) *actEntry { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + return a.entries[host] |
| +} |
| + |
| +func heldLegCount(a *Service, host string) int { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + if e := a.entries[host]; e != nil { |
| + return len(e.heldLegs) |
| + } |
| + return 0 |
| +} |
| + |
| +func TestAdmitHeldLegAsleepRefusesWithoutWake(t *testing.T) { |
| + t.Parallel() |
| + a, b, _, _ := testActivator(t, time.Hour) |
| + leg, err := a.AdmitHeldLeg(t.Context(), testRoute("shop.example.com")) |
| + if !errors.Is(err, ErrHeldAsleep) || leg != nil { |
| + t.Fatalf("AdmitHeldLeg asleep = %v, %v; want ErrHeldAsleep", leg, err) |
| + } |
| + if _, _, starts := b.counts(); starts != 0 { |
| + t.Fatalf("starts = %d, want 0: a held leg woke the host", starts) |
| + } |
| + if a.entryCount() != 0 { |
| + t.Fatal("a held leg created an entry") |
| + } |
| +} |
| + |
| +func TestAdmitHeldLegAwakeNoActivity(t *testing.T) { |
| + t.Parallel() |
| + a, _, clk, _ := testActivator(t, time.Hour) |
| + rt := testRoute("shop.example.com") |
| + arrangeAwake(t, a, rt) |
| + clk.advance(5 * time.Second) |
| + a.mu.Lock() |
| + e := a.entries[rt.Host] |
| + inflight, last := e.inflight, e.lastActive |
| + a.mu.Unlock() |
| + |
| + leg, err := a.AdmitHeldLeg(t.Context(), rt) |
| + if err != nil { |
| + t.Fatalf("AdmitHeldLeg awake: %v", err) |
| + } |
| + if leg.Context().Err() != nil { |
| + t.Fatalf("an admitted leg's context is already done: %v", leg.Context().Err()) |
| + } |
| + a.mu.Lock() |
| + gotInflight, gotLast, n := e.inflight, e.lastActive, len(e.heldLegs) |
| + a.mu.Unlock() |
| + if gotInflight != inflight || !gotLast.Equal(last) { |
| + t.Fatalf("held leg touched activity: inflight %d->%d lastActive %v->%v", inflight, gotInflight, last, gotLast) |
| + } |
| + if n != 1 { |
| + t.Fatalf("registered legs = %d, want 1", n) |
| + } |
| + leg.Done() |
| + if n := heldLegCount(a, rt.Host); n != 0 { |
| + t.Fatalf("registered legs after Done = %d, want 0", n) |
| + } |
| + leg.Done() // idempotent |
| +} |
| + |
| +func TestBeginStopCancelsHeldLegsBeforeStop(t *testing.T) { |
| + t.Parallel() |
| + a, b, clk, _ := testActivator(t, 10*time.Second) |
| + rt := testRoute("shop.example.com") |
| + arrangeAwake(t, a, rt) |
| + leg, err := a.AdmitHeldLeg(t.Context(), rt) |
| + if err != nil { |
| + t.Fatalf("AdmitHeldLeg: %v", err) |
| + } |
| + b.mu.Lock() |
| + p := b.procs[0] |
| + b.mu.Unlock() |
| + var mu sync.Mutex |
| + var atStop error |
| + stopped := false |
| + p.mu.Lock() |
| + p.onStopEnter = func() { |
| + mu.Lock() |
| + atStop, stopped = leg.Context().Err(), true |
| + mu.Unlock() |
| + } |
| + p.mu.Unlock() |
| + |
| + clk.advance(11 * time.Second) |
| + a.sweepOnce() |
| + waitFor(t, "hibernation", func() bool { return a.entryCount() == 0 }) |
| + mu.Lock() |
| + defer mu.Unlock() |
| + if !stopped { |
| + t.Fatal("the process was never stopped") |
| + } |
| + if !errors.Is(atStop, context.Canceled) { |
| + t.Fatalf("leg context at Proc.Stop = %v, want context.Canceled", atStop) |
| + } |
| +} |
| + |
| +func TestAdmitHeldLegAfterStopRefused(t *testing.T) { |
| + t.Parallel() |
| + a, b, _, _ := testActivator(t, time.Hour) |
| + rt := testRoute("shop.example.com") |
| + arrangeAwake(t, a, rt) |
| + gate := make(chan struct{}) |
| + t.Cleanup(func() { close(gate) }) |
| + b.mu.Lock() |
| + p := b.procs[0] |
| + b.mu.Unlock() |
| + p.mu.Lock() |
| + p.stopGate = gate |
| + p.mu.Unlock() |
| + a.mu.Lock() |
| + a.beginStopLocked(a.entries[rt.Host], StopIdle) |
| + a.mu.Unlock() |
| + if leg, err := a.AdmitHeldLeg(t.Context(), rt); !errors.Is(err, ErrHeldAsleep) || leg != nil { |
| + t.Fatalf("AdmitHeldLeg on a stopping host = %v, %v; want ErrHeldAsleep", leg, err) |
| + } |
| +} |
| + |
| +func TestHeldAdmissibleMatchesAdmit(t *testing.T) { |
| + t.Parallel() |
| + const host = "shop.example.com" |
| + closed := make(chan struct{}) |
| + close(closed) |
| + cases := []struct { |
| + name string |
| + awake bool // wake the host first |
| + startup <-chan struct{} // a.Startup, set before any wake |
| + after func(t *testing.T, a *Service, b *fakeBackend) // arrange the state |
| + want bool |
| + }{ |
| + {name: "asleep"}, |
| + {name: "awake", awake: true, want: true}, |
| + {name: "stopping", awake: true, after: func(t *testing.T, a *Service, b *fakeBackend) { |
| + gate := make(chan struct{}) |
| + t.Cleanup(func() { close(gate) }) |
| + b.mu.Lock() |
| + p := b.procs[0] |
| + b.mu.Unlock() |
| + p.mu.Lock() |
| + p.stopGate = gate |
| + p.mu.Unlock() |
| + a.mu.Lock() |
| + a.beginStopLocked(a.entries[host], StopIdle) |
| + a.mu.Unlock() |
| + }}, |
| + {name: "fenced", awake: true, after: func(t *testing.T, a *Service, _ *fakeBackend) { |
| + a.mu.Lock() |
| + if a.fences == nil { |
| + a.fences = map[string]uint64{} |
| + } |
| + a.fences[host] = 7 |
| + a.mu.Unlock() |
| + }}, |
| + {name: "probeHeld", awake: true, after: func(t *testing.T, a *Service, _ *fakeBackend) { |
| + a.mu.Lock() |
| + a.entries[host].probeHeld = true |
| + a.mu.Unlock() |
| + }}, |
| + {name: "replica error", awake: true, after: func(t *testing.T, a *Service, b *fakeBackend) { |
| + b.mu.Lock() |
| + r := b.reps[0] |
| + b.mu.Unlock() |
| + r.setErr(errors.New("lease lost")) |
| + }}, |
| + {name: "proc exited", awake: true, after: func(t *testing.T, a *Service, b *fakeBackend) { |
| + b.mu.Lock() |
| + p := b.procs[0] |
| + b.mu.Unlock() |
| + p.mu.Lock() |
| + p.dead = true |
| + p.mu.Unlock() |
| + }}, |
| + {name: "shutting down", awake: true, after: func(t *testing.T, a *Service, _ *fakeBackend) { |
| + a.mu.Lock() |
| + a.shuttingDown = true |
| + a.mu.Unlock() |
| + }}, |
| + {name: "Startup nil", awake: true, want: true}, |
| + {name: "Startup closed", awake: true, startup: closed, want: true}, |
| + {name: "Startup open", awake: true, after: func(t *testing.T, a *Service, _ *fakeBackend) { |
| + // Woken before the gate was set; the gate is not yet closed. |
| + a.Startup = make(chan struct{}) |
| + }}, |
| + } |
| + for _, c := range cases { |
| + t.Run(c.name, func(t *testing.T) { |
| + t.Parallel() |
| + a, b, _, _ := testActivator(t, time.Hour) |
| + if c.startup != nil { |
| + a.Startup = c.startup |
| + } |
| + rt := testRoute(host) |
| + if c.awake { |
| + arrangeAwake(t, a, rt) |
| + } |
| + if c.after != nil { |
| + c.after(t, a, b) |
| + } |
| + admissible := a.HeldAdmissible(host) |
| + ctx, cancel := context.WithTimeout(t.Context(), 100*time.Millisecond) |
| + defer cancel() |
| + start := time.Now() |
| + leg, err := a.AdmitHeldLeg(ctx, rt) |
| + took := time.Since(start) |
| + if leg != nil { |
| + defer leg.Done() |
| + } |
| + admitted := err == nil && took < 50*time.Millisecond |
| + if admissible != c.want { |
| + t.Errorf("HeldAdmissible = %v, want %v", admissible, c.want) |
| + } |
| + if admissible != admitted { |
| + t.Errorf("HeldAdmissible = %v but AdmitHeldLeg = %v after %v", admissible, err, took) |
| + } |
| + if err != nil && leg != nil { |
| + t.Errorf("a refused admission returned a leg") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestAdmitHeldLegCancelledContext(t *testing.T) { |
| + t.Parallel() |
| + a, _, _, _ := testActivator(t, time.Hour) |
| + rt := testRoute("shop.example.com") |
| + arrangeAwake(t, a, rt) |
| + ctx, cancel := context.WithCancel(t.Context()) |
| + cancel() |
| + leg, err := a.AdmitHeldLeg(ctx, rt) |
| + if !errors.Is(err, context.Canceled) || leg != nil { |
| + t.Fatalf("AdmitHeldLeg with a cancelled context = %v, %v; want context.Canceled", leg, err) |
| + } |
| + if n := heldLegCount(a, rt.Host); n != 0 { |
| + t.Fatalf("registered legs = %d, want 0", n) |
| + } |
| +} |
| + |
| +func TestInstallProcCancelsPreviousGenLegs(t *testing.T) { |
| + t.Parallel() |
| + a, b, _, _ := testActivator(t, time.Hour) |
| + a.gens = true |
| + rt := testRoute("shop.example.com") |
| + arrangeAwake(t, a, rt) |
| + old, err := a.AdmitHeldLeg(t.Context(), rt) |
| + if err != nil { |
| + t.Fatalf("AdmitHeldLeg on N: %v", err) |
| + } |
| + defer old.Done() |
| + |
| + a.mu.Lock() |
| + e := a.entries[rt.Host] |
| + n := e.gen.N |
| + succ := Gen{N: nextGen(), Socket: e.gen.Socket, Control: e.gen.Control} |
| + a.installProcLocked(e, nil, &fakeProc{label: "instance", rec: b}, succ) |
| + a.mu.Unlock() |
| + if n == 0 || succ.N == n { |
| + t.Fatalf("generations: old %d, successor %d", n, succ.N) |
| + } |
| + if !errors.Is(old.Context().Err(), context.Canceled) { |
| + t.Fatalf("leg on generation %d after the switch: %v, want context.Canceled", n, old.Context().Err()) |
| + } |
| + |
| + fresh, err := a.AdmitHeldLeg(t.Context(), rt) |
| + if err != nil { |
| + t.Fatalf("AdmitHeldLeg on N+1: %v", err) |
| + } |
| + defer fresh.Done() |
| + if fresh.Context().Err() != nil { |
| + t.Fatalf("a leg admitted after the switch is cancelled: %v", fresh.Context().Err()) |
| + } |
| + got := fresh.(*heldLeg).gen |
| + if got != succ.N { |
| + t.Fatalf("fresh leg registered on generation %d, want %d", got, succ.N) |
| + } |
| + |
| + // Re-installing the same generation (a worker's respawn under its |
| + // number) does not cancel that generation's legs. |
| + a.mu.Lock() |
| + a.installProcLocked(e, nil, e.proc, succ) |
| + a.mu.Unlock() |
| + if fresh.Context().Err() != nil { |
| + t.Fatalf("same-generation install cancelled its legs: %v", fresh.Context().Err()) |
| + } |
| +} |
| + |
| +func TestEntryRemovalCancelsHeldLegs(t *testing.T) { |
| + t.Parallel() |
| + obs := probeObserved(probeClaim(hostclaim.KindRestoring, hostclaim.PhaseProbing, "box")) |
| + a, _, _ := probeService(t, obs) |
| + p := probePolicy(probeInputs()) |
| + e := &actEntry{host: probeHost, route: registry.Route{Host: probeHost}, state: actWaking, ready: make(chan struct{}), recoveryPolicy: &p, probeHeld: true} |
| + a.mu.Lock() |
| + a.entries[probeHost] = e |
| + // No admission reaches a waking probe entry; the leg is registered |
| + // directly to pin the removal site's cancellation. |
| + leg := a.registerHeldLegLocked(e, t.Context()) |
| + a.mu.Unlock() |
| + if err := a.finishRecoveryProbe(e, 0, nil, errors.New("probe failed")); err == nil { |
| + t.Fatal("finishRecoveryProbe with a failure answered nil") |
| + } |
| + if a.Owns(probeHost) { |
| + t.Fatal("the failed probe's entry was kept") |
| + } |
| + if !errors.Is(leg.Context().Err(), context.Canceled) { |
| + t.Fatalf("leg on a removed entry: %v, want context.Canceled", leg.Context().Err()) |
| + } |
| +} |
| + |
| +func TestHeldWakeHookFires(t *testing.T) { |
| + t.Parallel() |
| + var mu sync.Mutex |
| + var got []string |
| + hook := func(host string) { |
| + mu.Lock() |
| + got = append(got, host) |
| + mu.Unlock() |
| + } |
| + seen := func() []string { |
| + mu.Lock() |
| + defer mu.Unlock() |
| + return append([]string(nil), got...) |
| + } |
| + count := func(host string) int { |
| + n := 0 |
| + for _, h := range seen() { |
| + if h == host { |
| + n++ |
| + } |
| + } |
| + return n |
| + } |
| + |
| + // A completed wake. |
| + a, _, _, _ := testActivator(t, time.Hour) |
| + a.SetHeldWakeHook(hook) |
| + rt := testRoute("shop.example.com") |
| + arrangeAwake(t, a, rt) |
| + if n := count(rt.Host); n != 1 { |
| + t.Fatalf("wake: hook saw %s %d times (%v), want 1", rt.Host, n, seen()) |
| + } |
| + |
| + // A fence lift. |
| + const fenced = "fenced.example.com" |
| + a.mu.Lock() |
| + if a.fences == nil { |
| + a.fences = map[string]uint64{} |
| + } |
| + a.fences[fenced] = 5 |
| + a.mu.Unlock() |
| + if !a.LiftFence(fenced, 5) { |
| + t.Fatal("LiftFence lifted nothing") |
| + } |
| + if n := count(fenced); n != 1 { |
| + t.Fatalf("fence lift: hook saw %s %d times (%v), want 1", fenced, n, seen()) |
| + } |
| + // A lift that lifts nothing says nothing. |
| + if a.LiftFence(fenced, 5) { |
| + t.Fatal("LiftFence lifted twice") |
| + } |
| + if n := count(fenced); n != 1 { |
| + t.Fatalf("a no-op lift fired the hook: %v", seen()) |
| + } |
| + |
| + // A recovery probe's release. |
| + obs := probeObserved(probeClaim(hostclaim.KindRestoring, hostclaim.PhaseProbing, "box")) |
| + admitted := probeAdmitted(obs) |
| + opened := probeAdmitted(obs) |
| + oc := *opened.Claim |
| + oc.Op.Phase = hostclaim.PhaseOpened |
| + opened.Claim = &oc |
| + pa, r, _ := probeService(t, obs) |
| + pa.SetHeldWakeHook(hook) |
| + e, _, _, err := heldProbe(t, pa, 0, admitted, probeInputs()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if n := count(probeHost); n != 0 { |
| + t.Fatalf("a held probe fired the hook: %v", seen()) |
| + } |
| + r.Read = func(context.Context, string) (hostclaim.Observed, error) { return opened, nil } |
| + pa.reviewRecoveryHold(e) |
| + if !pa.HeldAdmissible(probeHost) { |
| + t.Fatal("an opened probe is not admissible") |
| + } |
| + if n := count(probeHost); n != 1 { |
| + t.Fatalf("probe release: hook saw %s %d times (%v), want 1", probeHost, n, seen()) |
| + } |
| + |
| + // nil removes the hook. |
| + a.SetHeldWakeHook(nil) |
| + a.mu.Lock() |
| + a.fences[fenced] = 6 |
| + a.mu.Unlock() |
| + a.LiftFence(fenced, 6) |
| + if n := count(fenced); n != 1 { |
| + t.Fatalf("a removed hook fired: %v", seen()) |
| + } |
| +} |
diff --git a/internal/activator/maintenance.go b/internal/activator/maintenance.go| index 1c8054087..3c0f7ebf5 100644 |
| --- a/internal/activator/maintenance.go |
| +++ b/internal/activator/maintenance.go |
| @@ -226,12 +226,14 @@ func (a *Service) LiftFence(host string, generation uint64) bool { |
| return false |
| } |
| a.mu.Lock() |
| - defer a.mu.Unlock() |
| if a.seedExclusions[host] != nil || a.fences[host] != generation { |
| + a.mu.Unlock() |
| return false |
| } |
| delete(a.fences, host) |
| delete(a.fenceOwners, host) |
| + a.mu.Unlock() |
| + a.noteHeldAdmissible(host) // a fence lifted (edge-held streams spec §3.2) |
| return true |
| } |
| @@ -244,12 +246,14 @@ func (a *Service) LiftFenceAs(host string, generation uint64, owner string) bool |
| return false |
| } |
| a.mu.Lock() |
| - defer a.mu.Unlock() |
| if a.seedExclusions[host] != nil || a.fences[host] != generation || a.fenceOwners[host] != owner { |
| + a.mu.Unlock() |
| return false |
| } |
| delete(a.fences, host) |
| delete(a.fenceOwners, host) |
| + a.mu.Unlock() |
| + a.noteHeldAdmissible(host) // a fence lifted (edge-held streams spec §3.2) |
| return true |
| } |
diff --git a/internal/activator/recoveryprobe.go b/internal/activator/recoveryprobe.go| index 673679916..60e4fb24c 100644 |
| --- a/internal/activator/recoveryprobe.go |
| +++ b/internal/activator/recoveryprobe.go |
| @@ -218,6 +218,7 @@ func (a *Service) finishRecoveryProbe(e *actEntry, fence uint64, w *wokenInstanc |
| } |
| a.rememberStopLocked(e.host, outcome) |
| if a.entries[e.host] == e { |
| + a.cancelHeldLegsLocked(e, 0) |
| delete(a.entries, e.host) |
| } |
| a.mu.Unlock() |
| @@ -305,6 +306,15 @@ func (a *Service) reviewRecoveryHold(e *actEntry) { |
| fresh, err = r.Read(ctx, e.host) |
| cancel() |
| } |
| + // The hold's release (and the recovery fence's lift with it) is told to |
| + // held streams after a.mu is released: this defer runs after the |
| + // unlock deferred below (edge-held streams spec §3.2). |
| + released := false |
| + defer func() { |
| + if released { |
| + a.noteHeldAdmissible(e.host) |
| + } |
| + }() |
| a.mu.Lock() |
| defer a.mu.Unlock() |
| e.probeReviewing = false |
| @@ -342,6 +352,7 @@ func (a *Service) reviewRecoveryHold(e *actEntry) { |
| } |
| e.probeHeld = false |
| e.lastActive = a.now() |
| + released = true |
| } |
| } |
diff --git a/internal/activator/seed_exclusion.go b/internal/activator/seed_exclusion.go| index 8aa9eeced..db7c1c898 100644 |
| --- a/internal/activator/seed_exclusion.go |
| +++ b/internal/activator/seed_exclusion.go |
| @@ -86,11 +86,13 @@ func (t *SeedExclusion) Release() error { |
| } |
| a := t.service |
| a.mu.Lock() |
| - defer a.mu.Unlock() |
| if a.seedExclusions[t.host] != t || a.fences[t.host] != ^uint64(0) { |
| + a.mu.Unlock() |
| return ErrFenceHeld |
| } |
| delete(a.seedExclusions, t.host) |
| delete(a.fences, t.host) |
| + a.mu.Unlock() |
| + a.noteHeldAdmissible(t.host) // a fence lifted (edge-held streams spec §3.2) |
| return nil |
| } |
diff --git a/internal/activator/swaphold.go b/internal/activator/swaphold.go| index aab3cc7f3..8efaaa5a2 100644 |
| --- a/internal/activator/swaphold.go |
| +++ b/internal/activator/swaphold.go |
| @@ -362,6 +362,8 @@ func (a *Service) holdWakeLocked(e *actEntry, h *holdSpec) (*actEntry, error) { |
| next.pinCheck = func() error { return a.attemptCurrentLocked(next, h.at, h.newest, true) } |
| a.putEntryLocked(e.host, next) |
| if err := next.pinCheck(); err != nil { |
| + // The entry removed is next, the one just installed. |
| + a.cancelHeldLegsLocked(next, 0) |
| delete(a.entries, e.host) |
| return nil, err |
| } |
diff --git a/internal/edge/heldleg.go b/internal/edge/heldleg.go| new file mode 100644 |
| index 000000000..041b0cfe5 |
| --- /dev/null |
| +++ b/internal/edge/heldleg.go |
| @@ -0,0 +1,14 @@ |
| +package edge |
| + |
| +import "context" |
| + |
| +// HeldLeg is one upstream leg of an edge-held event stream, admitted by the |
| +// activator (edge-held streams spec §3.2). Context is derived from the |
| +// admitting request's context and is cancelled by the activator, under its |
| +// lock, when the instance stops or the generation the leg was admitted on |
| +// stops being current. Done deregisters the leg when it ends; it is safe to |
| +// call more than once. |
| +type HeldLeg interface { |
| + Context() context.Context |
| + Done() |
| +} |