fix: scope demo store failures and control cancellation
Address Task 4 review P1-1 and P2-1 through P2-4. Isolate request cancellation and refused control entries, preserve unrelated responses, sample the clock under its lock, and require protected acknowledgements for stop confirmation. Add regression coverage for cancellation at connection wait, BEGIN and UPDATE, selective cancellation, retirement delivery and legacy status.
internal/console/demo_operator_test.go+110 −3internal/console/demo_serving.go+16 −6internal/edge/demo_traffic.go+15 −5internal/edge/demo_traffic_test.go+55 −0internal/host/agent.go+2 −2internal/host/demo_cleanup_test.go+4 −1internal/host/demo_control_fix_test.go+403 −0internal/host/demo_jobs.go+4 −7internal/host/demo_retirement_stream_test.go+19 −4internal/host/demo_serving.go+62 −27internal/host/demo_serving_test.go+10 −15internal/host/demo_traffic.go+40 −8
CI failed — run details
Intent
<task-notification> <task-id>ae7e84a6208556a16</task-id> <tool-use-id>toolu_011wQagh99WuD6jW2zPBLD8k</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6e566fe9-9aca-47cb-9753-64e881b0d285/tasks/ae7e84a6208556a16.output</output-file> <status>completed</status> <summary>Agent "Review Task 4 (Opus)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Spec verdict:** issues found. The signed early-retirement boundary, its root-facing consumer, operator authority, R8 and R9 are all compliant. What fails is the box's serving control, which acts all-or-nothing across the whole box. **Quality verdict:** NOT READY. **Counts:** P1 1, P2 4, P3 7. - **P1-1:** One cancelled request poisons the whole box's traffic store until the agent restarts (`internal/host/demo_traffic.go:158-160`). Admit and DebitBytes run on the request's context. A client disconnect, the expiry deadline or the 100 ms monitor cancelling it sets the `failed` flag. After that, every demo on the box gets 503, and Fence, Purge and control persistence all fail, so retirement stops too. I confirmed this with an overlay test: after one debit on a cancelled context, a different demo's Admit and a Fence both returned DEMO-UNAVAILABLE. - **P2-1:** Every new revision cancels every in-flight response on the box (`internal/host/demo_serving.go:126-129`). Revisions are global, so creating a demo anywhere cuts unrelated streams and downloads on all boxes at the next heartbeat. - **P2-2:** Clock-rollback detection compares time samples taken by different goroutines (`demo_serving.go:204-208`, `:255-259`). A slightly stale sample closes serving for the whole box for up to 10 seconds. An overlay test reproduced it. - **P2-3:** One bad entry fails the whole control (`demo_serving.go:122,137,154`). Two things follow: - The stream drops before the retirement messages sent in the same pass are read. A lost `demo-traffic.db` can therefore hold up purges for as long as 24 hours. - Ordinary one-second clock boundaries also trigger the drop, and reconnect backoff never resets, so each drop can cost up to 15 seconds of box-wide 503s. - **P2-4:** Operator status reports old-binary or legacy demos as stopped once the 35-second timer runs out (`internal/console/demo_serving.go:223-244,323,325`). That bound only holds for protected workers, so `takedown-status` and `serving off` can say "stopped" while an old box is still serving. The targeted tests, `TestDemo(Operator|Kill|Takedown|ServingStream)` and `TestSystemDemosRemote`, pass. The CLI test needed a scratch TMPDIR with no `~/.carlos/config` above it. The two overlay tests ran from `$TMPDIR` without touching the worktree, and all scratch is deleted. The full review is in `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/agent-start-demo-2/.superpowers/sdd/2026-11-04-agent-start-demo-2-edge-protections/task-4-review-r1.md`.</result> <usage><subagent_tokens>252324</subagent_tokens><tool_uses>28</tool_uses><duration_ms>720973</duration_ms></usage> </task-notification>
Attributed to this commit: 10.4 g CO₂e (1,215,835 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on agent-start-demo-2, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/internal/console/demo_operator_test.go b/internal/console/demo_operator_test.go| index 2da3ab138..c7fa01ae4 100644 |
| --- a/internal/console/demo_operator_test.go |
| +++ b/internal/console/demo_operator_test.go |
| @@ -5,6 +5,7 @@ import ( |
| "context" |
| "database/sql" |
| "errors" |
| + "fmt" |
| "github.com/carlosframework/platform/internal/demo" |
| "github.com/carlosframework/platform/internal/demobuild" |
| "github.com/carlosframework/platform/internal/interactive" |
| @@ -64,6 +65,10 @@ func TestDemoTakedownBeforeExpiry(t *testing.T) { |
| func TestDemoKillFence(t *testing.T) { |
| s, d, _, _ := demoPublishFixture(t) |
| + s.demoJobs.peers = nil // Simulate an offline worker with a prior protected acknowledgement. |
| + if _, err := s.store.db.Exec(`UPDATE demo_caps SET initialized=1 WHERE demo_id=?`, d.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| now := time.Now() |
| before, _ := s.demoServingSetting(t.Context()) |
| if err := s.setDemoServing(t.Context(), false, "operator@example.com", now); err != nil { |
| @@ -373,16 +378,118 @@ func TestDemoKillDefaultAndRestartBound(t *testing.T) { |
| // Persisted wall time is insufficient after restart, even for an old fence. |
| at := time.Now().Add(-time.Hour) |
| now := time.Now() |
| - if s.demoStopConfirmed("box", 1, at, now) { |
| + if s.demoStopConfirmed("box", 1, at, now, true) { |
| t.Fatal("restart trusted old wall clock as stop proof") |
| } |
| s.demoStopMu.Lock() |
| bound := s.demoStopDeadlines[at.UnixNano()] |
| s.demoStopMu.Unlock() |
| - if s.demoStopConfirmed("box", 1, at, bound.Add(-time.Nanosecond)) { |
| + if s.demoStopConfirmed("box", 1, at, bound.Add(-time.Nanosecond), true) { |
| t.Fatal("stop before monotonic bound") |
| } |
| - if !s.demoStopConfirmed("box", 1, at, bound) { |
| + if !s.demoStopConfirmed("box", 1, at, bound, true) { |
| t.Fatal("stop not confirmed at bound") |
| } |
| } |
| + |
| +func TestDemoOperatorUnprotectedStopPending(t *testing.T) { |
| + for _, legacy := range []bool{false, true} { |
| + for _, retiring := range []bool{false, true} { |
| + t.Run(fmt.Sprintf("legacy=%t/retiring=%t", legacy, retiring), func(t *testing.T) { |
| + s, d, _, _ := demoPublishFixture(t) |
| + if legacy { |
| + if _, err := s.store.db.Exec(`DELETE FROM demo_caps WHERE demo_id=?`, d.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if retiring { |
| + unlock := s.lockApp(d.AccountSqid, d.App) |
| + err := s.retireDemoLocked(t.Context(), d, time.Now(), "operator") |
| + unlock() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + } else if err := s.setDemoServing(t.Context(), false, "operator@example.com", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + // Reading after the resident bound cannot prove an old worker stopped. |
| + view, err := s.demoOperatorView(t.Context(), time.Now().Add(time.Minute)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if view.ServingConfirmed || len(view.Demos) != 1 || view.Demos[0].ServingConfirmed { |
| + t.Fatalf("unacknowledged stop reported confirmed: %+v", view) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +func TestDemoOperatorProtectedStopEvidence(t *testing.T) { |
| + for _, mode := range []string{"offline-acknowledged", "connected-acknowledged", "probe-without-ack", "old-binary", "legacy-acknowledged"} { |
| + t.Run(mode, func(t *testing.T) { |
| + s, d, _, _ := demoPublishFixture(t) |
| + life, err := s.store.AppLife(d.AccountID, d.App) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + setting, err := s.demoServingSetting(t.Context()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + peer := s.demoJobs.peers[d.AssignedBox] |
| + peer.issued = []demo.ServingControl{{Revision: setting.Revision, Demos: []demo.ServingDemo{{Identity: demo.TrafficIdentity{ID: d.ID, Lifetime: life.Lifetime, Host: d.Host}, Initialize: true}}}} |
| + if mode != "probe-without-ack" { |
| + if err := s.ackDemoServing(t.Context(), peer, setting.Revision); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + switch mode { |
| + case "offline-acknowledged": |
| + s.demoJobs.peers = nil |
| + case "old-binary": |
| + peer.ready.ServingProbe = 0 |
| + case "legacy-acknowledged": |
| + if _, err := s.store.db.Exec(`DELETE FROM demo_caps WHERE demo_id=?`, d.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := s.setDemoServing(t.Context(), false, "operator@example.com", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + view, err := s.demoOperatorView(t.Context(), time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if view.ServingConfirmed { |
| + t.Fatal("unacknowledged new revision confirmed early") |
| + } |
| + view, err = s.demoOperatorView(t.Context(), time.Now().Add(time.Minute)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := mode == "offline-acknowledged" || mode == "connected-acknowledged" |
| + if view.ServingConfirmed != want { |
| + t.Fatalf("confirmed=%t want %t", view.ServingConfirmed, want) |
| + } |
| + // Purge acknowledgement remains sufficient even for a legacy worker. |
| + unlock := s.lockApp(d.AccountSqid, d.App) |
| + err = s.retireDemoLocked(t.Context(), d, time.Now(), "operator") |
| + unlock() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r, err := s.demoRetirement(t.Context(), d.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.completeDemoRetirement(t.Context(), d.Fleet+"/"+d.AssignedBox, r.Wire); err != nil { |
| + t.Fatal(err) |
| + } |
| + view, err = s.demoOperatorView(t.Context(), time.Now()) |
| + if err != nil || !view.ServingConfirmed { |
| + t.Fatalf("purge ack not confirmed: %+v %v", view, err) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/console/demo_serving.go b/internal/console/demo_serving.go| index 792c3dc0a..24f1991a6 100644 |
| --- a/internal/console/demo_serving.go |
| +++ b/internal/console/demo_serving.go |
| @@ -220,17 +220,26 @@ func (s *Server) recordDemoStopFence(at int64) { |
| } |
| s.demoStopDeadlines[at] = time.Now().Add(35 * time.Second) |
| } |
| -func (s *Server) demoStopConfirmed(box string, revision int64, at time.Time, now time.Time) bool { |
| +func (s *Server) demoStopConfirmed(box string, revision int64, at time.Time, now time.Time, initialized bool) bool { |
| if box == "" { |
| return true |
| } |
| s.demoJobs.mu.Lock() |
| p := s.demoJobs.peers[box] |
| - confirmed := p != nil && s.demoPeerOK(p) && p.servingAck >= revision |
| + // initialized is durable evidence of a protected assignment acknowledgement. |
| + // A current peer must establish that evidence again for its own session. |
| + protected := initialized |
| + if p != nil { |
| + protected = p.ready.ServingProbe != 0 && p.servingAck > 0 && s.demoPeerOK(p) |
| + } |
| + confirmed := protected && p != nil && p.servingAck >= revision |
| s.demoJobs.mu.Unlock() |
| if confirmed { |
| return true |
| } |
| + if !protected { |
| + return false |
| + } |
| s.demoStopMu.Lock() |
| defer s.demoStopMu.Unlock() |
| if s.demoStopDeadlines == nil { |
| @@ -292,7 +301,8 @@ func (s *Server) demoOperatorView(ctx context.Context, now time.Time) (demoOpera |
| return out, err |
| } |
| v := demoOperatorDemo{Host: d.Host, State: d.State, Cleanup: "pending"} |
| - err = s.store.db.QueryRowContext(ctx, `SELECT request_cap,byte_cap FROM demo_caps WHERE demo_id=?`, id).Scan(&v.Caps.Requests, &v.Caps.BodyBytes) |
| + var initialized bool |
| + err = s.store.db.QueryRowContext(ctx, `SELECT request_cap,byte_cap,initialized FROM demo_caps WHERE demo_id=?`, id).Scan(&v.Caps.Requests, &v.Caps.BodyBytes, &initialized) |
| legacy := errors.Is(err, sql.ErrNoRows) |
| if err != nil && !legacy { |
| return out, err |
| @@ -320,13 +330,13 @@ func (s *Server) demoOperatorView(ctx context.Context, now time.Time) (demoOpera |
| if r.FencedAt == 0 { |
| at = time.Unix(receipt.Tombstone+1, 0) |
| } |
| - v.ServingConfirmed = r.Acknowledged || s.demoStopConfirmed(d.AssignedBox, setting.Revision, at, now) |
| + v.ServingConfirmed = r.Acknowledged || !legacy && s.demoStopConfirmed(d.AssignedBox, setting.Revision, at, now, initialized) |
| } else if !setting.Enabled { |
| - v.ServingConfirmed = s.demoStopConfirmed(d.AssignedBox, setting.Revision, time.Unix(0, setting.ChangedAt), now) |
| + v.ServingConfirmed = !legacy && s.demoStopConfirmed(d.AssignedBox, setting.Revision, time.Unix(0, setting.ChangedAt), now, initialized) |
| } else if !live { |
| // Legacy rows have no protected authority. They still require takedown |
| // during activation; do not claim an old binary has stopped. |
| - v.ServingConfirmed = d.AssignedBox == "" || life != nil && now.Unix() >= life.ExpiresAt+35 |
| + v.ServingConfirmed = d.AssignedBox == "" || !legacy && life != nil && now.Unix() >= life.ExpiresAt+35 && s.demoStopConfirmed(d.AssignedBox, setting.Revision, time.Unix(life.ExpiresAt, 0), now, initialized) |
| } else { |
| s.demoJobs.mu.Lock() |
| p := s.demoJobs.peers[d.AssignedBox] |
diff --git a/internal/edge/demo_traffic.go b/internal/edge/demo_traffic.go| index 75d63d8ea..ea6d9fbb1 100644 |
| --- a/internal/edge/demo_traffic.go |
| +++ b/internal/edge/demo_traffic.go |
| @@ -597,17 +597,27 @@ func (w *demoRefusalWriter) Flush() { |
| } |
| // CancelDemoResponses ends current resident streams without retiring their |
| -// lifetimes. Task 4 calls it immediately on off/disconnect after closing its |
| -// serving snapshot; the per-write check also observes that closed snapshot. |
| -func (e *Edge) CancelDemoResponses() { |
| +// lifetimes. With identities, only those responses are cancelled; without |
| +// identities, off/disconnect cancels every response. The caller holds the |
| +// serving gate after draining writes and before acknowledging the control. |
| +func (e *Edge) CancelDemoResponses(ids ...demo.TrafficIdentity) { |
| s := e.demoTraffic |
| if s == nil { |
| return |
| } |
| s.mu.Lock() |
| defer s.mu.Unlock() |
| - for a := range s.active { |
| - a.cancel() |
| + for a, id := range s.active { |
| + if len(ids) == 0 { |
| + a.cancel() |
| + continue |
| + } |
| + for _, revoked := range ids { |
| + if id == revoked { |
| + a.cancel() |
| + break |
| + } |
| + } |
| } |
| } |
diff --git a/internal/edge/demo_traffic_test.go b/internal/edge/demo_traffic_test.go| index 407bf6e09..f2bc9ab6a 100644 |
| --- a/internal/edge/demo_traffic_test.go |
| +++ b/internal/edge/demo_traffic_test.go |
| @@ -500,3 +500,58 @@ func TestDemoServingHTTPAndStartupHook(t *testing.T) { |
| t.Fatal("second startup hook reset retired state") |
| } |
| } |
| + |
| +func TestDemoTrafficCancelOnlyRevokedLifetime(t *testing.T) { |
| + contexts := make(chan context.Context, 2) |
| + e, rt, _ := demoTrafficFixture(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + contexts <- r.Context() |
| + <-r.Context().Done() |
| + })) |
| + other := rt |
| + otherID, err := demo.NewIdentity(strings.NewReader(strings.Repeat("\x01", 64))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + other.Host = otherID.Name + ".example.com" |
| + other.DemoHost = other.Host |
| + other.DemoID = otherID.ID |
| + other.DemoLifetime = "life2" |
| + other.App = otherID.App |
| + other.Socket = provision.NestedSocket(other.Host) |
| + routes := e.current() |
| + routes[other.Host] = upstream{route: other, proxy: routes[rt.Host].proxy} |
| + e.upstreams.Store(&routes) |
| + var done sync.WaitGroup |
| + run := func(host string) context.Context { |
| + done.Add(1) |
| + go func() { |
| + defer done.Done() |
| + demoRunAbort(func() { e.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "https://"+host+"/", nil)) }) |
| + }() |
| + select { |
| + case ctx := <-contexts: |
| + return ctx |
| + case <-time.After(2 * time.Second): |
| + t.Fatal("stream did not start") |
| + return nil |
| + } |
| + } |
| + t.Cleanup(func() { e.CancelDemoResponses(); done.Wait() }) |
| + first := run(rt.Host) |
| + second := run(other.Host) |
| + e.CancelDemoResponses(demoTrafficID(rt)) |
| + select { |
| + case <-first.Done(): |
| + case <-time.After(time.Second): |
| + t.Fatal("revoked stream remained active") |
| + } |
| + if second.Err() != nil { |
| + t.Fatal("unrelated stream cancelled") |
| + } |
| + e.CancelDemoResponses() |
| + select { |
| + case <-second.Done(): |
| + case <-time.After(time.Second): |
| + t.Fatal("off left stream active") |
| + } |
| +} |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 35eba7bdc..c8d4edd0c 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -1009,9 +1009,9 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| armPolicyCache() |
| startDemoWorker(agentCtx, reg, demoData, cfg.Prefix, traffic, stopDemoTraffic, func(w *demoWorker) { |
| w.trafficGate = &demoGate |
| - w.serving.cancel = func() { |
| + w.serving.cancel = func(ids ...demo.TrafficIdentity) { |
| if e := demoEdge.Load(); e != nil { |
| - e.CancelDemoResponses() |
| + e.CancelDemoResponses(ids...) |
| } |
| } |
| servingWorker.Store(w) |
diff --git a/internal/host/demo_cleanup_test.go b/internal/host/demo_cleanup_test.go| index a3cccda8a..d9761cb90 100644 |
| --- a/internal/host/demo_cleanup_test.go |
| +++ b/internal/host/demo_cleanup_test.go |
| @@ -167,7 +167,10 @@ func testDemoRetirement(t *testing.T, legacy bool) { |
| w.beginDemoServing() |
| now := time.Now() |
| c := demo.ServingControl{Revision: 1, Probe: w.demoHeartbeat(now).ServingProbe, ValidUntil: now.Add(30 * time.Second).Unix(), Enabled: true, Demos: []demo.ServingDemo{{Identity: trafficID, Caps: demo.TrafficCaps{Requests: 2000, BodyBytes: 200000000}, ExpiresAt: d.ExpiresAt, Initialize: true}}} |
| - if err := w.applyDemoServing(c, now); err == nil { |
| + if err := w.applyDemoServing(c, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, ok := w.serving.demos[trafficID]; ok { |
| t.Fatal("legacy route received allowance") |
| } |
| var n int |
diff --git a/internal/host/demo_control_fix_test.go b/internal/host/demo_control_fix_test.go| new file mode 100644 |
| index 000000000..1385201cc |
| --- /dev/null |
| +++ b/internal/host/demo_control_fix_test.go |
| @@ -0,0 +1,403 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "database/sql/driver" |
| + "errors" |
| + "path/filepath" |
| + "runtime" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| + "github.com/carlosframework/platform/internal/demobuild" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "modernc.org/sqlite" |
| +) |
| + |
| +func demoControlFixFixture(t *testing.T) (*demoWorker, demo.ServingControl, registry.Route, time.Time) { |
| + t.Helper() |
| + store, err := openDemoTraffic(filepath.Join(t.TempDir(), "traffic.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { store.Close() }) |
| + w := &demoWorker{traffic: store, cfg: demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com", EdgeProtections: true}, box: "box"} |
| + now := time.Now() |
| + w.beginDemoServing() |
| + id := demo.TrafficIdentity{ID: "shop", Lifetime: "life", Host: "shop.example.com"} |
| + rt := registry.Route{Host: id.Host, DemoHost: id.Host, DemoID: id.ID, DemoLifetime: id.Lifetime, DemoExpiresAt: now.Add(time.Hour).Unix(), FleetBox: "box", Region: "fleet/demo", Account: "shop"} |
| + c := demo.ServingControl{Revision: 1, Probe: w.demoHeartbeat(now).ServingProbe, ValidUntil: now.Add(30 * time.Second).Unix(), Enabled: true, Demos: []demo.ServingDemo{{Identity: id, Caps: demo.TrafficCaps{Requests: 2000, BodyBytes: 200000000}, ExpiresAt: rt.DemoExpiresAt, Initialize: true}}} |
| + if err := w.applyDemoServing(c, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + return w, c, rt, now |
| +} |
| + |
| +func TestDemoTrafficCancelledRequestIsolation(t *testing.T) { |
| + for _, admit := range []bool{false, true} { |
| + for _, deadline := range []bool{false, true} { |
| + name := "debit" |
| + if admit { |
| + name = "admit" |
| + } |
| + if deadline { |
| + name += "-deadline" |
| + } |
| + t.Run(name, func(t *testing.T) { |
| + w, c, _, _ := demoControlFixFixture(t) |
| + id := c.Demos[0].Identity |
| + other := demo.TrafficIdentity{ID: "shop2", Lifetime: "life2", Host: "shop2.example.com"} |
| + if err := w.traffic.Initialize(t.Context(), other, c.Demos[0].Caps); err != nil { |
| + t.Fatal(err) |
| + } |
| + conn, err := w.traffic.db.Conn(t.Context()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer conn.Close() |
| + var ctx context.Context |
| + var cancel context.CancelFunc |
| + if deadline { |
| + ctx, cancel = context.WithTimeout(t.Context(), 50*time.Millisecond) |
| + } else { |
| + ctx, cancel = context.WithCancel(t.Context()) |
| + } |
| + defer cancel() |
| + done := make(chan error, 1) |
| + waits := w.traffic.db.Stats().WaitCount |
| + go func() { |
| + if admit { |
| + done <- w.traffic.Admit(ctx, id) |
| + } else { |
| + n, err := w.traffic.DebitBytes(ctx, id, 17) |
| + if n != 0 { |
| + t.Errorf("cancelled debit authorized %d bytes", n) |
| + } |
| + done <- err |
| + } |
| + }() |
| + until := time.Now().Add(time.Second) |
| + for w.traffic.db.Stats().WaitCount == waits && time.Now().Before(until) { |
| + runtime.Gosched() |
| + } |
| + if w.traffic.db.Stats().WaitCount == waits { |
| + t.Fatal("debit did not wait for connection") |
| + } |
| + if !deadline { |
| + cancel() |
| + } |
| + err = <-done |
| + if !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) { |
| + t.Fatalf("cancellation: %v", err) |
| + } |
| + conn.Close() |
| + if w.traffic.failed.Load() { |
| + t.Error("request cancellation poisoned shared store") |
| + } |
| + if err = w.traffic.Admit(t.Context(), other); err != nil { |
| + t.Errorf("other demo refused: %v", err) |
| + } |
| + c.Revision++ |
| + if err = w.applyDemoServing(c, time.Now()); err != nil { |
| + t.Errorf("control persistence refused: %v", err) |
| + } |
| + if err = w.traffic.Fence(t.Context(), id); err != nil { |
| + t.Errorf("fence refused: %v", err) |
| + } |
| + if err = w.traffic.Purge(t.Context(), id); err != nil { |
| + t.Errorf("purge refused: %v", err) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +func TestDemoServingStreamRevisionPreservesAuthority(t *testing.T) { |
| + w, c, rt, _ := demoControlFixFixture(t) |
| + cancelled := false |
| + w.serving.cancel = func(...demo.TrafficIdentity) { cancelled = true } |
| + c.Revision++ |
| + if err := w.applyDemoServing(c, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if cancelled { |
| + t.Fatal("unrelated revision cancelled authorized response") |
| + } |
| + if !w.demoServingAllowed(rt, time.Now()) { |
| + t.Fatal("unchanged lifetime lost authority") |
| + } |
| +} |
| + |
| +func TestDemoServingStreamOutOfOrderSamples(t *testing.T) { |
| + w, _, rt, _ := demoControlFixFixture(t) |
| + now := time.Now() |
| + if !w.demoServingAllowed(rt, now.Add(2*time.Millisecond)) { |
| + t.Fatal("fresh sample refused") |
| + } |
| + if !w.demoServingAllowed(rt, now.Add(time.Millisecond)) { |
| + t.Fatal("scheduling order mistaken for clock rollback") |
| + } |
| + if !w.demoJobAllowed(demobuild.Job{DemoID: rt.DemoID, Lifetime: rt.DemoLifetime, Host: rt.Host}, now) { |
| + t.Fatal("job sample order closed serving") |
| + } |
| + if !w.demoServingAllowed(rt, time.Now()) { |
| + t.Fatal("fresh request remains closed") |
| + } |
| +} |
| + |
| +func TestDemoServingStreamEntryIsolation(t *testing.T) { |
| + for _, fault := range []string{"missing-counter", "invalid", "expired", "duplicate", "rounding", "wrong-host", "caps"} { |
| + t.Run(fault, func(t *testing.T) { |
| + w, c, rt, now := demoControlFixFixture(t) |
| + c.Revision++ |
| + bad := c.Demos[0] |
| + bad.Identity = demo.TrafficIdentity{ID: "shop2", Lifetime: "life2", Host: "shop2.example.com"} |
| + bad.Initialize = false |
| + switch fault { |
| + case "invalid": |
| + bad.Caps.Requests = 0 |
| + case "expired": |
| + bad.ExpiresAt = now.Unix() |
| + case "duplicate": |
| + bad.Initialize = true |
| + c.Demos = append(c.Demos, bad) |
| + case "rounding": |
| + c.ValidUntil = now.Add(31 * time.Second).Unix() |
| + case "wrong-host": |
| + bad.Identity.Host = "shop.other.example.com" |
| + case "caps": |
| + if err := w.traffic.Initialize(t.Context(), bad.Identity, bad.Caps); err != nil { |
| + t.Fatal(err) |
| + } |
| + bad.Caps.Requests++ |
| + } |
| + if fault != "rounding" { |
| + c.Demos = append(c.Demos, bad) |
| + } |
| + if err := w.applyDemoServing(c, now); err != nil { |
| + t.Fatalf("one entry rejected whole control: %v", err) |
| + } |
| + if !w.demoServingAllowed(rt, time.Now()) { |
| + t.Fatal("healthy lifetime closed") |
| + } |
| + if _, ok := w.serving.demos[bad.Identity]; ok { |
| + t.Fatal("bad lifetime accepted") |
| + } |
| + if w.serving.until.After(now.Add(30 * time.Second)) { |
| + t.Fatal("rounding extended probe bound") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoTrafficStoragePoisonStillRetires(t *testing.T) { |
| + w, c, _, _ := demoControlFixFixture(t) |
| + id := c.Demos[0].Identity |
| + _, err := w.traffic.db.Exec(`CREATE TABLE parent(id INTEGER PRIMARY KEY); CREATE TABLE child(id INTEGER REFERENCES parent(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER failed_commit BEFORE UPDATE ON demo_traffic BEGIN INSERT INTO child VALUES(1); END`) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if n, err := w.traffic.DebitBytes(t.Context(), id, 17); err == nil || n != 0 { |
| + t.Fatalf("failed commit authorized output: %d %v", n, err) |
| + } |
| + if !w.traffic.failed.Load() { |
| + t.Fatal("constraint failure did not close traffic") |
| + } |
| + if _, err := w.traffic.db.Exec(`DROP TRIGGER failed_commit`); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := w.traffic.Admit(t.Context(), id); err == nil { |
| + t.Fatal("storage failure reopened traffic") |
| + } |
| + if err := w.traffic.Fence(t.Context(), id); err != nil { |
| + t.Fatalf("traffic poison blocked fence: %v", err) |
| + } |
| + if err := w.traffic.Purge(t.Context(), id); err != nil { |
| + t.Fatalf("traffic poison blocked purge: %v", err) |
| + } |
| +} |
| + |
| +func TestDemoServingStreamScopedCancellation(t *testing.T) { |
| + for _, mode := range []string{"removed", "expired", "retired", "off"} { |
| + t.Run(mode, func(t *testing.T) { |
| + w, c, _, now := demoControlFixFixture(t) |
| + other := c.Demos[0] |
| + other.Identity = demo.TrafficIdentity{ID: "shop2", Lifetime: "life2", Host: "shop2.example.com"} |
| + c.Revision++ |
| + c.Demos = append(c.Demos, other) |
| + if err := w.applyDemoServing(c, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + cancelled := make(map[demo.TrafficIdentity]bool) |
| + all := false |
| + w.serving.cancel = func(ids ...demo.TrafficIdentity) { |
| + if len(ids) == 0 { |
| + all = true |
| + } |
| + for _, id := range ids { |
| + cancelled[id] = true |
| + } |
| + } |
| + c.Revision++ |
| + switch mode { |
| + case "removed": |
| + c.Demos = c.Demos[1:] |
| + case "expired": |
| + c.Demos[0].ExpiresAt = now.Unix() |
| + case "retired": |
| + if err := w.fenceDemoServing(t.Context(), c.Demos[0].Identity); err != nil { |
| + t.Fatal(err) |
| + } |
| + case "off": |
| + c.Enabled = false |
| + } |
| + if err := w.applyDemoServing(c, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if mode == "off" { |
| + if !all { |
| + t.Fatal("off did not cancel all") |
| + } |
| + return |
| + } |
| + id := demo.TrafficIdentity{ID: "shop", Lifetime: "life", Host: "shop.example.com"} |
| + if all || !cancelled[id] || cancelled[other.Identity] { |
| + t.Fatalf("wrong cancellation set: all=%t ids=%v", all, cancelled) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoServingStreamReconnectBackoff(t *testing.T) { |
| + w, c, _, now := demoControlFixFixture(t) |
| + w.closeDemoServing() |
| + if got := w.demoReconnectDelay(15 * time.Second); got != time.Second { |
| + t.Fatalf("healthy session backoff %s", got) |
| + } |
| + w.beginDemoServing() |
| + if got := w.demoReconnectDelay(time.Second); got != 2*time.Second { |
| + t.Fatalf("failed session backoff %s", got) |
| + } |
| + c.Probe = w.demoHeartbeat(now).ServingProbe |
| + c.Revision++ |
| + if err := w.applyDemoServing(c, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + w.closeDemoServing() |
| + if got := w.demoReconnectDelay(15 * time.Second); got != time.Second { |
| + t.Fatalf("recovery did not reset backoff: %s", got) |
| + } |
| +} |
| + |
| +// Cancel at the first debit UPDATE, after BEGIN has succeeded. The wrapper |
| +// forwards every database operation to the real SQLite driver. |
| +type demoCancelConnector struct { |
| + cancelBegin bool |
| + path string |
| + cancel context.CancelFunc |
| + once sync.Once |
| + driver sqlite.Driver |
| +} |
| + |
| +func (c *demoCancelConnector) Driver() driver.Driver { return &c.driver } |
| +func (c *demoCancelConnector) Connect(context.Context) (driver.Conn, error) { |
| + conn, err := c.driver.Open(c.path) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return &demoCancelConn{Conn: conn, owner: c}, nil |
| +} |
| + |
| +type demoCancelConn struct { |
| + driver.Conn |
| + owner *demoCancelConnector |
| +} |
| + |
| +func (c *demoCancelConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { |
| + if c.owner.cancelBegin && query == "BEGIN IMMEDIATE" { |
| + result, err := c.Conn.(driver.ExecerContext).ExecContext(ctx, query, args) |
| + if err != nil { |
| + return result, err |
| + } |
| + cancelled := false |
| + c.owner.once.Do(func() { c.owner.cancel(); cancelled = true }) |
| + if cancelled { |
| + return nil, ctx.Err() |
| + } |
| + return result, nil |
| + } |
| + if !c.owner.cancelBegin && strings.HasPrefix(query, "UPDATE demo_traffic SET") { |
| + c.owner.once.Do(c.owner.cancel) |
| + } |
| + return c.Conn.(driver.ExecerContext).ExecContext(ctx, query, args) |
| +} |
| +func (c *demoCancelConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { |
| + return c.Conn.(driver.QueryerContext).QueryContext(ctx, query, args) |
| +} |
| + |
| +func TestDemoTrafficCancellationAfterBegin(t *testing.T) { |
| + w, c, _, _ := demoControlFixFixture(t) |
| + id := c.Demos[0].Identity |
| + var path string |
| + if err := w.traffic.db.QueryRow(`SELECT file FROM pragma_database_list WHERE name='main'`).Scan(&path); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := w.traffic.db.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx, cancel := context.WithCancel(t.Context()) |
| + defer cancel() |
| + w.traffic.db = sql.OpenDB(&demoCancelConnector{path: path, cancel: cancel}) |
| + w.traffic.db.SetMaxOpenConns(1) |
| + if _, err := w.traffic.db.Exec(`PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON`); err != nil { |
| + t.Fatal(err) |
| + } |
| + n, err := w.traffic.DebitBytes(ctx, id, 17) |
| + if n != 0 || !errors.Is(err, context.Canceled) { |
| + t.Fatalf("cancelled request authorized output: %d %v", n, err) |
| + } |
| + var spent int64 |
| + if err := w.traffic.db.QueryRow(`SELECT body_bytes FROM demo_traffic`).Scan(&spent); err != nil || spent != 17 { |
| + t.Fatalf("in-flight transaction did not finish conservatively: %d %v", spent, err) |
| + } |
| + if w.traffic.failed.Load() { |
| + t.Fatal("in-flight cancellation poisoned traffic") |
| + } |
| + if err := w.traffic.Admit(t.Context(), id); err != nil { |
| + t.Fatalf("next request refused: %v", err) |
| + } |
| +} |
| + |
| +func TestDemoTrafficCancelledBeginIsolation(t *testing.T) { |
| + w, c, _, _ := demoControlFixFixture(t) |
| + id := c.Demos[0].Identity |
| + var path string |
| + if err := w.traffic.db.QueryRow(`SELECT file FROM pragma_database_list WHERE name='main'`).Scan(&path); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := w.traffic.db.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx, cancel := context.WithCancel(t.Context()) |
| + defer cancel() |
| + w.traffic.db = sql.OpenDB(&demoCancelConnector{path: path, cancel: cancel, cancelBegin: true}) |
| + w.traffic.db.SetMaxOpenConns(1) |
| + // SQLite can finish BEGIN, then report ctx.Err() from its deferred check. |
| + n, err := w.traffic.DebitBytes(ctx, id, 17) |
| + if n != 0 || !errors.Is(err, context.Canceled) { |
| + t.Fatalf("cancelled BEGIN authorized output: %d %v", n, err) |
| + } |
| + if err := w.traffic.Admit(t.Context(), id); err != nil { |
| + t.Fatalf("cancelled BEGIN leaked transaction into next request: %v", err) |
| + } |
| + if err := w.traffic.Fence(t.Context(), id); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := w.traffic.Purge(t.Context(), id); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
diff --git a/internal/host/demo_jobs.go b/internal/host/demo_jobs.go| index 25c02db20..9189e65c5 100644 |
| --- a/internal/host/demo_jobs.go |
| +++ b/internal/host/demo_jobs.go |
| @@ -108,7 +108,7 @@ func startDemoWorker(ctx context.Context, reg *registry.Registry, data release.S |
| w.complete = func(ctx context.Context, b []byte) error { return w.acknowledgeDemoPhaseHTTP(ctx, b, true) } |
| installed(w) |
| go func() { |
| - delay := time.Second |
| + var delay time.Duration |
| for { |
| err := w.Connect(ctx) |
| if ctx.Err() != nil { |
| @@ -116,6 +116,7 @@ func startDemoWorker(ctx context.Context, reg *registry.Registry, data release.S |
| } else if err != nil { |
| log.Printf("agent: demo stream: %v", err) |
| } |
| + delay = w.demoReconnectDelay(delay) |
| timer := time.NewTimer(delay) |
| select { |
| case <-ctx.Done(): |
| @@ -123,9 +124,6 @@ func startDemoWorker(ctx context.Context, reg *registry.Registry, data release.S |
| return |
| case <-timer.C: |
| } |
| - if delay < 15*time.Second { |
| - delay = min(delay*2, 15*time.Second) |
| - } |
| } |
| }() |
| } |
| @@ -496,9 +494,8 @@ func (w *demoWorker) Connect(ctx context.Context) error { |
| return errors.New("demo-build: malformed stream") |
| } |
| if msg.Serving != nil { |
| - if err := w.applyDemoServing(*msg.Serving, time.Now()); err != nil { |
| - return err |
| - } |
| + // Refusal closes serving, but retirement delivery must keep running. |
| + _ = w.applyDemoServing(*msg.Serving, time.Now()) |
| } |
| if len(msg.Retirement) > 0 { |
| // Keep one pending or running receipt per signed demo ID. Cleanup |
diff --git a/internal/host/demo_retirement_stream_test.go b/internal/host/demo_retirement_stream_test.go| index f5f527911..6f8907c69 100644 |
| --- a/internal/host/demo_retirement_stream_test.go |
| +++ b/internal/host/demo_retirement_stream_test.go |
| @@ -39,11 +39,14 @@ func (s *retirementReadStore) Get(ctx context.Context, key string) ([]byte, stri |
| func TestDemoRetirementStreamFailureIsolation(t *testing.T) { |
| for _, ready := range []bool{false, true} { |
| - t.Run(fmt.Sprint(ready), func(t *testing.T) { testDemoRetirementStream(t, ready, false) }) |
| + t.Run(fmt.Sprint(ready), func(t *testing.T) { testDemoRetirementStream(t, ready, false, false) }) |
| } |
| } |
| -func TestDemoRetirementSlowStream(t *testing.T) { testDemoRetirementStream(t, true, true) } |
| -func testDemoRetirementStream(t *testing.T, builderReady, slow bool) { |
| +func TestDemoRetirementSlowStream(t *testing.T) { testDemoRetirementStream(t, true, true, false) } |
| +func TestDemoServingStreamRefusalStillRetires(t *testing.T) { |
| + testDemoRetirementStream(t, true, false, true) |
| +} |
| +func testDemoRetirementStream(t *testing.T, builderReady, slow, refusedControl bool) { |
| t.Setenv("CARLOS_DEMO_ACCOUNT", "shop") |
| t.Setenv("CARLOS_DEMO_FLEET", "demo") |
| t.Setenv("CARLOS_DEMO_DOMAIN", "example.com") |
| @@ -171,7 +174,19 @@ func testDemoRetirementStream(t *testing.T, builderReady, slow bool) { |
| } |
| } |
| } |
| - if err := websocket.JSON.Send(ws, demobuild.StreamMessage{Serving: &demo.ServingControl{Enabled: true, Revision: 1, Probe: ready.ServingProbe, ValidUntil: time.Now().Add(30 * time.Second).Unix(), Demos: []demo.ServingDemo{{Identity: demo.TrafficIdentity{ID: jobDemo.ID, Host: jobDemo.Name + ".example.com", Lifetime: "life"}, Caps: demo.TrafficCaps{Requests: 2000, BodyBytes: 200000000}, ExpiresAt: time.Now().Add(time.Hour).Unix(), Initialize: true}}}}); err != nil { |
| + if refusedControl { |
| + // A rejected envelope and a missing initialized counter must not |
| + // prevent the same message's retirement or later stream work. |
| + for _, control := range []demo.ServingControl{ |
| + {Revision: 1, Probe: 0}, |
| + {Revision: 1, Probe: ready.ServingProbe, ValidUntil: time.Now().Add(30 * time.Second).Unix(), Enabled: true, Demos: []demo.ServingDemo{{Identity: demo.TrafficIdentity{ID: "shop", Lifetime: "life", Host: "shop.example.com"}, Caps: demo.TrafficCaps{Requests: 2000, BodyBytes: 200000000}, ExpiresAt: time.Now().Add(time.Hour).Unix()}}}, |
| + } { |
| + if websocket.JSON.Send(ws, demobuild.StreamMessage{Serving: &control, Retirement: wires[1]}) != nil { |
| + return |
| + } |
| + } |
| + } |
| + if err := websocket.JSON.Send(ws, demobuild.StreamMessage{Serving: &demo.ServingControl{Enabled: true, Revision: 2, Probe: ready.ServingProbe, ValidUntil: time.Now().Add(30 * time.Second).Unix(), Demos: []demo.ServingDemo{{Identity: demo.TrafficIdentity{ID: jobDemo.ID, Host: jobDemo.Name + ".example.com", Lifetime: "life"}, Caps: demo.TrafficCaps{Requests: 2000, BodyBytes: 200000000}, ExpiresAt: time.Now().Add(time.Hour).Unix(), Initialize: true}}}}); err != nil { |
| return |
| } |
| for range 3 { |
diff --git a/internal/host/demo_serving.go b/internal/host/demo_serving.go| index b795ed72d..7b4290a72 100644 |
| --- a/internal/host/demo_serving.go |
| +++ b/internal/host/demo_serving.go |
| @@ -27,7 +27,9 @@ type demoServingState struct { |
| demos map[demo.TrafficIdentity]demo.ServingDemo |
| retired map[demo.TrafficIdentity]bool |
| enabled bool |
| - cancel func() |
| + cancel func(...demo.TrafficIdentity) |
| + wallNow func() time.Time |
| + sessionHealthy bool |
| } |
| func (w *demoWorker) beginDemoServing() { |
| @@ -39,6 +41,7 @@ func (w *demoWorker) beginDemoServing() { |
| s.deadline = 0 |
| s.lastWall = 0 |
| s.ack = 0 |
| + s.sessionHealthy = false |
| if w.traffic == nil { |
| return |
| } |
| @@ -100,8 +103,8 @@ func (w *demoWorker) demoHeartbeat(now time.Time) demobuild.WorkerReady { |
| } |
| // The gate is also held around edge dispatch admission and each output write. |
| -// Installation closes the old snapshot first, drains writes and cancels old |
| -// responses before acknowledging the new revision. |
| +// Installation drains writes and cancels responses whose lifetimes lost |
| +// authority before acknowledging the new revision. |
| func (w *demoWorker) applyDemoServing(c demo.ServingControl, now time.Time) error { |
| entered, observed := time.Now(), now |
| s := &w.serving |
| @@ -119,40 +122,39 @@ func (w *demoWorker) applyDemoServing(c demo.ServingControl, now time.Time) erro |
| } |
| now = observed.Add(time.Since(entered)) |
| sent, ok := s.probes[c.Probe] |
| - if !s.connected || !ok || c.Probe == 0 || c.Revision <= 0 || c.Revision < s.revision || c.ValidUntil <= now.Unix() || c.ValidUntil > now.Add(30*time.Second).Unix() || (c.Revision == s.revision && c.ValidUntil <= s.deadline) || now.UnixNano() < s.lastWall || now.Before(sent) || !now.Before(sent.Add(30*time.Second)) || w.traffic == nil { |
| + if !s.connected || !ok || c.Probe == 0 || c.Revision <= 0 || c.Revision < s.revision || c.ValidUntil <= now.Unix() || (c.Revision == s.revision && c.ValidUntil <= s.deadline) || !s.observeClock() || now.Before(sent) || !now.Before(sent.Add(30*time.Second)) || w.traffic == nil { |
| return fail() |
| } |
| - // A revision change fences old requests even if global serving stays on. |
| - changed := c.Revision != s.revision || !c.Enabled |
| s.enabled = false |
| - if changed && s.cancel != nil { |
| - s.cancel() |
| - } |
| ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| defer cancel() |
| demos := make(map[demo.TrafficIdentity]demo.ServingDemo) |
| - hosts := make(map[string]bool) |
| + hosts := make(map[string]int) |
| + identities := make(map[demo.TrafficIdentity]int) |
| + for _, d := range c.Demos { |
| + hosts[d.Identity.Host]++ |
| + identities[d.Identity]++ |
| + } |
| for _, d := range c.Demos { |
| id := d.Identity |
| - if !validTrafficIdentity(id) || !d.Caps.Valid() || d.ExpiresAt <= now.Unix() || !strings.HasSuffix(id.Host, "."+w.cfg.Domain) || strings.Contains(strings.TrimSuffix(id.Host, "."+w.cfg.Domain), ".") || demos[id].Identity.ID != "" || hosts[id.Host] || s.retired[id] { |
| - return fail() |
| + if !validTrafficIdentity(id) || !d.Caps.Valid() || d.ExpiresAt <= now.Unix() || !strings.HasSuffix(id.Host, "."+w.cfg.Domain) || strings.Contains(strings.TrimSuffix(id.Host, "."+w.cfg.Domain), ".") || identities[id] != 1 || hosts[id.Host] != 1 || s.retired[id] { |
| + continue |
| } |
| - hosts[id.Host] = true |
| if w.reg != nil { |
| rt, err := w.reg.Get(id.Host) |
| if err != nil { |
| - return fail() |
| + continue |
| } |
| if rt != nil && (rt.FleetBox != w.box || rt.DemoID != id.ID || rt.DemoLifetime != id.Lifetime || rt.DemoExpiresAt != d.ExpiresAt) { |
| - return fail() |
| + continue |
| } |
| } |
| if d.Initialize { |
| if err := w.traffic.Initialize(ctx, id, d.Caps); err != nil { |
| - return fail() |
| + continue |
| } |
| } else if err := w.traffic.checkAssignment(ctx, id, d.Caps); err != nil { |
| - return fail() |
| + continue |
| } |
| demos[id] = d |
| } |
| @@ -176,7 +178,7 @@ func (w *demoWorker) applyDemoServing(c demo.ServingControl, now time.Time) erro |
| return fail() |
| } |
| now = observed.Add(time.Since(entered)) |
| - if now.Unix() >= c.ValidUntil || !now.Before(sent.Add(30*time.Second)) { |
| + if now.Unix() >= c.ValidUntil || !now.Before(sent.Add(30*time.Second)) || !s.observeClock() { |
| return fail() |
| } |
| until := sent.Add(30 * time.Second) |
| @@ -184,10 +186,21 @@ func (w *demoWorker) applyDemoServing(c demo.ServingControl, now time.Time) erro |
| if absolute := now.Add(time.Unix(c.ValidUntil, 0).Sub(now)); absolute.Before(until) { |
| until = absolute |
| } |
| + if s.cancel != nil { |
| + if !c.Enabled || !w.cfg.EdgeProtections { |
| + s.cancel() |
| + } else { |
| + for id, old := range s.demos { |
| + if _, ok := demos[id]; !ok || old.ExpiresAt <= now.Unix() { |
| + s.cancel(id) |
| + } |
| + } |
| + } |
| + } |
| s.demos = demos |
| s.revision, s.ack, s.deadline = c.Revision, c.Revision, c.ValidUntil |
| s.until = until |
| - s.lastWall = now.UnixNano() |
| + s.sessionHealthy = true |
| s.enabled = c.Enabled && w.cfg.EdgeProtections |
| return nil |
| } |
| @@ -201,11 +214,9 @@ func (w *demoWorker) demoServingAllowed(rt registry.Route, now time.Time) bool { |
| if !s.connected || !s.enabled { |
| return false |
| } |
| - if now.UnixNano() < s.lastWall { |
| - s.enabled = false |
| - s.ack = 0 |
| + if !s.observeClock() { |
| + return false |
| } |
| - s.lastWall = max(s.lastWall, now.UnixNano()) |
| id := demo.TrafficIdentity{ID: rt.DemoID, Lifetime: rt.DemoLifetime, Host: rt.Host} |
| d, ok := s.demos[id] |
| return s.connected && s.enabled && now.Before(s.until) && now.Unix() < s.deadline && ok && !s.retired[id] && d.ExpiresAt == rt.DemoExpiresAt && now.Unix() < d.ExpiresAt && rt.FleetBox == w.box && rt.FleetBox != "" && rt.Region == "fleet/"+w.cfg.Fleet && rt.Account == w.cfg.Account && rt.HoldOp == "" && !registry.IsHold(rt.Status) |
| @@ -223,7 +234,7 @@ func (w *demoWorker) fenceDemoServing(ctx context.Context, id demo.TrafficIdenti |
| delete(s.demos, id) |
| s.mu.Unlock() |
| if s.cancel != nil { |
| - s.cancel() |
| + s.cancel(id) |
| } |
| if w.traffic == nil { |
| return demo.ErrTrafficUnavailable |
| @@ -252,10 +263,34 @@ func (w *demoWorker) demoJobAllowed(j demobuild.Job, now time.Time) bool { |
| now = now.Add(time.Since(entered)) |
| id := demo.TrafficIdentity{ID: j.DemoID, Lifetime: j.Lifetime, Host: j.Host} |
| d, ok := s.demos[id] |
| - if now.UnixNano() < s.lastWall { |
| + if !s.observeClock() { |
| + return false |
| + } |
| + return s.connected && s.enabled && s.ack > 0 && now.Before(s.until) && now.Unix() < s.deadline && ok && !s.retired[id] && now.Unix() < d.ExpiresAt |
| +} |
| + |
| +// Sample the wall clock under mu, so scheduling cannot reorder observations. |
| +// Request timestamps are used for expiry only, never as rollback evidence. |
| +func (s *demoServingState) observeClock() bool { |
| + now := time.Now() |
| + if s.wallNow != nil { |
| + now = s.wallNow() |
| + } |
| + wall := now.UnixNano() |
| + if wall < s.lastWall { |
| s.enabled = false |
| s.ack = 0 |
| + return false |
| } |
| - s.lastWall = max(s.lastWall, now.UnixNano()) |
| - return s.connected && s.enabled && s.ack > 0 && now.Before(s.until) && now.Unix() < s.deadline && ok && !s.retired[id] && now.Unix() < d.ExpiresAt |
| + s.lastWall = wall |
| + return true |
| +} |
| + |
| +func (w *demoWorker) demoReconnectDelay(previous time.Duration) time.Duration { |
| + w.serving.mu.Lock() |
| + defer w.serving.mu.Unlock() |
| + if w.serving.sessionHealthy || previous == 0 { |
| + return time.Second |
| + } |
| + return min(previous*2, 15*time.Second) |
| } |
diff --git a/internal/host/demo_serving_test.go b/internal/host/demo_serving_test.go| index f1effa8df..9351907a2 100644 |
| --- a/internal/host/demo_serving_test.go |
| +++ b/internal/host/demo_serving_test.go |
| @@ -70,25 +70,28 @@ func TestDemoServingStream(t *testing.T) { |
| if err = w.applyDemoServing(c, now); err != nil { |
| t.Fatal(err) |
| } |
| - if w.demoServingAllowed(rt, now.Add(-time.Second)) { |
| + w.serving.wallNow = func() time.Time { return now.Add(-time.Second) } |
| + if w.demoServingAllowed(rt, time.Now()) { |
| t.Fatal("clock rollback open") |
| } |
| + w.serving.wallNow = nil |
| w.beginDemoServing() |
| c.Probe = w.demoHeartbeat(now).ServingProbe |
| if _, err = store.db.Exec(`DELETE FROM demo_traffic`); err != nil { |
| t.Fatal(err) |
| } |
| - if err = w.applyDemoServing(c, now); err == nil { |
| - t.Fatal("missing row with Initialize=false accepted") |
| + if err = w.applyDemoServing(c, now); err != nil || w.demoServingAllowed(rt, time.Now()) { |
| + t.Fatal("missing counter must close only its lifetime", err) |
| } |
| c.Demos[0].Initialize = true |
| - if err = w.applyDemoServing(c, now); err == nil { |
| - t.Fatal("lost row recreated") |
| + c.Revision++ |
| + if err = w.applyDemoServing(c, now); err != nil || w.demoServingAllowed(rt, time.Now()) { |
| + t.Fatal("lost row must stay closed", err) |
| } |
| } |
| func TestDemoServingStreamBoundsAndRestart(t *testing.T) { |
| - for _, fault := range []string{"missing", "old-revision", "expired", "future", "delayed", "rollback", "non-increasing", "wrong-host", "caps", "duplicate"} { |
| + for _, fault := range []string{"missing", "old-revision", "expired", "delayed", "rollback", "non-increasing"} { |
| t.Run(fault, func(t *testing.T) { |
| path := filepath.Join(t.TempDir(), "traffic.db") |
| store, err := openDemoTraffic(path) |
| @@ -115,8 +118,6 @@ func TestDemoServingStreamBoundsAndRestart(t *testing.T) { |
| c.Revision = 1 |
| case "expired": |
| c.ValidUntil = at.Unix() |
| - case "future": |
| - c.ValidUntil = at.Add(31 * time.Second).Unix() |
| case "delayed": |
| at = now.Add(32 * time.Second) |
| c.ValidUntil = at.Add(30 * time.Second).Unix() |
| @@ -124,12 +125,6 @@ func TestDemoServingStreamBoundsAndRestart(t *testing.T) { |
| at = now.Add(-time.Second) |
| case "non-increasing": |
| c.ValidUntil = now.Add(30 * time.Second).Unix() |
| - case "wrong-host": |
| - c.Demos[0].Identity.Host = "shop.other.example.com" |
| - case "caps": |
| - c.Demos[0].Caps.Requests++ |
| - case "duplicate": |
| - c.Demos = append(c.Demos, c.Demos[0]) |
| } |
| if err = w.applyDemoServing(c, at); err == nil { |
| t.Fatal("malformed control accepted") |
| @@ -166,7 +161,7 @@ func TestDemoServingStreamDrainsBeforeAck(t *testing.T) { |
| t.Fatal(err) |
| } |
| var cancelled atomic.Bool |
| - w.serving.cancel = func() { cancelled.Store(true) } |
| + w.serving.cancel = func(...demo.TrafficIdentity) { cancelled.Store(true) } |
| w.demoServingGate().RLock() |
| done := make(chan error, 1) |
| c.Enabled = false |
diff --git a/internal/host/demo_traffic.go b/internal/host/demo_traffic.go| index cf1ca126a..790b6c180 100644 |
| --- a/internal/host/demo_traffic.go |
| +++ b/internal/host/demo_traffic.go |
| @@ -10,7 +10,8 @@ import ( |
| "sync/atomic" |
| "github.com/carlosframework/platform/internal/demo" |
| - _ "modernc.org/sqlite" |
| + "modernc.org/sqlite" |
| + sqlite3 "modernc.org/sqlite/lib" |
| ) |
| // Only the authenticated assignment stream may initialize an identity. Traffic |
| @@ -74,7 +75,7 @@ func (s *demoTrafficStore) Close() error { return s.db.Close() } |
| // BEGIN IMMEDIATE serializes read/check/update across all database handles. |
| // Returning success requires COMMIT, including SQLite's FULL sync, to succeed. |
| func (s *demoTrafficStore) transaction(ctx context.Context, f func(*sql.Conn) error) error { |
| - if s == nil || s.db == nil || s.failed.Load() { |
| + if s == nil || s.db == nil { |
| return demo.ErrTrafficUnavailable |
| } |
| c, err := s.db.Conn(ctx) |
| @@ -82,14 +83,16 @@ func (s *demoTrafficStore) transaction(ctx context.Context, f func(*sql.Conn) er |
| return err |
| } |
| defer c.Close() |
| + // BEGIN can take effect before the driver reports cancellation. Always |
| + // clean up the connection, including when BEGIN returns an error. |
| + defer c.ExecContext(context.Background(), "ROLLBACK") |
| if _, err = c.ExecContext(ctx, "BEGIN IMMEDIATE"); err != nil { |
| return err |
| } |
| - defer c.ExecContext(context.Background(), "ROLLBACK") |
| if err = f(c); err != nil { |
| return err |
| } |
| - _, err = c.ExecContext(ctx, "COMMIT") |
| + _, err = c.ExecContext(context.WithoutCancel(ctx), "COMMIT") |
| return err |
| } |
| func validTrafficIdentity(id demo.TrafficIdentity) bool { |
| @@ -127,15 +130,21 @@ func (s *demoTrafficStore) Initialize(ctx context.Context, id demo.TrafficIdenti |
| } |
| func (s *demoTrafficStore) debit(ctx context.Context, id demo.TrafficIdentity, n int64, admit bool) (int64, error) { |
| - if !validTrafficIdentity(id) || n < 0 { |
| + if s == nil || s.failed.Load() || !validTrafficIdentity(id) || n < 0 { |
| return 0, demo.ErrTrafficUnavailable |
| } |
| var spent int64 |
| err := s.transaction(ctx, func(c *sql.Conn) error { |
| + if s.failed.Load() { |
| + return demo.ErrTrafficUnavailable |
| + } |
| + // Once BEGIN succeeds, finish the debit and FULL-sync commit even if |
| + // the client leaves. A cancelled caller receives no output allowance. |
| + txnCtx := context.WithoutCancel(ctx) |
| var host string |
| var requests, bytes, rc, bc int64 |
| var terminal int |
| - err := c.QueryRowContext(ctx, `SELECT a.host,t.requests,t.body_bytes,a.request_cap,a.byte_cap,a.terminal FROM demo_assignments a JOIN demo_traffic t USING(demo_id,lifetime) WHERE a.demo_id=? AND a.lifetime=?`, id.ID, id.Lifetime).Scan(&host, &requests, &bytes, &rc, &bc, &terminal) |
| + err := c.QueryRowContext(txnCtx, `SELECT a.host,t.requests,t.body_bytes,a.request_cap,a.byte_cap,a.terminal FROM demo_assignments a JOIN demo_traffic t USING(demo_id,lifetime) WHERE a.demo_id=? AND a.lifetime=?`, id.ID, id.Lifetime).Scan(&host, &requests, &bytes, &rc, &bc, &terminal) |
| if err != nil { |
| return err |
| } |
| @@ -151,17 +160,40 @@ func (s *demoTrafficStore) debit(ctx context.Context, id demo.TrafficIdentity, n |
| spent = min(n, bc-bytes) |
| bytes += spent |
| } |
| - _, err = c.ExecContext(ctx, `UPDATE demo_traffic SET requests=?,body_bytes=? WHERE demo_id=? AND lifetime=?`, requests, bytes, id.ID, id.Lifetime) |
| + _, err = c.ExecContext(txnCtx, `UPDATE demo_traffic SET requests=?,body_bytes=? WHERE demo_id=? AND lifetime=?`, requests, bytes, id.ID, id.Lifetime) |
| return err |
| }) |
| if err != nil { |
| - if s != nil && !errors.Is(err, demo.ErrTrafficLimit) && !errors.Is(err, demo.ErrTrafficUnavailable) && !errors.Is(err, sql.ErrNoRows) { |
| + if demoTrafficStorageFault(err) { |
| s.failed.Store(true) |
| } |
| return 0, err |
| } |
| + if err := ctx.Err(); err != nil { |
| + return 0, err |
| + } |
| return spent, nil |
| } |
| + |
| +// Only SQLite storage failures poison traffic. Cancellation, interruption and |
| +// lock contention refuse this attempt without disabling unrelated lifetimes. |
| +func demoTrafficStorageFault(err error) bool { |
| + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { |
| + return false |
| + } |
| + var dbErr *sqlite.Error |
| + if !errors.As(err, &dbErr) { |
| + return false |
| + } |
| + switch dbErr.Code() & 0xff { |
| + case sqlite3.SQLITE_IOERR, sqlite3.SQLITE_CORRUPT, sqlite3.SQLITE_NOTADB, |
| + sqlite3.SQLITE_FULL, sqlite3.SQLITE_READONLY, sqlite3.SQLITE_CANTOPEN, |
| + sqlite3.SQLITE_CONSTRAINT: |
| + return true |
| + } |
| + return false |
| +} |
| + |
| func (s *demoTrafficStore) Admit(ctx context.Context, id demo.TrafficIdentity) error { |
| _, err := s.debit(ctx, id, 0, true) |
| return err |