carlos / platform Public

host: one lock across each telemetry pass, replacing generations

A generation recorded invocation order, not read order, so a pass that
started later but read earlier could still publish a stale snapshot.
Paul's ruling after the second round in that fault family: one mutex
held across each pass's whole read, settle and publish on both paths.
Deterministic tests for both orderings, armed and disarmed. Built by Astra.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 4789386e0337f0e30d44d555f81bbedec625affa parent 98d1128
2 files changed, +228 −131
  • internal/host/telemetry_pass.go +7 −18
  • internal/host/telemetry_pass_test.go +221 −113
diff --git a/internal/host/telemetry_pass.go b/internal/host/telemetry_pass.go
index 0eecc2f20..ca5ae175b 100644
--- a/internal/host/telemetry_pass.go
+++ b/internal/host/telemetry_pass.go
@@ -48,14 +48,7 @@ func setAssetOwnersSource(fn func() []registry.Route) { assetOwnersSource.Store(
// gate has no good object for yet.
var recordOnlyLast = &recordOnlyMemory{}
-// Generations reject older passes after a newer one publishes, armed or
-// disarmed. The mutex keeps that check, both sink calls and the remembered
-// record-only value together, so a slow read cannot undo newer settings.
-var telemetryPublication struct {
- next atomic.Uint64
- mu sync.Mutex
- published uint64
-}
+var telemetryPassMu sync.Mutex
type recordOnlyMemory struct {
mu sync.Mutex
@@ -112,9 +105,8 @@ type telemetrySwitchSet struct {
// own, nothing is remembered within or across passes, and a failed read
// leaves only that app off, as before the index.
type telemetryReads struct {
- // mu is held across a whole pass, reads included: the fast converge loop
- // and the instances loop both run the pass and take turns here. Nothing
- // else is locked under it.
+ // Direct resolver calls also use this state without telemetryPassMu;
+ // mu protects their gate and last good settings across reads.
mu sync.Mutex
w *release.ChangeWatch
gate *release.ReadGate
@@ -336,7 +328,10 @@ func (r *telemetryReads) read(ctx context.Context, s release.Store, key string,
// line each. A pass that cannot list the routes pushes nothing, so the edge
// keeps the maps it has.
func telemetryPass(ctx context.Context, s release.Store, reg *registry.Registry) {
- gen := telemetryPublication.next.Add(1)
+ // Armed and disarmed passes take turns from the first read through both
+ // sinks and the remembered values, so the last read always publishes last.
+ telemetryPassMu.Lock()
+ defer telemetryPassMu.Unlock()
aSink, pSink := analyticsSink.Load(), protectionSink.Load()
if aSink == nil && pSink == nil {
return
@@ -350,16 +345,10 @@ func telemetryPass(ctx context.Context, s release.Store, reg *registry.Registry)
log.Printf("agent: telemetry pass: %v", err)
return
}
- telemetryPublication.mu.Lock()
- defer telemetryPublication.mu.Unlock()
- if gen < telemetryPublication.published {
- return
- }
if aSink != nil {
(*aSink)(set.analytics)
}
if pSink != nil {
(*pSink)(recordOnlyLast.settle(set.recordOnly, set.unread))
}
- telemetryPublication.published = gen
}
diff --git a/internal/host/telemetry_pass_test.go b/internal/host/telemetry_pass_test.go
index ac95a3f01..05922b66d 100644
--- a/internal/host/telemetry_pass_test.go
+++ b/internal/host/telemetry_pass_test.go
@@ -10,6 +10,7 @@ import (
"path/filepath"
"slices"
"sync"
+ "sync/atomic"
"testing"
"time"
@@ -43,127 +44,234 @@ type telemetryObservations struct{ obs []analytics.Obs }
func (m *telemetryObservations) Observe(ob analytics.Obs) { m.obs = append(m.obs, ob) }
-func TestTelemetryPassRecordOnlyRejectsOlderPublication(t *testing.T) {
+func TestTelemetryPassRecordOnlySerializesReadAndPublication(t *testing.T) {
for _, armed := range []bool{false, true} {
name := "disarmed"
if armed {
- name = "rearmed"
+ name = "armed"
}
- t.Run(name, func(t *testing.T) {
- t.Setenv("CARLOS_EDGE_PROTECT", "block")
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
- s := newCICountingStore(t)
- reg := edgesTestRegistry(t)
- if err := reg.Upsert(registry.Route{
- Host: "shop.example.com", Kind: "static", Account: "bab", App: "shop", Status: "ready",
- }); err != nil {
- t.Fatal(err)
+ for _, beforeRead := range []bool{true, false} {
+ phase := "after_read"
+ if beforeRead {
+ phase = "before_read"
}
- e, err := edge.New(reg, nil)
- if err != nil {
- t.Fatal(err)
- }
- root := t.TempDir()
- if err := os.MkdirAll(filepath.Join(root, "shop", "current"), 0o755); err != nil {
- t.Fatal(err)
- }
- edge.WithLocalStatic(root)(e)
- if err := e.Reload(); err != nil {
- t.Fatal(err)
- }
- meter := &telemetryObservations{}
- e.EnableAnalytics(meter)
- prevA, prevP, prevO := analyticsSink.Load(), protectionSink.Load(), assetOwnersSource.Load()
- prevW := armedChangeWatch.Load()
- t.Cleanup(func() {
- analyticsSink.Store(prevA)
- protectionSink.Store(prevP)
- assetOwnersSource.Store(prevO)
- armedChangeWatch.Store(prevW)
- recordOnlyLast.reset()
+ t.Run(name+"/"+phase, func(t *testing.T) {
+ testTelemetryPassRecordOnlySerialized(t, armed, beforeRead)
})
- recordOnlyLast.reset()
- setAnalyticsSink(e.SetAnalyticsOn)
- setProtectionSink(e.SetProtectionRecordOnly)
- setAssetOwnersSource(func() []registry.Route {
- return []registry.Route{{Account: "bdk", App: "cart"}}
- })
- armedChangeWatch.Store(nil)
- if armed {
- armedChangeWatch.Store(release.NewChangeWatch(s))
- }
- setOn := func(on bool) {
- t.Helper()
- if err := telemetry.Update(ctx, s, telemetry.AppKey("bab", "shop"), func(st *telemetry.Settings) {
- st.Analytics = &telemetry.Analytics{Count: telemetry.CountOff}
- st.Protection = nil
- if on {
- st.Analytics.Count = telemetry.CountEdge
- st.Protection = &telemetry.Protection{Mode: telemetry.ProtectRecordOnly}
- }
- }); err != nil {
- t.Fatal(err)
- }
- }
- setOn(false)
- // The far asset read follows shop's read, so the older pass holds
- // shop's off values while the newer pass reads and publishes on.
- blocked := &telemetryBlockingStore{
- Store: s, key: telemetry.AppKey("bdk", "cart"),
- entered: make(chan struct{}), resume: make(chan struct{}),
- }
- done := make(chan struct{})
- go func() {
- defer close(done)
- telemetryPass(ctx, blocked, reg)
- }()
- defer func() {
- cancel()
- <-done
- }()
- <-blocked.entered
- setOn(true)
- if armed {
- // Replacing the watch gives the newer pass its own reader;
- // publication ordering must outlive either reader's mutex.
- armedChangeWatch.Store(release.NewChangeWatch(s))
- }
- telemetryPass(ctx, s, reg)
- assertOn := func() {
- t.Helper()
- w := httptest.NewRecorder()
- r := httptest.NewRequest("GET", "http://shop.example.com/.env", nil)
- n := len(meter.obs)
- e.ServeHTTP(w, r)
- if w.Code != http.StatusNotFound || w.Body.String() != "404 page not found\n" || w.Header().Get("X-Carlos-Ref") != "" {
- t.Errorf("record-only request = %d %q, want static 404 without a protection reference", w.Code, w.Body.String())
- }
- if len(meter.obs) != n+1 {
- t.Errorf("analytics observations = %d, want %d", len(meter.obs), n+1)
- }
- recordOnlyLast.mu.Lock()
- remembered := recordOnlyLast.m["bab/shop"]
- recordOnlyLast.mu.Unlock()
- if !remembered {
- t.Error("remembered record-only value is off, want on")
- }
+ }
+ }
+}
+
+func testTelemetryPassRecordOnlySerialized(t *testing.T, armed, beforeRead bool) {
+ t.Setenv("CARLOS_EDGE_PROTECT", "block")
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ s := newCICountingStore(t)
+ reg := edgesTestRegistry(t)
+ if err := reg.Upsert(registry.Route{
+ Host: "shop.example.com", Kind: "static", Account: "bab", App: "shop", Status: "ready",
+ }); err != nil {
+ t.Fatal(err)
+ }
+ e, err := edge.New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ root := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(root, "shop", "current"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ edge.WithLocalStatic(root)(e)
+ if err := e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ meter := &telemetryObservations{}
+ e.EnableAnalytics(meter)
+ prevA, prevP, prevO := analyticsSink.Load(), protectionSink.Load(), assetOwnersSource.Load()
+ prevW := armedChangeWatch.Load()
+ t.Cleanup(func() {
+ analyticsSink.Store(prevA)
+ protectionSink.Store(prevP)
+ assetOwnersSource.Store(prevO)
+ armedChangeWatch.Store(prevW)
+ recordOnlyLast.reset()
+ })
+ recordOnlyLast.reset()
+ armedChangeWatch.Store(nil)
+ if armed {
+ armedChangeWatch.Store(release.NewChangeWatch(s))
+ }
+ setOn := func(on bool) {
+ t.Helper()
+ if err := telemetry.Update(ctx, s, telemetry.AppKey("bab", "shop"), func(st *telemetry.Settings) {
+ st.Analytics = &telemetry.Analytics{Count: telemetry.CountOff}
+ st.Protection = nil
+ if on {
+ st.Analytics.Count = telemetry.CountEdge
+ st.Protection = &telemetry.Protection{Mode: telemetry.ProtectRecordOnly}
}
- assertOn()
- close(blocked.resume)
- <-done
- assertOn()
- // A failed read must reuse the newer remembered value too.
- armedChangeWatch.Store(nil)
- failed := &keysFailingStore{ciCountingStore: s}
- failed.failing(telemetry.AppKey("bab", "shop"))
- telemetryPass(ctx, failed, reg)
- w := httptest.NewRecorder()
- e.ServeHTTP(w, httptest.NewRequest("GET", "http://shop.example.com/.env", nil))
- if w.Code != http.StatusNotFound || w.Body.String() != "404 page not found\n" || w.Header().Get("X-Carlos-Ref") != "" {
- t.Errorf("failed read undid record-only: %d %q", w.Code, w.Body.String())
+ }); err != nil {
+ t.Fatal(err)
+ }
+ }
+ setOn(beforeRead)
+
+ paused, resume := make(chan struct{}), make(chan struct{})
+ published, finishPublish := make(chan struct{}), make(chan struct{})
+ releaseRead := sync.OnceFunc(func() { close(resume) })
+ releasePublish := sync.OnceFunc(func() { close(finishPublish) })
+ var workers sync.WaitGroup
+ t.Cleanup(func() {
+ cancel()
+ releaseRead()
+ releasePublish()
+ workers.Wait()
+ })
+ await := func(ch <-chan struct{}) {
+ t.Helper()
+ select {
+ case <-ch:
+ case <-time.After(10 * time.Second):
+ t.Fatal("telemetry pass did not reach the handshake")
+ }
+ }
+ assertLocked := func() {
+ t.Helper()
+ // This pins exclusion without depending on whether the waiting
+ // goroutine has been scheduled yet.
+ if telemetryPassMu.TryLock() {
+ telemetryPassMu.Unlock()
+ t.Error("telemetry pass mutex is not held through read and publication")
+ }
+ }
+ type event struct {
+ stage string
+ on bool
+ }
+ events := make(chan event, 12)
+ var ownerCalls, protectionCalls atomic.Int32
+ secondEntered := make(chan struct{})
+ setAssetOwnersSource(func() []registry.Route {
+ assertLocked()
+ events <- event{stage: "owners"}
+ if ownerCalls.Add(1) == 1 {
+ if beforeRead {
+ close(paused)
+ <-resume
}
- })
+ } else {
+ close(secondEntered)
+ }
+ return []registry.Route{{Account: "bdk", App: "cart"}}
+ })
+ setAnalyticsSink(func(m map[string]bool) {
+ assertLocked()
+ e.SetAnalyticsOn(m)
+ events <- event{"analytics", m["bab/shop"]}
+ })
+ setProtectionSink(func(m map[string]bool) {
+ assertLocked()
+ e.SetProtectionRecordOnly(m)
+ events <- event{"record-only", m["bab/shop"]}
+ if protectionCalls.Add(1) == 1 {
+ close(published)
+ <-finishPublish
+ assertLocked()
+ }
+ })
+ var firstStore release.Store = s
+ if !beforeRead {
+ // The far asset read follows shop's read, so the first pass has
+ // already read off while its publication is held back.
+ firstStore = &telemetryBlockingStore{
+ Store: s, key: telemetry.AppKey("bdk", "cart"), entered: paused, resume: resume,
+ }
+ }
+ firstDone, secondDone := make(chan struct{}), make(chan struct{})
+ workers.Add(1)
+ go func() {
+ defer workers.Done()
+ defer close(firstDone)
+ telemetryPass(ctx, firstStore, reg)
+ }()
+ await(paused)
+ assertLocked()
+ secondStarted := make(chan struct{})
+ workers.Add(1)
+ go func() {
+ defer workers.Done()
+ defer close(secondDone)
+ assertLocked()
+ close(secondStarted)
+ telemetryPass(ctx, s, reg)
+ }()
+ await(secondStarted)
+ if beforeRead {
+ // A started first but has not read yet; B has started too. A must
+ // read and publish before B can enter the owners hook.
+ setOn(false)
+ } else {
+ setOn(true)
+ }
+ releaseRead()
+ await(published)
+ assertLocked()
+ select {
+ case <-secondEntered:
+ t.Error("second pass entered before the first finished publishing")
+ default:
+ }
+ recordOnlyLast.mu.Lock()
+ firstRemembered := recordOnlyLast.m["bab/shop"]
+ recordOnlyLast.mu.Unlock()
+ if firstRemembered {
+ t.Error("first pass remembered on, want the off value it read")
+ }
+ setOn(true)
+ if armed {
+ // A new reader must still obey the process-wide pass lock.
+ armedChangeWatch.Store(release.NewChangeWatch(s))
+ }
+ releasePublish()
+ await(firstDone)
+ await(secondDone)
+ var got []event
+ for len(events) > 0 {
+ got = append(got, <-events)
+ }
+ want := []event{
+ {stage: "owners"}, {"analytics", false}, {"record-only", false},
+ {stage: "owners"}, {"analytics", true}, {"record-only", true},
+ }
+ if !slices.Equal(got, want) {
+ t.Errorf("pass order and values = %v, want %v", got, want)
+ }
+ w := httptest.NewRecorder()
+ e.ServeHTTP(w, httptest.NewRequest("GET", "http://shop.example.com/.env", nil))
+ if w.Code != http.StatusNotFound || w.Body.String() != "404 page not found\n" || w.Header().Get("X-Carlos-Ref") != "" {
+ t.Errorf("record-only request = %d %q, want static 404 without a protection reference", w.Code, w.Body.String())
+ }
+ if len(meter.obs) != 1 {
+ t.Errorf("analytics observations = %d, want 1", len(meter.obs))
+ }
+ recordOnlyLast.mu.Lock()
+ remembered := recordOnlyLast.m["bab/shop"]
+ recordOnlyLast.mu.Unlock()
+ if !remembered {
+ t.Error("remembered record-only value is off, want the latest read's on value")
+ }
+ // A failed read must reuse the newer remembered value too.
+ assetOwnersSource.Store(nil)
+ setAnalyticsSink(e.SetAnalyticsOn)
+ setProtectionSink(e.SetProtectionRecordOnly)
+ armedChangeWatch.Store(nil)
+ failed := &keysFailingStore{ciCountingStore: s}
+ failed.failing(telemetry.AppKey("bab", "shop"))
+ telemetryPass(ctx, failed, reg)
+ w = httptest.NewRecorder()
+ e.ServeHTTP(w, httptest.NewRequest("GET", "http://shop.example.com/.env", nil))
+ if w.Code != http.StatusNotFound || w.Body.String() != "404 page not found\n" || w.Header().Get("X-Carlos-Ref") != "" {
+ t.Errorf("failed read undid record-only: %d %q", w.Code, w.Body.String())
}
}