carlos / platform Public

host: the agent nudges root after an egress column changes (#328)

egressNudgeLoop polls the registry's SnapshotFingerprint every
edgesFileWatchInterval (Fingerprint leaves both policy columns out and
never moves on a grant or revoke) and sends POST /egress?host= for each
host whose egress_allow differs from what root last heard. A host first
seen with an allow counts as changed; a failed call is logged, throttled,
and sent again on the next pass. Promptness only: root's 30 s loop is the
guarantee. Local registry and root socket only, no store request.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev d1c4b1c0af5bf1e89a97eb14576829f177df57ee parent 4f8d9e1
3 files changed, +445 −1
  • internal/host/agent.go +5 −1
  • internal/host/egress_nudge.go +152 −0
  • internal/host/egress_nudge_test.go +288 −0
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 00139089b..0b19d9d3e 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -453,7 +453,11 @@ func runAgent(args []string, buildClaims ClaimFactory) {
// journal check and the peer list both read this SAME registry
// handle, so a nested row's classification here always agrees with
// what the rest of this process already knows about the box.
- eb.Control = instancectl.NewClient(controlsock.Path)
+ ctl := instancectl.NewClient(controlsock.Path)
+ eb.Control = ctl
+ // A grant or revoke the agent converged into the registry reaches
+ // root on the next 2 s beat rather than root's 30 s loop (#328).
+ go egressNudgeLoop(agentCtx, reg, ctl)
eb.LayoutFacts = activator.LayoutInputs{
DataDir: dd,
// A journal that cannot be read is not proof there isn't one: an
diff --git a/internal/host/egress_nudge.go b/internal/host/egress_nudge.go
new file mode 100644
index 000000000..31348ab3c
--- /dev/null
+++ b/internal/host/egress_nudge.go
@@ -0,0 +1,152 @@
+package host
+
+import (
+ "context"
+ "log"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// egressNudgeLoop tells root about an egress allow change as soon as the
+// registry holds it (#328): every edgesFileWatchInterval it reads the
+// registry's SnapshotFingerprint and, when that moved, lists the rows and
+// sends POST /egress?host= for each host whose egress_allow changed.
+//
+// It watches SnapshotFingerprint, not Fingerprint: the policy columns
+// (egress_allow, policy_expires_at) are kept out of Fingerprint, so a grant
+// or a revoke alone would never move it.
+//
+// This is promptness only. Root re-asserts every populated slice on its
+// own 30 s loop and on every start path, so a nudge that fails, or an agent
+// that crashes before sending one, delays a change and loses nothing. It
+// reads the local registry and talks to root's socket: no store request.
+func egressNudgeLoop(ctx context.Context, reg *registry.Registry, c interface {
+ Egress(context.Context, string) error
+}) {
+ n := newEgressNudger(c)
+ log.Printf("agent: egress nudge armed (%s after a registry change)", edgesFileWatchInterval)
+ tick := time.NewTicker(edgesFileWatchInterval)
+ defer tick.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-tick.C:
+ n.tick(ctx, reg)
+ }
+ }
+}
+
+// egressNudgeRegistry is what the loop's step reads; *registry.Registry
+// satisfies it.
+type egressNudgeRegistry interface {
+ SnapshotFingerprint() (string, error)
+ List() ([]registry.Route, error)
+}
+
+// egressNudger is the loop's state. One goroutine owns it.
+type egressNudger struct {
+ c interface {
+ Egress(context.Context, string) error
+ }
+ logf func(format string, args ...any)
+
+ // nudged is each host's egress_allow as root last heard of it (or,
+ // for a host first seen with none, as first seen). failing holds the
+ // hosts whose last call failed: each is sent again on the next pass,
+ // whatever its column holds by then.
+ nudged map[string]string
+ failing map[string]bool
+ fp string
+ haveFP bool
+ // Failure counts, throttled the way edgesFileLoop counts its own.
+ regErrs, callErrs int
+}
+
+func newEgressNudger(c interface {
+ Egress(context.Context, string) error
+}) *egressNudger {
+ return &egressNudger{c: c, logf: log.Printf, nudged: map[string]string{}, failing: map[string]bool{}}
+}
+
+// tick is one beat of the loop: a pass when the snapshot fingerprint moved
+// since the last listed one (the first read always counts).
+func (n *egressNudger) tick(ctx context.Context, reg egressNudgeRegistry) {
+ fp, err := reg.SnapshotFingerprint()
+ if err != nil {
+ n.regErr("registry poll", err)
+ return
+ }
+ if n.haveFP && fp == n.fp {
+ return
+ }
+ rows, err := reg.List()
+ if err != nil {
+ n.regErr("registry list", err)
+ return
+ }
+ n.regErrs = 0
+ // The fingerprint read before the list: a write between the two moves
+ // it again, and the next tick lists once more.
+ n.fp, n.haveFP = fp, true
+ n.pass(ctx, rows)
+}
+
+// pass sends POST /egress for each row whose egress_allow differs from
+// what root last heard. A host first seen with an allow counts as changed;
+// one first seen with none does not. A failed call is logged (throttled)
+// and sent again on the next pass. Hosts no longer listed are forgotten.
+func (n *egressNudger) pass(ctx context.Context, rows []registry.Route) {
+ listed := make(map[string]bool, len(rows))
+ failed := false
+ for _, rt := range rows {
+ if ctx.Err() != nil {
+ return
+ }
+ if listed[rt.Host] {
+ continue
+ }
+ listed[rt.Host] = true
+ prev, known := n.nudged[rt.Host]
+ switch {
+ case n.failing[rt.Host]:
+ case !known && rt.EgressAllow == "":
+ n.nudged[rt.Host] = ""
+ continue
+ case known && prev == rt.EgressAllow:
+ continue
+ }
+ if err := n.c.Egress(ctx, rt.Host); err != nil {
+ failed = true
+ n.failing[rt.Host] = true
+ n.callErrs++
+ if n.callErrs == 1 || n.callErrs%30 == 0 {
+ n.logf("agent: egress nudge for %s failed (#%d): %v", rt.Host, n.callErrs, err)
+ }
+ continue
+ }
+ delete(n.failing, rt.Host)
+ n.nudged[rt.Host] = rt.EgressAllow
+ }
+ for h := range n.nudged {
+ if !listed[h] {
+ delete(n.nudged, h)
+ }
+ }
+ for h := range n.failing {
+ if !listed[h] {
+ delete(n.failing, h)
+ }
+ }
+ if !failed {
+ n.callErrs = 0
+ }
+}
+
+func (n *egressNudger) regErr(what string, err error) {
+ n.regErrs++
+ if n.regErrs == 1 || n.regErrs%300 == 0 {
+ n.logf("agent: egress nudge %s error (#%d): %v", what, n.regErrs, err)
+ }
+}
diff --git a/internal/host/egress_nudge_test.go b/internal/host/egress_nudge_test.go
new file mode 100644
index 000000000..9260d397b
--- /dev/null
+++ b/internal/host/egress_nudge_test.go
@@ -0,0 +1,288 @@
+package host
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "path/filepath"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// fakeEgressNudge records every POST /egress the nudger sends and fails
+// the hosts listed in fail, once each.
+type fakeEgressNudge struct {
+ mu sync.Mutex
+ calls []string
+ fail map[string]int
+}
+
+func (f *fakeEgressNudge) Egress(_ context.Context, host string) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.calls = append(f.calls, host)
+ if f.fail[host] > 0 {
+ f.fail[host]--
+ return errors.New("POST /egress: 502 carlos-instances-x.slice: set-property failed")
+ }
+ return nil
+}
+
+// take returns the hosts nudged since the last take, sorted.
+func (f *fakeEgressNudge) take() []string {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ out := f.calls
+ f.calls = nil
+ slices.Sort(out)
+ return out
+}
+
+// newTestNudger is a nudger whose log lines go to logs, not the process
+// log, so the tests stay parallel and their output clean.
+func newTestNudger(c *fakeEgressNudge, logs *[]string) *egressNudger {
+ n := newEgressNudger(c)
+ n.logf = func(format string, args ...any) {
+ *logs = append(*logs, fmt.Sprintf(format, args...))
+ }
+ return n
+}
+
+func allowRow(host, allow string) registry.Route {
+ return registry.Route{Host: host, Kind: "instance", EgressAllow: allow}
+}
+
+func wantNudged(t *testing.T, step string, got []string, want ...string) {
+ t.Helper()
+ if !slices.Equal(got, want) {
+ t.Fatalf("%s: nudged %q, want %q", step, got, want)
+ }
+}
+
+func TestEgressNudgeOnlyChangedHosts(t *testing.T) {
+ t.Parallel()
+ c := &fakeEgressNudge{}
+ var logs []string
+ n := newTestNudger(c, &logs)
+ ctx := context.Background()
+
+ // First sight: a host with an allow counts as changed, a host with
+ // none does not (nothing is on by default).
+ n.pass(ctx, []registry.Route{
+ allowRow("shop-a.example.com", "10.0.5.20"),
+ allowRow("shop-b.example.com", ""),
+ allowRow("shop-c.example.com", "10.0.5.21 fd00:5::20"),
+ })
+ wantNudged(t, "first pass", c.take(), "shop-a.example.com", "shop-c.example.com")
+
+ // Nothing moved: nothing is sent.
+ n.pass(ctx, []registry.Route{
+ allowRow("shop-a.example.com", "10.0.5.20"),
+ allowRow("shop-b.example.com", ""),
+ allowRow("shop-c.example.com", "10.0.5.21 fd00:5::20"),
+ })
+ wantNudged(t, "unchanged pass", c.take())
+
+ // A grant on b and a change on c: only those two.
+ n.pass(ctx, []registry.Route{
+ allowRow("shop-a.example.com", "10.0.5.20"),
+ allowRow("shop-b.example.com", "10.0.5.22"),
+ allowRow("shop-c.example.com", "10.0.5.21"),
+ })
+ wantNudged(t, "grant pass", c.take(), "shop-b.example.com", "shop-c.example.com")
+
+ // A host that leaves the registry is forgotten: back with an allow,
+ // it is first seen again.
+ n.pass(ctx, []registry.Route{
+ allowRow("shop-b.example.com", "10.0.5.22"),
+ allowRow("shop-c.example.com", "10.0.5.21"),
+ })
+ wantNudged(t, "removal pass", c.take())
+ n.pass(ctx, []registry.Route{
+ allowRow("shop-a.example.com", "10.0.5.20"),
+ allowRow("shop-b.example.com", "10.0.5.22"),
+ allowRow("shop-c.example.com", "10.0.5.21"),
+ })
+ wantNudged(t, "return pass", c.take(), "shop-a.example.com")
+
+ // Two rows for one host send one nudge.
+ n.pass(ctx, []registry.Route{
+ allowRow("shop-a.example.com", "10.0.5.23"),
+ allowRow("shop-a.example.com", "10.0.5.23"),
+ allowRow("shop-b.example.com", "10.0.5.22"),
+ allowRow("shop-c.example.com", "10.0.5.21"),
+ })
+ wantNudged(t, "duplicate-row pass", c.take(), "shop-a.example.com")
+ if len(logs) != 0 {
+ t.Fatalf("logged %q with every nudge succeeding", logs)
+ }
+}
+
+func TestEgressNudgeRevokeToEmpty(t *testing.T) {
+ t.Parallel()
+ c := &fakeEgressNudge{}
+ var logs []string
+ n := newTestNudger(c, &logs)
+ ctx := context.Background()
+
+ n.pass(ctx, []registry.Route{allowRow("shop-a.example.com", "10.0.5.20")})
+ wantNudged(t, "grant", c.take(), "shop-a.example.com")
+
+ // The revoke down to "" is a change like any other: root must hear of
+ // it, since an allow left on the slice is the case that matters.
+ n.pass(ctx, []registry.Route{allowRow("shop-a.example.com", "")})
+ wantNudged(t, "revoke", c.take(), "shop-a.example.com")
+
+ n.pass(ctx, []registry.Route{allowRow("shop-a.example.com", "")})
+ wantNudged(t, "after the revoke", c.take())
+}
+
+func TestEgressNudgeRetriesAfterAFailure(t *testing.T) {
+ t.Parallel()
+ c := &fakeEgressNudge{fail: map[string]int{"shop-a.example.com": 2}}
+ var logs []string
+ n := newTestNudger(c, &logs)
+ ctx := context.Background()
+ rows := []registry.Route{
+ allowRow("shop-a.example.com", "10.0.5.20"),
+ allowRow("shop-b.example.com", "10.0.5.21"),
+ }
+
+ // a fails; b, after it in the list, is still nudged.
+ n.pass(ctx, rows)
+ wantNudged(t, "first pass", c.take(), "shop-a.example.com", "shop-b.example.com")
+ if len(logs) != 1 || !strings.Contains(logs[0], "shop-a.example.com") || !strings.Contains(logs[0], "502") {
+ t.Fatalf("logs after the first failure = %q, want one line naming the host and the error", logs)
+ }
+
+ // The next pass retries a, and only a; its second failure is counted
+ // but not logged (throttled as edgesFileLoop is).
+ n.pass(ctx, rows)
+ wantNudged(t, "second pass", c.take(), "shop-a.example.com")
+ if len(logs) != 1 {
+ t.Fatalf("logs after the second failure = %q, want the first line only", logs)
+ }
+
+ // The third succeeds; after it a is settled.
+ n.pass(ctx, rows)
+ wantNudged(t, "third pass", c.take(), "shop-a.example.com")
+ n.pass(ctx, rows)
+ wantNudged(t, "fourth pass", c.take())
+
+ // The throttle restarted after a clean pass: the next failure logs.
+ c.fail["shop-b.example.com"] = 1
+ n.pass(ctx, []registry.Route{
+ allowRow("shop-a.example.com", "10.0.5.20"),
+ allowRow("shop-b.example.com", ""),
+ })
+ wantNudged(t, "revoke pass", c.take(), "shop-b.example.com")
+ if len(logs) != 2 || !strings.Contains(logs[1], "shop-b.example.com") || !strings.Contains(logs[1], "(#1)") {
+ t.Fatalf("logs after a later failure = %q, want a fresh first line for shop-b", logs)
+ }
+
+ // A host whose first nudge failed, then revoked before any succeeded:
+ // root may hold the allow (its loop or a start asserted it), so the
+ // revoke is sent although the host was never heard of with a value.
+ c2 := &fakeEgressNudge{fail: map[string]int{"shop-d.example.com": 1}}
+ var logs2 []string
+ n2 := newTestNudger(c2, &logs2)
+ n2.pass(ctx, []registry.Route{allowRow("shop-d.example.com", "10.0.5.24")})
+ wantNudged(t, "first sight, failing", c2.take(), "shop-d.example.com")
+ n2.pass(ctx, []registry.Route{allowRow("shop-d.example.com", "")})
+ wantNudged(t, "revoke after a failed first nudge", c2.take(), "shop-d.example.com")
+ n2.pass(ctx, []registry.Route{allowRow("shop-d.example.com", "")})
+ wantNudged(t, "settled", c2.take())
+}
+
+// TestEgressNudgeWatchesTheSnapshotFingerprint drives the loop's step
+// against a real registry: a change to egress_allow alone, or to
+// policy_expires_at alone, moves SnapshotFingerprint and leaves
+// Fingerprint where it was, which is why the loop watches the former.
+func TestEgressNudgeWatchesTheSnapshotFingerprint(t *testing.T) {
+ t.Parallel()
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { reg.Close() })
+ for _, rt := range []registry.Route{
+ {Host: "shop-a.example.com", Kind: "instance", Account: "bab", App: "shop", Status: "ready"},
+ {Host: "shop-b.example.com", Kind: "instance", Account: "bab", App: "shop", Status: "ready"},
+ } {
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ }
+ fingerprints := func() (string, string) {
+ t.Helper()
+ fp, err := reg.Fingerprint()
+ if err != nil {
+ t.Fatal(err)
+ }
+ snap, err := reg.SnapshotFingerprint()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return fp, snap
+ }
+ c := &fakeEgressNudge{}
+ var logs []string
+ n := newTestNudger(c, &logs)
+ ctx := context.Background()
+
+ n.tick(ctx, reg)
+ wantNudged(t, "first tick, no policy", c.take())
+
+ fp0, snap0 := fingerprints()
+ if err := reg.SetPolicy("shop-a.example.com", "10.0.5.20", "", "1900000000"); err != nil {
+ t.Fatal(err)
+ }
+ fp1, snap1 := fingerprints()
+ if fp1 != fp0 {
+ t.Fatalf("Fingerprint moved on a policy write: the loop could watch it, and this test's premise is wrong")
+ }
+ if snap1 == snap0 {
+ t.Fatal("SnapshotFingerprint did not move when egress_allow and policy_expires_at changed")
+ }
+ n.tick(ctx, reg)
+ wantNudged(t, "grant tick", c.take(), "shop-a.example.com")
+ n.tick(ctx, reg)
+ wantNudged(t, "quiet tick", c.take())
+
+ // egress_allow alone.
+ if err := reg.SetPolicy("shop-a.example.com", "10.0.5.21", "", "1900000000"); err != nil {
+ t.Fatal(err)
+ }
+ fp2, snap2 := fingerprints()
+ if fp2 != fp1 || snap2 == snap1 {
+ t.Fatalf("egress_allow alone: Fingerprint moved %v, SnapshotFingerprint moved %v; want false, true", fp2 != fp1, snap2 != snap1)
+ }
+ n.tick(ctx, reg)
+ wantNudged(t, "egress_allow tick", c.take(), "shop-a.example.com")
+
+ // policy_expires_at alone (a re-sign): the snapshot moves, the allow
+ // did not, so nothing is sent.
+ if err := reg.SetPolicy("shop-a.example.com", "10.0.5.21", "", "1900043200"); err != nil {
+ t.Fatal(err)
+ }
+ fp3, snap3 := fingerprints()
+ if fp3 != fp2 || snap3 == snap2 {
+ t.Fatalf("policy_expires_at alone: Fingerprint moved %v, SnapshotFingerprint moved %v; want false, true", fp3 != fp2, snap3 != snap2)
+ }
+ n.tick(ctx, reg)
+ wantNudged(t, "re-sign tick", c.take())
+
+ // The revoke reaches root on the next tick.
+ if err := reg.SetPolicy("shop-a.example.com", "", "", ""); err != nil {
+ t.Fatal(err)
+ }
+ n.tick(ctx, reg)
+ wantNudged(t, "revoke tick", c.take(), "shop-a.example.com")
+ if len(logs) != 0 {
+ t.Fatalf("logged %q with every nudge succeeding", logs)
+ }
+}