hostedctl: proxy silence outbox per episode; stored deadlines
Task 4 review round 2. Each proxy_silent episode is its own durable outbox row (proxy key and episode start), so a later silence never overwrites an undelivered one, and each is marked delivered once the alerter takes it. Each proxy's silence deadline is stored in controller time, so a restart never moves it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+138
−68
docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+14 −0internal/hostedctl/ctlproxy/feed.go+42 −43internal/hostedctl/ctlproxy/feed_test.go+60 −10internal/hostedctl/proxy.go+5 −6internal/hostedctl/schema/0004_proxy.sql+16 −7internal/hostedctl/store.go+1 −2
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md| index 8a30428d..63c3d178 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -140,3 +140,17 @@ Mutation checks (each applied by script, then restored and checked byte for byte |
| A first rejected attempt at 17 (widening `Delivered`'s UPDATE) passed, since it only acts after a successful delivery; it is not a guard and was replaced by the mutation above. |
| Also run: `go test ./internal/hostedcert ./internal/hostedctl/... ./internal/hostedclient ./internal/hostedwire ./cmd/equipo-hosted-controller -count=1` ok (hostedctl 10.6 s and 16.9 s on a box at load average 21 to 40; 8.3 s before at low load); `go vet -tags hostedlive` ok; staticcheck v0.7.0 ok; `make budget build vet` ok after raising the `internal/hostedctl` record to 5689/9355. One full run before the fix hit `TestReapLoopRunsPassesUntilDone: read unmatched_vms = ... cannot start a transaction within a transaction` under that load; `-run TestReapLoopRunsPassesUntilDone -count=200` then passed. It cancels the loop mid-pass and is untouched by this task. |
| + |
| +### Task 4 review round 2 (t4-r2.md: finding 3's two gaps) |
| + |
| +(a) Each silence episode is its own row in a durable outbox, `proxy_silences`, keyed by the proxy key and the episode's start (its deadline less 3 minutes), with `raised_t` and `delivered`. `MarkSilent` inserts the episode (`ON CONFLICT DO NOTHING`), so a later silence never replaces an undelivered earlier one; `Pending` drains the outbox oldest first and `Delivered` marks one episode once the alerter has taken it. The alert's detail names the episode (`episode <key>@<start ns>`), so a repeat after a crash between delivery and marking (the one way a row is sent twice) can be told from a new silence. |
| +(b) `proxy_polls.deadline_t` stores each key's silence deadline in controller time: a feed request sets it to now plus 3 minutes; a key that never asked gets one from the first pass that watches it. `MarkSilent` compares controller time with it and nothing else, so a restart never moves it, and downtime is not exempt. The round 1 `alert_pending`/`alerted_t` columns and `Store.lastRun` are gone. Both changes are in the unreleased `0004_proxy.sql`. |
| + |
| +Tests: TestProxySilentEpisodesKeptApart (alerter down; proxy-1 silent, polls, silent again; restart; the three episodes `proxy-1@0`, `proxy-2@0`, `proxy-1@180000000000` each delivered once, then none), TestProxySilentRestartKeepsDeadline (restart at 2 min 59 s; the alert comes at 3 min), and TestProxySilentOverdueAtStartup now wants both proxies alerted on the first pass after a restart with 10 minutes down. |
| + |
| +Mutation checks (each applied by script, then restored and checked byte for byte): |
| + |
| +21. Episodes share one identity per key (`INSERT OR REPLACE INTO proxy_silences ... VALUES (?, 0 * ?, ?)`, `ctlproxy/feed.go`). Command: `CGO_ENABLED=0 go test ./internal/hostedctl/ctlproxy -run 'TestProxySilentEpisodesKeptApart' -count=1`. Observed: FAIL, `feed_test.go:411: proxy_silent alerts after the restart = ["proxy proxy-2 ... (episode proxy-2@0)" "proxy proxy-1 ... (episode proxy-1@0)"], want one each for [...]` (proxy-1's first episode was replaced). Restored. |
| +22. A restart restarts the allowance (MarkSilent takes `OpenedAt` and waits until `max(deadline, OpenedAt + SilentAfter)`; `feed.go` and `proxy.go`). Command: `... -run 'TestProxySilentRestartKeepsDeadline|TestProxySilentOverdueAtStartup' -count=1`. Observed: FAIL, `feed_test.go:377: proxy_silent alerts = [], want one each for [proxy-1 proxy-2]` and `feed_test.go:361: proxy_silent alerts = [], want one each for [proxy-1 proxy-2]`. Restored. |
| + |
| +Also run: `go test ./internal/hostedctl/... -run 'TestRedeem|TestCertCapped|TestRenew|TestStopRevokes|TestFeed|TestProxyRole|TestProxySilent|TestVMList|TestProxyCodeKey|TestReplaySends' -count=1` ok; `go test ./internal/hostedcert ./internal/hostedctl/... ./internal/hostedclient ./internal/hostedwire ./cmd/equipo-hosted-controller -count=1` ok (hostedctl 12.4 s at load average 14 to 25); staticcheck v0.7.0 on `./internal/hostedctl/...` ok; `make budget build vet` ok within the existing 5689/9355 record. |
diff --git a/internal/hostedctl/ctlproxy/feed.go b/internal/hostedctl/ctlproxy/feed.go| index 8d58a9af..7225a9c3 100644 |
| --- a/internal/hostedctl/ctlproxy/feed.go |
| +++ b/internal/hostedctl/ctlproxy/feed.go |
| @@ -34,8 +34,9 @@ const ( |
| // lists the services snapshot saved with its intent. The API signs the |
| // response with the controller's key, bound to the proxy's request. |
| func Feed(ctx context.Context, tx *sql.Tx, by hostedwire.KeyID, now time.Duration) (hostedwire.ProxyFeed, error) { |
| - if _, err := tx.ExecContext(ctx, `INSERT INTO proxy_polls (key_id, last_t, silent_alerted) VALUES (?, ?, 0) |
| - ON CONFLICT (key_id) DO UPDATE SET last_t = excluded.last_t, silent_alerted = 0`, string(by), int64(now)); err != nil { |
| + if _, err := tx.ExecContext(ctx, `INSERT INTO proxy_polls (key_id, last_t, deadline_t, silent_alerted) VALUES (?, ?, ?, 0) |
| + ON CONFLICT (key_id) DO UPDATE SET last_t = excluded.last_t, deadline_t = excluded.deadline_t, silent_alerted = 0`, |
| + string(by), int64(now), int64(now+SilentAfter)); err != nil { |
| return hostedwire.ProxyFeed{}, fmt.Errorf("ctlproxy: record feed request: %w", err) |
| } |
| f := hostedwire.ProxyFeed{Version: FeedVersion, IssuedNS: int64(now), TTLMS: FeedLifetime.Milliseconds(), |
| @@ -92,59 +93,58 @@ func column(ctx context.Context, tx *sql.Tx, q string, args ...any) ([]string, e |
| return out, rows.Err() |
| } |
| -// MarkSilent opens a silence episode for each of proxies that has not |
| -// asked for the feed for SilentAfter or more at now and has no open |
| -// episode: it is marked alerted, with its alert pending delivery (Pending, |
| -// Delivered), so each silence raises one alert, and a restart neither loses |
| -// it nor raises it again. A key's next feed request closes the episode. |
| -// |
| -// The allowance runs from the key's last request. Across a restart, the |
| -// time the controller was down does not count against a proxy (it could not |
| -// ask), so the allowance restarts at opened, the controller's start, unless |
| -// the episode was already overdue at lastRun, the last controller time the |
| -// previous run recorded: then its deadline stands. A key that never asked |
| -// counts from opened. |
| -func MarkSilent(ctx context.Context, tx *sql.Tx, proxies []hostedwire.KeyID, now, opened, lastRun time.Duration) error { |
| +// MarkSilent opens a silence episode for each of proxies whose silence |
| +// deadline (its last feed request plus SilentAfter, in controller time) has |
| +// come at now and whose current silence has none yet: one outbox row, |
| +// identified by the key and the episode's start, which Pending and |
| +// Delivered drain. The deadline is stored, so a restart never moves it; a |
| +// key that never asked gets one SilentAfter from the first pass that |
| +// watches it. A key's next feed request sets a new deadline and ends the |
| +// silence; its earlier episodes stay in the outbox until delivered. |
| +func MarkSilent(ctx context.Context, tx *sql.Tx, proxies []hostedwire.KeyID, now time.Duration) error { |
| for _, id := range proxies { |
| - var last sql.NullInt64 |
| - var alerted bool |
| - err := tx.QueryRowContext(ctx, `SELECT last_t, silent_alerted FROM proxy_polls WHERE key_id = ?`, string(id)).Scan(&last, &alerted) |
| - if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| - return fmt.Errorf("ctlproxy: read last feed request of %s: %w", id, err) |
| + if _, err := tx.ExecContext(ctx, `INSERT INTO proxy_polls (key_id, deadline_t) VALUES (?, ?) |
| + ON CONFLICT (key_id) DO NOTHING`, string(id), int64(now+SilentAfter)); err != nil { |
| + return fmt.Errorf("ctlproxy: watch %s: %w", id, err) |
| } |
| - from := opened |
| - if last.Valid { |
| - from = time.Duration(last.Int64) |
| - if from+SilentAfter > lastRun { // not overdue before the restart |
| - from = max(from, opened) |
| - } |
| + var deadline int64 |
| + var alerted bool |
| + if err := tx.QueryRowContext(ctx, `SELECT deadline_t, silent_alerted FROM proxy_polls WHERE key_id = ?`, |
| + string(id)).Scan(&deadline, &alerted); err != nil { |
| + return fmt.Errorf("ctlproxy: read the silence deadline of %s: %w", id, err) |
| } |
| - if alerted || now-from < SilentAfter { |
| + if alerted || now < time.Duration(deadline) { |
| continue |
| } |
| - if _, err := tx.ExecContext(ctx, `INSERT INTO proxy_polls (key_id, silent_alerted, alert_pending, alerted_t) VALUES (?, 1, 1, ?) |
| - ON CONFLICT (key_id) DO UPDATE SET silent_alerted = 1, alert_pending = 1, alerted_t = excluded.alerted_t`, |
| - string(id), int64(now)); err != nil { |
| + if _, err := tx.ExecContext(ctx, `INSERT INTO proxy_silences (key_id, started_t, raised_t) VALUES (?, ?, ?) |
| + ON CONFLICT (key_id, started_t) DO NOTHING`, string(id), deadline-int64(SilentAfter), int64(now)); err != nil { |
| + return fmt.Errorf("ctlproxy: queue the silence of %s: %w", id, err) |
| + } |
| + if _, err := tx.ExecContext(ctx, `UPDATE proxy_polls SET silent_alerted = 1 WHERE key_id = ?`, string(id)); err != nil { |
| return fmt.Errorf("ctlproxy: mark %s silent: %w", id, err) |
| } |
| } |
| return nil |
| } |
| -// Silence is one proxy_silent alert waiting for delivery. |
| +// Silence is one proxy_silent episode in the outbox: Key fell silent at |
| +// Since (controller time), and the episode was raised at At. |
| type Silence struct { |
| - Key hostedwire.KeyID |
| - At time.Duration // when the episode was raised, controller time |
| + Key hostedwire.KeyID |
| + Since, At time.Duration |
| } |
| -// Detail is the alert's text. |
| +// Detail is the alert's text. It names the episode (key and start), so |
| +// a repeat delivery after a crash can be told from a new silence. |
| func (s Silence) Detail() string { |
| - return fmt.Sprintf("proxy %s has not asked for the launch feed for %v or more", s.Key, SilentAfter) |
| + return fmt.Sprintf("proxy %s has not asked for the launch feed since controller time %v (%v or more; episode %s@%d)", |
| + s.Key, s.Since, SilentAfter, s.Key, int64(s.Since)) |
| } |
| -// Pending returns the silences whose alert has not been delivered, by key. |
| +// Pending returns the episodes not yet delivered, oldest first. |
| func Pending(ctx context.Context, tx *sql.Tx) ([]Silence, error) { |
| - rows, err := tx.QueryContext(ctx, `SELECT key_id, alerted_t FROM proxy_polls WHERE alert_pending = 1 ORDER BY key_id`) |
| + rows, err := tx.QueryContext(ctx, `SELECT key_id, started_t, raised_t FROM proxy_silences WHERE delivered = 0 |
| + ORDER BY raised_t, key_id, started_t`) |
| if err != nil { |
| return nil, fmt.Errorf("ctlproxy: read pending silence alerts: %w", err) |
| } |
| @@ -152,7 +152,7 @@ func Pending(ctx context.Context, tx *sql.Tx) ([]Silence, error) { |
| var out []Silence |
| for rows.Next() { |
| var s Silence |
| - if err := rows.Scan(&s.Key, &s.At); err != nil { |
| + if err := rows.Scan(&s.Key, &s.Since, &s.At); err != nil { |
| return nil, fmt.Errorf("ctlproxy: read pending silence alerts: %w", err) |
| } |
| out = append(out, s) |
| @@ -160,12 +160,11 @@ func Pending(ctx context.Context, tx *sql.Tx) ([]Silence, error) { |
| return out, rows.Err() |
| } |
| -// Delivered records that s's alert was delivered. A later episode of the |
| -// same key, raised since, stays pending. |
| +// Delivered records that episode s was delivered. |
| func Delivered(ctx context.Context, tx *sql.Tx, s Silence) error { |
| - if _, err := tx.ExecContext(ctx, `UPDATE proxy_polls SET alert_pending = 0 WHERE key_id = ? AND alerted_t = ?`, |
| - string(s.Key), int64(s.At)); err != nil { |
| - return fmt.Errorf("ctlproxy: mark the silence alert of %s delivered: %w", s.Key, err) |
| + if _, err := tx.ExecContext(ctx, `UPDATE proxy_silences SET delivered = 1 WHERE key_id = ? AND started_t = ?`, |
| + string(s.Key), int64(s.Since)); err != nil { |
| + return fmt.Errorf("ctlproxy: mark the silence of %s delivered: %w", s.Key, err) |
| } |
| return nil |
| } |
diff --git a/internal/hostedctl/ctlproxy/feed_test.go b/internal/hostedctl/ctlproxy/feed_test.go| index 4a089f48..cab085ef 100644 |
| --- a/internal/hostedctl/ctlproxy/feed_test.go |
| +++ b/internal/hostedctl/ctlproxy/feed_test.go |
| @@ -346,10 +346,10 @@ func TestProxySilentAlertSurvivesRestart(t *testing.T) { |
| e.reapAlerts() |
| } |
| -// TestProxySilentOverdueAtStartup: a restart does not give back the |
| -// allowance of a silence already overdue before it, but does give a full |
| -// one to a proxy whose allowance ran out only while the controller was |
| -// down. |
| +// TestProxySilentOverdueAtStartup: silence deadlines are stored in |
| +// controller time, so a restart neither forgets nor moves them: every |
| +// proxy whose deadline passed, before the restart or while the controller |
| +// was down, is alerted by the first pass after it. |
| func TestProxySilentOverdueAtStartup(t *testing.T) { |
| t.Parallel() |
| e := newEnv(t) |
| @@ -357,15 +357,65 @@ func TestProxySilentOverdueAtStartup(t *testing.T) { |
| e.advance(time.Minute) |
| e.poll(idProxy2, keyProxy2) // deadline 4m |
| e.advance(2*time.Minute + 30*time.Second) |
| - if err := e.store.Checkpoint(e.ctx); err != nil { // the run ends at 3m30 with no reaper pass since 0 |
| - t.Fatal(err) |
| - } |
| - e.restart(10 * time.Minute) |
| - e.reapAlerts(idProxy) |
| + e.restart(10 * time.Minute) // no reaper pass ran before it |
| + e.reapAlerts(idProxy, idProxy2) |
| + e.reapAlerts() |
| +} |
| + |
| +// TestProxySilentRestartKeepsDeadline: a restart just before a silence's |
| +// deadline does not move it. |
| +func TestProxySilentRestartKeepsDeadline(t *testing.T) { |
| + t.Parallel() |
| + e := newEnv(t) |
| + e.poll(idProxy, keyProxy) |
| + e.poll(idProxy2, keyProxy2) |
| e.advance(ctlproxy.SilentAfter - time.Second) |
| e.reapAlerts() |
| + e.restart(0) |
| + e.reapAlerts() |
| e.advance(time.Second) |
| - e.reapAlerts(idProxy2) |
| + e.reapAlerts(idProxy, idProxy2) |
| +} |
| + |
| +// TestProxySilentEpisodesKeptApart: two silences of one proxy while the |
| +// alerter is down are two episodes; after a restart each is delivered |
| +// exactly once. |
| +func TestProxySilentEpisodesKeptApart(t *testing.T) { |
| + t.Parallel() |
| + e := newEnv(t) |
| + e.alerts.setFail(true) |
| + e.poll(idProxy, keyProxy) |
| + e.poll(idProxy2, keyProxy2) |
| + e.advance(ctlproxy.SilentAfter) |
| + if _, err := e.c.Reap(e.ctx); err == nil { |
| + t.Fatal("Reap with the alerter down = nil, want the failed delivery") |
| + } |
| + e.poll(idProxy, keyProxy) // ends proxy-1's first silence |
| + e.advance(ctlproxy.SilentAfter) |
| + if _, err := e.c.Reap(e.ctx); err == nil { |
| + t.Fatal("second Reap with the alerter down = nil, want the failed delivery") |
| + } |
| + |
| + e.restart(time.Minute) |
| + e.alerts.setFail(false) |
| + if _, err := e.c.Reap(e.ctx); err != nil { |
| + t.Fatalf("Reap = %v", err) |
| + } |
| + got := e.alerts.take(ctlproxy.AlertProxySilent) |
| + var details []string |
| + for _, a := range got { |
| + details = append(details, a.Detail) |
| + } |
| + want := []string{"episode proxy-1@0)", "episode proxy-2@0)", "episode proxy-1@180000000000)"} |
| + if len(got) != len(want) { |
| + t.Fatalf("proxy_silent alerts after the restart = %q, want one each for %q", details, want) |
| + } |
| + for i, w := range want { |
| + if !strings.HasSuffix(details[i], w) { |
| + t.Fatalf("proxy_silent alerts after the restart = %q, want one each for %q", details, want) |
| + } |
| + } |
| + e.reapAlerts() |
| } |
| // TestVMListDoesNotOpenCodeWindow: the operator's VM list may show the VM |
diff --git a/internal/hostedctl/proxy.go b/internal/hostedctl/proxy.go| index b9367815..3bfb5e98 100644 |
| --- a/internal/hostedctl/proxy.go |
| +++ b/internal/hostedctl/proxy.go |
| @@ -86,10 +86,10 @@ func (c *Controller) watchProxies(keys map[hostedwire.KeyID]hostedwire.VerifyKey |
| } |
| // checkProxies opens a silence episode (ctlproxy.MarkSilent) for each |
| -// configured proxy silent for ctlproxy.SilentAfter, then delivers every |
| -// ctlproxy.AlertProxySilent alert still pending, this run's or an earlier |
| -// run's, marking each delivered only once the alerter took it. One the |
| -// alerter refuses stays pending for the next pass. |
| +// configured proxy past its silence deadline, then delivers every |
| +// ctlproxy.AlertProxySilent episode still in the outbox, this run's or an |
| +// earlier run's, marking each delivered only once the alerter took it. One |
| +// the alerter refuses stays in the outbox for the next pass. |
| func (c *Controller) checkProxies(ctx context.Context) error { |
| var ids []hostedwire.KeyID |
| if p := c.proxies.Load(); p != nil { |
| @@ -97,8 +97,7 @@ func (c *Controller) checkProxies(ctx context.Context) error { |
| } |
| var pending []ctlproxy.Silence |
| err := c.store.Tx(ctx, func(tx *sql.Tx) error { |
| - err := ctlproxy.MarkSilent(ctx, tx, ids, time.Duration(c.store.Clock().Now()), time.Duration(c.store.OpenedAt()), |
| - time.Duration(c.store.lastRun)) |
| + err := ctlproxy.MarkSilent(ctx, tx, ids, time.Duration(c.store.Clock().Now())) |
| if err == nil { |
| pending, err = ctlproxy.Pending(ctx, tx) |
| } |
diff --git a/internal/hostedctl/schema/0004_proxy.sql b/internal/hostedctl/schema/0004_proxy.sql| index d51708cf..aeacf466 100644 |
| --- a/internal/hostedctl/schema/0004_proxy.sql |
| +++ b/internal/hostedctl/schema/0004_proxy.sql |
| @@ -37,15 +37,24 @@ CREATE TABLE proxy_certs ( |
| CREATE INDEX proxy_certs_attempt ON proxy_certs(attempt_id); |
| CREATE INDEX proxy_certs_revoked ON proxy_certs(not_after_t) WHERE revoked_t IS NOT NULL; |
| --- Each proxy key's last feed request, and its silence episode: |
| --- proxy_silent is raised once per silence (silent_alerted), and stays |
| --- pending (alert_pending) until the alerter takes it, across restarts. |
| +-- Each proxy key's last feed request and its silence deadline, in |
| +-- controller time, which survives restarts: a restart never moves it. |
| CREATE TABLE proxy_polls ( |
| key_id TEXT PRIMARY KEY, |
| - last_t INTEGER, -- absent for a key alerted before it ever asked |
| - silent_alerted INTEGER NOT NULL DEFAULT 0 CHECK (silent_alerted IN (0, 1)), |
| - alert_pending INTEGER NOT NULL DEFAULT 0 CHECK (alert_pending IN (0, 1)), |
| - alerted_t INTEGER -- when the current episode was raised; absent before any |
| + last_t INTEGER, -- absent for a key that has never asked |
| + deadline_t INTEGER NOT NULL, -- last_t plus 3 minutes; for a key that never asked, from when the controller first watched it |
| + silent_alerted INTEGER NOT NULL DEFAULT 0 CHECK (silent_alerted IN (0, 1)) -- the current silence has its episode |
| +); |
| + |
| +-- The proxy_silent outbox: one row per silence episode, identified by the |
| +-- proxy key and the episode's start (its deadline less 3 minutes), kept |
| +-- until the alerter takes it. A later episode never replaces an earlier. |
| +CREATE TABLE proxy_silences ( |
| + key_id TEXT NOT NULL, |
| + started_t INTEGER NOT NULL, |
| + raised_t INTEGER NOT NULL, |
| + delivered INTEGER NOT NULL DEFAULT 0 CHECK (delivered IN (0, 1)), |
| + PRIMARY KEY (key_id, started_t) |
| ); |
| -- The last feed serial: one row. Each feed takes the next. |
diff --git a/internal/hostedctl/store.go b/internal/hostedctl/store.go| index fa833636..e621d7bd 100644 |
| --- a/internal/hostedctl/store.go |
| +++ b/internal/hostedctl/store.go |
| @@ -65,7 +65,6 @@ type Store struct { |
| host isolatedjob.Clock |
| clock *CtlClock |
| restarted bool |
| - lastRun T // the checkpoint Open found: the last controller time the previous run recorded (0 when fresh) |
| mu sync.Mutex |
| pending []outboxAlert // undelivered rows of alert_outbox, oldest first |
| @@ -248,7 +247,7 @@ func (s *Store) restoreClock(ctx context.Context) error { |
| return fmt.Errorf("hostedctl: restore clock: %w", err) |
| } |
| s.clock = &CtlClock{base: base, monoAtOpen: monoNow, c: s.host} |
| - s.restarted, s.lastRun = restarted, T(cpT) |
| + s.restarted = restarted |
| s.pending = pending |
| return nil |
| } |