carlos / platform Public

fix: one backoff for every idle claim wait

Persist a shared retry budget for every coordinator phase and reset it on durable progress or new external signals. Keep recovery, acknowledgments, target generations and deadline scheduling consistent across restarts. Guard every wait with counted local stores and simulated ticks through the cap.
codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 8ebbf75710f5dc949a8c418dc527156d62801ddf parent 4030d08
7 files changed, +483 −27
  • internal/console/apidemobox.go +2 −2
  • internal/console/demo_claim_backoff_test.go +356 −0
  • internal/console/demo_claim_store.go +1 −0
  • internal/console/demo_claim_transfer.go +117 −21
  • internal/console/demo_claim_transfer_test.go +1 −1
  • internal/console/demo_expiry.go +1 −1
  • internal/console/demo_jobs.go +5 −2

Intent

Human

<task-notification> <task-id>btm7dqbml</task-id> <tool-use-id>toolu_01PG9MeDkEntKGJxVoKCYxrm</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/btm7dqbml.output</output-file> <status>killed</status> <summary>Background command "S=/home/paulca/.cache/tmp/claude-1001/agent-start-demo-3; until [ -f $S/cifix.done ]; do sleep 60; done; tail -1 $S/cifix.log" was stopped after reaching its background time limit</summary> <note>If the work in progress still needs it, start it again with `run_in_background` and a longer `timeout`. If it already had the longest `timeout` allowed, do not restart it. Either way, report that it was stopped.</note> </task-notification>

Human

<task-notification> <task-id>bh9yw9xkm</task-id> <tool-use-id>toolu_01Lb5rUg2oxSNjV2fLBMgbcY</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/bh9yw9xkm.output</output-file> <status>completed</status> <summary>Background command "until amadan ci status carlos/platform -branch agent-start-demo-3 2&gt;&amp;1 | head -1 | grep -q '76f358e4.*\(passed\|failed\|succeeded\|green\)'; do sleep 60; done; amadan ci status carlos/platform -branch agent-start-demo-3 2&gt;&amp;1 | head -3" completed (exit code 0)</summary> </task-notification>

diff --git a/internal/console/apidemobox.go b/internal/console/apidemobox.go
index 6a267ba89..5ed26739e 100644
--- a/internal/console/apidemobox.go
+++ b/internal/console/apidemobox.go
@@ -506,13 +506,13 @@ func (s *Server) ackDemoClaim(ctx context.Context, id, action string, generation
}
switch action {
case "freeze":
- _, err := s.store.db.ExecContext(ctx, `UPDATE demo_claim_progress SET hold_ack=1,retry_at=0 WHERE operation_id=?`, id)
+ _, err := s.store.db.ExecContext(ctx, `UPDATE demo_claim_progress SET hold_ack=1,retry_at=0,retry_delay=0 WHERE operation_id=? AND hold_ack=0`, id)
if err != nil {
return err
}
case "export": // Successful snapshot receipt already advanced the operation.
case "abort":
- _, err := s.store.db.ExecContext(ctx, `UPDATE demo_claim_progress SET abort_ack=1,retry_at=0 WHERE operation_id=? AND cleanup=1`, id)
+ _, err := s.store.db.ExecContext(ctx, `UPDATE demo_claim_progress SET abort_ack=1,retry_at=0,retry_delay=0 WHERE operation_id=? AND cleanup=1 AND abort_ack=0`, id)
if err != nil {
return err
}
diff --git a/internal/console/demo_claim_backoff_test.go b/internal/console/demo_claim_backoff_test.go
new file mode 100644
index 000000000..22163048e
--- /dev/null
+++ b/internal/console/demo_claim_backoff_test.go
@@ -0,0 +1,356 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "io"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/democlaim"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// Count all store operations, including failures before the underlying fake.
+type claimWaitStore struct {
+ *demoDisabledStore
+ failGet string
+}
+
+func (s *claimWaitStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if key == s.failGet {
+ s.gets.Add(1)
+ return nil, "", errors.New("injected unavailable object")
+ }
+ return s.demoDisabledStore.Get(ctx, key)
+}
+
+func (s *claimWaitStore) Open(ctx context.Context, key string) (io.ReadCloser, string, error) {
+ s.gets.Add(1)
+ return release.OpenObjectStreaming(ctx, s.Store, key)
+}
+
+func (s *claimWaitStore) PutFrom(ctx context.Context, key string, body io.ReadSeeker, size int64, tag string) (string, error) {
+ s.puts.Add(1)
+ return release.PutObjectFrom(ctx, s.Store, key, body, size, tag)
+}
+
+func TestDemoClaimRequestCostEveryWait(t *testing.T) {
+ for _, state := range []string{
+ "reserved", "freezing/hold", "freezing/ack", "copying/snapshot", "copying/storedSnapshot",
+ "verifying/placement", "committed/open", "committed/moved", "committed/retire",
+ "aborting/cleanup", "aborting/abort_ack", "done", "aborted",
+ } {
+ t.Run(state, func(t *testing.T) {
+ s, op, data := claimTransferFixture(t)
+ quiet := false
+ failGet := ""
+ switch state {
+ case "reserved":
+ s.demoClaimBoundary = func(at string) error {
+ if at == "pipeline" {
+ return errors.New("pipeline reply lost")
+ }
+ return nil
+ }
+ case "freezing/hold", "freezing/ack":
+ claimAdvance(t, s, op)
+ if state == "freezing/hold" {
+ claimBackoffSQL(t, s, `UPDATE demo_claim_progress SET hold_ready=0 WHERE operation_id=?`, op.ID)
+ d, err := s.store.demoByID(t.Context(), op.DemoID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ failGet = "apps/" + d.AccountSqid + "/" + d.App + "/instances/" + d.Host + ".json"
+ } else {
+ quiet = true
+ }
+ case "copying/snapshot", "copying/storedSnapshot":
+ claimAdvance(t, s, op)
+ if err := s.ackDemoClaim(t.Context(), op.ID, "freeze", uint64(op.Generation)); err != nil {
+ t.Fatal(err)
+ }
+ claimAdvance(t, s, op)
+ if state == "copying/storedSnapshot" {
+ claimBackoffSQL(t, s, `UPDATE demo_claim_progress SET snapshot_sha=?,snapshot_bytes=4096 WHERE operation_id=?`, strings.Repeat("a", 64), op.ID)
+ } else {
+ quiet = true
+ }
+ case "verifying/placement":
+ claimToVerify(t, s, op, data)
+ s.demoTransport = roundTripFunc(func(*http.Request) (*http.Response, error) { return nil, errors.New("placement pending") })
+ case "committed/open", "committed/moved", "committed/retire", "done":
+ claimToVerify(t, s, op, data)
+ boundary := "commit"
+ if state == "committed/moved" {
+ boundary = "open"
+ }
+ if state == "committed/retire" {
+ boundary = "moved"
+ }
+ if state != "done" {
+ s.demoClaimBoundary = func(at string) error {
+ if at == boundary {
+ return errors.New("pause before wait")
+ }
+ return nil
+ }
+ }
+ _ = s.advanceDemoClaim(t.Context(), op.ID)
+ s.demoClaimBoundary = nil
+ if boundary == "open" || boundary == "moved" {
+ claimBackoffSQL(t, s, `DELETE FROM demo_claim_outbox WHERE operation_id=? AND step=?`, op.ID, boundary)
+ }
+ switch state {
+ case "committed/open":
+ s.demoTransport = roundTripFunc(func(*http.Request) (*http.Response, error) { return nil, errors.New("destination offline") })
+ case "committed/moved":
+ failGet = democlaim.MovedKey
+ case "committed/retire":
+ d, err := s.store.demoByID(t.Context(), op.DemoID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ failGet = release.AppTombstoneKey(d.AccountSqid, d.App)
+ case "done":
+ quiet = true
+ }
+ case "aborting/cleanup":
+ claimToVerify(t, s, op, data)
+ if err := s.abortDemoClaim(t.Context(), op.ID, "test"); err != nil {
+ t.Fatal(err)
+ }
+ case "aborting/abort_ack", "aborted":
+ // This wait needs no object cleanup. Keep the fixture entirely local.
+ claimAdvance(t, s, op)
+ claimBackoffSQL(t, s, `UPDATE demo_claim_ops SET phase='aborting' WHERE id=?`, op.ID)
+ claimBackoffSQL(t, s, `UPDATE demo_claim_progress SET cleanup=1,hold_cleared=1,reason='test' WHERE operation_id=?`, op.ID)
+ fresh, err := s.store.demoClaimOp(t.Context(), op.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = s.setDemoClaimWork(t.Context(), fresh, "abort", democlaim.AbortDeliveryWindow); err != nil {
+ t.Fatal(err)
+ }
+ if state == "aborted" {
+ claimBackoffSQL(t, s, `UPDATE demo_claim_ops SET phase='aborted' WHERE id=?`, op.ID)
+ }
+ quiet = true
+ }
+
+ // Keep safety deadlines beyond the simulated backoff horizon. The
+ // separate deadline test checks that those deadlines can interrupt it.
+ now := time.Now()
+ claimBackoffSQL(t, s, `UPDATE demo_claim_ops SET deadline=? WHERE id=?`, now.Add(2*time.Hour).Unix(), op.ID)
+ claimBackoffSQL(t, s, `UPDATE demo_claim_progress SET phase_until=?,retry_at=0,retry_delay=0 WHERE operation_id=?`, now.Add(time.Hour).UnixNano(), op.ID)
+ counted := &claimWaitStore{demoDisabledStore: &demoDisabledStore{demoCountingStore: &demoCountingStore{Store: s.cfg.Releases}}, failGet: failGet}
+ seed := &claimWaitStore{demoDisabledStore: &demoDisabledStore{demoCountingStore: &demoCountingStore{Store: s.cfg.SeedData}}}
+ s.cfg.Releases, s.cfg.SeedData = counted, seed
+ requests := func() int32 {
+ return counted.requests() + counted.deletes.Load() + seed.requests() + seed.deletes.Load()
+ }
+ peer := s.demoJobs.peers["box"]
+ drain := func() {
+ peer.reconcile = false
+ select {
+ case <-peer.wake:
+ default:
+ }
+ }
+ drain()
+ for attempt := 0; attempt < 10; attempt++ {
+ beforeRequests := requests()
+ _ = s.reconcileDemoClaims(t.Context(), now)
+ if quiet && (requests() != beforeRequests || peer.reconcile || len(peer.wake) != 0) {
+ t.Fatal("worker or terminal wait polled or notified")
+ }
+ current, err := s.store.demoClaimOp(t.Context(), op.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if current.Phase == "done" || current.Phase == "aborted" {
+ if !quiet {
+ t.Fatal("wait unexpectedly completed")
+ }
+ now = now.Add(5 * time.Minute)
+ continue
+ }
+ var retryAt, delay int64
+ if err = s.store.db.QueryRow(`SELECT retry_at,retry_delay FROM demo_claim_progress WHERE operation_id=?`, op.ID).Scan(&retryAt, &delay); err != nil {
+ t.Fatal(err)
+ }
+ want := min(2*time.Second*time.Duration(1<<attempt), 5*time.Minute)
+ if time.Duration(delay) != want || time.Unix(0, retryAt).Sub(now) < want || time.Unix(0, retryAt).Sub(now) > want+time.Second {
+ t.Fatalf("attempt %d: delay=%v due=%v want=%v", attempt, time.Duration(delay), time.Unix(0, retryAt).Sub(now), want)
+ }
+ if !quiet && requests() == beforeRequests {
+ t.Fatal("due pass did not exercise store wait")
+ }
+ drain()
+ afterRequests := requests()
+ for _, tick := range []time.Time{now, now.Add(want / 2), time.Unix(0, retryAt-1)} {
+ if err = s.reconcileDemoClaims(t.Context(), tick); err != nil {
+ t.Fatal(err)
+ }
+ if requests() != afterRequests || peer.reconcile || len(peer.wake) != 0 {
+ t.Fatal("tick bypassed persisted backoff")
+ }
+ }
+ // Restart recovery must obey the same persisted clock.
+ if err = s.ReconcileDemoClaims(t.Context(), true); err != nil {
+ t.Fatal(err)
+ }
+ if requests() != afterRequests || peer.reconcile || len(peer.wake) != 0 {
+ t.Fatal("restart bypassed persisted backoff")
+ }
+ now = time.Unix(0, retryAt)
+ }
+ })
+ }
+}
+
+func claimBackoffSQL(t *testing.T, s *Server, query string, args ...any) {
+ t.Helper()
+ if _, err := s.store.db.Exec(query, args...); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestDemoClaimBackoffSignals(t *testing.T) {
+ for _, signal := range []string{"freeze_ack", "abort_ack", "snapshot", "target_change"} {
+ t.Run(signal, func(t *testing.T) {
+ s, op, data := claimTransferFixture(t)
+ claimAdvance(t, s, op)
+ if signal == "snapshot" {
+ if err := s.ackDemoClaim(t.Context(), op.ID, "freeze", uint64(op.Generation)); err != nil {
+ t.Fatal(err)
+ }
+ claimAdvance(t, s, op)
+ }
+ if signal == "abort_ack" {
+ claimBackoffSQL(t, s, `UPDATE demo_claim_ops SET phase='aborting' WHERE id=?`, op.ID)
+ claimBackoffSQL(t, s, `UPDATE demo_claim_progress SET cleanup=1,hold_cleared=1,reason='test' WHERE operation_id=?`, op.ID)
+ fresh, err := s.store.demoClaimOp(t.Context(), op.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = s.setDemoClaimWork(t.Context(), fresh, "abort", democlaim.AbortDeliveryWindow); err != nil {
+ t.Fatal(err)
+ }
+ }
+ claimBackoffSQL(t, s, `UPDATE demo_claim_progress SET retry_at=?,retry_delay=? WHERE operation_id=?`, time.Now().Add(5*time.Minute).UnixNano(), int64(5*time.Minute), op.ID)
+ switch signal {
+ case "freeze_ack", "abort_ack":
+ action := strings.TrimSuffix(signal, "_ack")
+ if err := s.ackDemoClaim(t.Context(), op.ID, action, uint64(op.Generation)); err != nil {
+ t.Fatal(err)
+ }
+ case "snapshot":
+ if err := claimSnapshot(t, s, op, data); err != nil {
+ t.Fatal(err)
+ }
+ case "target_change":
+ s.cfg.Demo.Enabled = false
+ watch := release.NewChangeWatch(s.cfg.Releases)
+ scopeKey := "apps/" + op.Target.Sqid + "/" + op.Target.App + "/instances/" + op.Target.Host + ".json"
+ if err := release.BumpChangeIndex(t.Context(), s.cfg.Releases, scopeKey); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := watch.Poll(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ unlock := s.acctLocks.lock("demo-claim:" + op.ID)
+ err := s.ObserveDemoJobs(t.Context(), watch)
+ unlock()
+ if !errors.Is(err, ErrDemoBusy) {
+ t.Fatalf("busy generation consumed: %v", err)
+ }
+ if err := s.ObserveDemoJobs(t.Context(), watch); err != nil {
+ t.Fatal(err)
+ }
+ // An unchanged observed generation must not reset a later wait.
+ defer func() {
+ claimBackoffSQL(t, s, `UPDATE demo_claim_progress SET retry_at=123,retry_delay=456 WHERE operation_id=?`, op.ID)
+ // A new observer after restart sees the same generation.
+ s.demoJobs.observed = nil
+ if err := s.ObserveDemoJobs(t.Context(), watch); err != nil {
+ t.Fatal(err)
+ }
+ var at, delay int64
+ if err := s.store.db.QueryRow(`SELECT retry_at,retry_delay FROM demo_claim_progress WHERE operation_id=?`, op.ID).Scan(&at, &delay); err != nil {
+ t.Fatal(err)
+ }
+ if at != 123 || delay != 456 {
+ t.Fatal("unchanged target reset backoff")
+ }
+ }()
+ }
+ var at, delay int64
+ if err := s.store.db.QueryRow(`SELECT retry_at,retry_delay FROM demo_claim_progress WHERE operation_id=?`, op.ID).Scan(&at, &delay); err != nil {
+ t.Fatal(err)
+ }
+ if at != 0 || delay != 0 {
+ t.Fatalf("signal retained backoff: at=%d delay=%d", at, delay)
+ }
+ if err := s.backoffDemoClaim(t.Context(), op.ID, false, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.store.db.QueryRow(`SELECT retry_delay FROM demo_claim_progress WHERE operation_id=?`, op.ID).Scan(&delay); err != nil {
+ t.Fatal(err)
+ }
+ if delay != int64(2*time.Second) {
+ t.Fatal("signal did not reset to base")
+ }
+ if signal == "freeze_ack" || signal == "abort_ack" {
+ if err := s.ackDemoClaim(t.Context(), op.ID, strings.TrimSuffix(signal, "_ack"), uint64(op.Generation)); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.store.db.QueryRow(`SELECT retry_delay FROM demo_claim_progress WHERE operation_id=?`, op.ID).Scan(&delay); err != nil {
+ t.Fatal(err)
+ }
+ if delay != int64(2*time.Second) {
+ t.Fatal("duplicate ack reset backoff")
+ }
+ }
+ })
+ }
+}
+
+func TestDemoClaimBackoffDeadline(t *testing.T) {
+ s, op, data := claimTransferFixture(t)
+ claimToVerify(t, s, op, data)
+ now := time.Now()
+ deadline := now.Add(time.Second).UnixNano()
+ claimBackoffSQL(t, s, `UPDATE demo_claim_progress SET retry_delay=?,phase_until=? WHERE operation_id=?`, int64(5*time.Minute), deadline, op.ID)
+ if err := s.backoffDemoClaim(t.Context(), op.ID, false, now); err != nil {
+ t.Fatal(err)
+ }
+ p, err := s.claimProgress(t.Context(), op.ID)
+ if err != nil || p.RetryAt != deadline {
+ t.Fatalf("deadline missed: %d %v", p.RetryAt, err)
+ }
+ // Expired deadlines may cause one abort attempt, then errors in that
+ // attempt must obey the same backoff as any other stalled phase.
+ claimBackoffSQL(t, s, `UPDATE demo_claim_ops SET deadline=1 WHERE id=?`, op.ID)
+ claimBackoffSQL(t, s, `UPDATE demo_claim_progress SET phase_until=1 WHERE operation_id=?`, op.ID)
+ if err := s.backoffDemoClaim(t.Context(), op.ID, false, now); err != nil {
+ t.Fatal(err)
+ }
+ counted := &demoCountingStore{Store: s.cfg.Releases}
+ s.cfg.Releases = counted
+ if err := s.ReconcileDemoClaims(t.Context(), true); err != nil {
+ t.Fatal(err)
+ }
+ if counted.requests() != 0 {
+ t.Fatal("overdue deadline bypassed retry budget")
+ }
+ if err := s.backoffDemoClaim(t.Context(), op.ID, true, now); err != nil {
+ t.Fatal(err)
+ }
+ p, err = s.claimProgress(t.Context(), op.ID)
+ if err != nil || p.RetryAt != now.Add(2*time.Second).UnixNano() {
+ t.Fatalf("progress did not reset to base: %d %v", p.RetryAt, err)
+ }
+}
diff --git a/internal/console/demo_claim_store.go b/internal/console/demo_claim_store.go
index ec2ff94e7..452bfba3e 100644
--- a/internal/console/demo_claim_store.go
+++ b/internal/console/demo_claim_store.go
@@ -52,6 +52,7 @@ func (s *Store) migrateDemoClaims() error {
for _, stmt := range []string{
`ALTER TABLE demo_claim_progress ADD COLUMN hold_cleared INTEGER NOT NULL DEFAULT 0`,
`ALTER TABLE demo_claim_progress ADD COLUMN retry_delay INTEGER NOT NULL DEFAULT 0`,
+ `ALTER TABLE demo_claim_progress ADD COLUMN target_generation INTEGER NOT NULL DEFAULT 0`,
} {
if _, err = s.db.Exec(stmt); err != nil && !strings.Contains(err.Error(), "duplicate column") {
return err
diff --git a/internal/console/demo_claim_transfer.go b/internal/console/demo_claim_transfer.go
index ca9198cf1..af6688647 100644
--- a/internal/console/demo_claim_transfer.go
+++ b/internal/console/demo_claim_transfer.go
@@ -154,6 +154,9 @@ func (s *Server) advanceDemoClaimLocked(ctx context.Context, id string) error {
return err
}
}
+ if p.HoldReady {
+ return nil
+ }
return s.ensureDemoClaimHold(ctx, op, false)
}
if p.Action != "export" {
@@ -506,7 +509,7 @@ func (s *Server) acceptDemoClaimSnapshotLocked(ctx context.Context, id string, b
if n != 1 {
return ErrDemoToken
}
- if _, err = tx.ExecContext(ctx, `UPDATE demo_claim_progress SET phase_until=?,retry_at=0 WHERE operation_id=?`, min(op.Deadline.UnixNano(), time.Now().Add(60*time.Second).UnixNano()), id); err != nil {
+ if _, err = tx.ExecContext(ctx, `UPDATE demo_claim_progress SET phase_until=?,retry_at=0,retry_delay=0 WHERE operation_id=?`, min(op.Deadline.UnixNano(), time.Now().Add(60*time.Second).UnixNano()), id); err != nil {
return err
}
if err = tx.Commit(); err != nil {
@@ -879,18 +882,22 @@ func (s *Server) finishDemoClaimAbort(ctx context.Context, op claimOp) error {
// ReconcileDemoClaims reads only SQL when idle or waiting for a worker.
// Object work has a persisted retry clock and uses the existing job loop.
-func (s *Server) ReconcileDemoClaims(ctx context.Context, restart bool) error {
+func (s *Server) ReconcileDemoClaims(ctx context.Context, _ bool) error {
+ return s.reconcileDemoClaims(ctx, time.Now())
+}
+
+func (s *Server) reconcileDemoClaims(ctx context.Context, now time.Time) error {
+ started := time.Now()
if s.cfg.HostClaim || s.store.claimGated() {
return nil
}
- now := time.Now()
if err := s.pruneDemoClaims(ctx, now); err != nil {
return err
}
+ // A process restart is not progress. Keep the persisted retry budget.
rows, err := s.store.db.QueryContext(ctx, `SELECT o.id FROM demo_claim_ops o LEFT JOIN demo_claim_progress p ON p.operation_id=o.id
- WHERE o.phase NOT IN ('done','aborted') AND (p.operation_id IS NULL OR (? AND o.phase!='committed') OR p.retry_at<=? OR o.deadline<=? AND o.phase NOT IN ('aborting','committed'))
- AND (o.phase NOT IN ('freezing','copying') OR o.phase='copying' AND p.snapshot_sha!='' OR p.work=X'' OR o.phase='freezing' AND p.hold_ready=0 OR p.hold_ack=1 AND o.phase='freezing' OR p.phase_until<=? OR o.deadline<=?) AND (o.phase!='aborting' OR p.cleanup=0 OR p.hold_cleared=0 OR p.abort_ack=1 OR p.action!='abort' OR p.reason='operator' OR p.phase_until<=? OR o.source_expires_at<=?)
- ORDER BY o.id LIMIT ?`, restart, now.UnixNano(), now.Unix(), now.UnixNano(), now.Unix(), now.UnixNano(), now.Unix(), demobuild.QueueLimit)
+ WHERE o.phase NOT IN ('done','aborted') AND (p.operation_id IS NULL OR p.retry_at<=?)
+ ORDER BY o.id LIMIT ?`, now.UnixNano(), demobuild.QueueLimit)
if err != nil {
return err
}
@@ -914,36 +921,125 @@ func (s *Server) ReconcileDemoClaims(ctx context.Context, restart bool) error {
}
func() {
defer unlock()
- var before, after int
- if e := s.store.db.QueryRowContext(ctx, `SELECT count(*) FROM demo_claim_outbox WHERE operation_id=?`, id).Scan(&before); e != nil {
+ // The loop and backstop can select the same due row. Recheck after
+ // acquiring its lock so a completed pass cannot spend this budget twice.
+ var due bool
+ if e := s.store.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM demo_claim_ops o LEFT JOIN demo_claim_progress p ON p.operation_id=o.id WHERE o.id=? AND o.phase NOT IN ('done','aborted') AND coalesce(p.retry_at,0)<=?)`, id, now.UnixNano()).Scan(&due); e != nil {
errs = append(errs, e)
return
}
- if err = s.advanceDemoClaimLocked(ctx, id); err != nil {
- errs = append(errs, err)
+ if !due {
+ return
}
- if e := s.store.db.QueryRowContext(ctx, `SELECT count(*) FROM demo_claim_outbox WHERE operation_id=?`, id).Scan(&after); e != nil {
+ before, e := s.demoClaimCheckpoint(ctx, id)
+ if e != nil {
errs = append(errs, e)
return
}
- if after < before {
- if _, e := s.store.db.ExecContext(ctx, `UPDATE demo_claim_progress SET retry_delay=0 WHERE operation_id=?`, id); e != nil {
- errs = append(errs, e)
- return
- }
+ if e = s.advanceDemoClaimLocked(ctx, id); e != nil {
+ errs = append(errs, e)
}
- // Keep failed committed work bounded across ticks and console restarts.
- _, e := s.store.db.ExecContext(ctx, `UPDATE demo_claim_progress SET
- retry_at=? + CASE WHEN (SELECT phase FROM demo_claim_ops WHERE id=operation_id)='committed' THEN min(max(retry_delay*2,?),?) ELSE ? END,
- retry_delay=CASE WHEN (SELECT phase FROM demo_claim_ops WHERE id=operation_id)='committed' THEN min(max(retry_delay*2,?),?) ELSE 0 END
- WHERE operation_id=?`, time.Now().UnixNano(), int64(2*time.Second), int64(5*time.Minute), int64(2*time.Second), int64(2*time.Second), int64(5*time.Minute), id)
+ after, e := s.demoClaimCheckpoint(ctx, id)
if e != nil {
errs = append(errs, e)
+ return
+ }
+ if e = s.backoffDemoClaim(ctx, id, before != after, now.Add(time.Since(started))); e != nil {
+ errs = append(errs, e)
}
}()
}
return errors.Join(errs...)
}
+
+// A checkpoint contains durable forward progress, excluding retry clocks and
+// refreshed delivery signatures. Reissuing the same work is still an idle wait.
+type demoClaimCheckpoint struct {
+ Phase, Version, Artifact, Action, SHA, Reason string
+ HoldReady, HoldAck, Copied, Cleanup, AbortAck, HoldCleared bool
+ Bytes, Outbox int64
+}
+
+func (s *Server) demoClaimCheckpoint(ctx context.Context, id string) (demoClaimCheckpoint, error) {
+ var c demoClaimCheckpoint
+ err := s.store.db.QueryRowContext(ctx, `SELECT o.phase,o.version,o.artifact_sha256,
+ coalesce(p.action,''),coalesce(p.snapshot_sha,''),coalesce(p.reason,''),
+ coalesce(p.hold_ready,0),coalesce(p.hold_ack,0),coalesce(p.copied,0),coalesce(p.cleanup,0),coalesce(p.abort_ack,0),coalesce(p.hold_cleared,0),coalesce(p.snapshot_bytes,0),
+ (SELECT count(*) FROM demo_claim_outbox WHERE operation_id=o.id)
+ FROM demo_claim_ops o LEFT JOIN demo_claim_progress p ON p.operation_id=o.id WHERE o.id=?`, id).
+ Scan(&c.Phase, &c.Version, &c.Artifact, &c.Action, &c.SHA, &c.Reason, &c.HoldReady, &c.HoldAck, &c.Copied, &c.Cleanup, &c.AbortAck, &c.HoldCleared, &c.Bytes, &c.Outbox)
+ return c, err
+}
+
+// Every coordinator attempt shares this persisted budget, including errors and
+// partial cleanup. A future safety deadline may shorten the next wait once;
+// an overdue deadline must not bypass backoff on every subsequent tick.
+func (s *Server) backoffDemoClaim(ctx context.Context, id string, progress bool, now time.Time) error {
+ tx, err := s.store.demoTx(ctx)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ // Admission or mutation setup can fail before advance creates progress.
+ if _, err = tx.ExecContext(ctx, `INSERT OR IGNORE INTO demo_claim_progress(operation_id) VALUES(?)`, id); err != nil {
+ return err
+ }
+ _, err = tx.ExecContext(ctx, `UPDATE demo_claim_progress SET
+ retry_delay=CASE WHEN ? THEN ? ELSE min(max(retry_delay*2,?),?) END
+ WHERE operation_id=?`, progress, int64(2*time.Second), int64(2*time.Second), int64(5*time.Minute), id)
+ if err != nil {
+ return err
+ }
+ _, err = tx.ExecContext(ctx, `UPDATE demo_claim_progress SET retry_at=min(?+retry_delay,
+ CASE WHEN phase_until>? AND EXISTS(SELECT 1 FROM demo_claim_ops WHERE id=operation_id AND phase NOT IN ('committed','done','aborted')) THEN phase_until ELSE ?+retry_delay END,
+ coalesce((SELECT CASE WHEN phase NOT IN ('aborting','committed','done','aborted') AND deadline*1000000000>? THEN deadline*1000000000
+ WHEN phase='aborting' AND source_expires_at*1000000000>? THEN source_expires_at*1000000000 ELSE ?+retry_delay END FROM demo_claim_ops WHERE id=operation_id),?+retry_delay))
+ WHERE operation_id=?`, now.UnixNano(), now.UnixNano(), now.UnixNano(), now.UnixNano(), now.UnixNano(), now.UnixNano(), now.UnixNano(), id)
+ if err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+
+// Target changes arrive through the existing watch. Consume each generation
+// only after its operation lock is available, so a concurrent pass cannot lose
+// the reset. Persist the generation so restart cannot replay an old signal.
+// The hint grants no authority; the next pass rereads the record.
+func (s *Server) dispatchDemoClaimChanges(ctx context.Context, scope string, generation uint64) error {
+ if s.cfg.HostClaim || s.store.claimGated() {
+ return nil
+ }
+ rows, err := s.store.db.QueryContext(ctx, `SELECT id FROM demo_claim_ops WHERE 'apps/'||target_sqid||'/'||app=? AND phase NOT IN ('done','aborted')`, scope)
+ if err != nil {
+ return err
+ }
+ var ids []string
+ for rows.Next() {
+ var id string
+ if err = rows.Scan(&id); err != nil {
+ break
+ }
+ ids = append(ids, id)
+ }
+ if err = errors.Join(err, rows.Err(), rows.Close()); err != nil {
+ return err
+ }
+ for _, id := range ids {
+ unlock, ok := s.acctLocks.tryLock("demo-claim:" + id)
+ if !ok {
+ return ErrDemoBusy
+ }
+ _, err = s.store.db.ExecContext(ctx, `INSERT INTO demo_claim_progress(operation_id,target_generation) VALUES(?,?)
+ ON CONFLICT(operation_id) DO UPDATE SET retry_at=0,retry_delay=0,target_generation=excluded.target_generation
+ WHERE target_generation<excluded.target_generation`, id, generation)
+ unlock()
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
func (s *Server) pruneDemoClaims(ctx context.Context, now time.Time) error {
// demoTx acquires the writer lock with a settings-row update. Avoid that
// write when neither capabilities nor terminal operations need pruning.
diff --git a/internal/console/demo_claim_transfer_test.go b/internal/console/demo_claim_transfer_test.go
index 927b34621..801c38c83 100644
--- a/internal/console/demo_claim_transfer_test.go
+++ b/internal/console/demo_claim_transfer_test.go
@@ -822,7 +822,7 @@ func TestDemoClaimRequestCostHoldCheckpoint(t *testing.T) {
func TestDemoClaimTransferProgressMigration(t *testing.T) {
s, op, _ := claimAbortWaitFixture(t)
- for _, column := range []string{"hold_cleared", "retry_delay"} {
+ for _, column := range []string{"hold_cleared", "retry_delay", "target_generation"} {
if _, err := s.store.db.Exec("ALTER TABLE demo_claim_progress DROP COLUMN " + column); err != nil {
t.Fatal(err)
}
diff --git a/internal/console/demo_expiry.go b/internal/console/demo_expiry.go
index a9ac3b9f4..0653c0103 100644
--- a/internal/console/demo_expiry.go
+++ b/internal/console/demo_expiry.go
@@ -138,7 +138,7 @@ func (s *Server) retireDemoLocked(ctx context.Context, d DemoRow, now time.Time,
if _, err = tx.ExecContext(ctx, `INSERT OR IGNORE INTO demo_claim_progress(operation_id) SELECT id FROM demo_claim_ops WHERE demo_id=? AND phase NOT IN ('committed','done','aborted')`, d.ID); err != nil {
return err
}
- if _, err = tx.ExecContext(ctx, `UPDATE demo_claim_progress SET reason='operator',retry_at=0 WHERE operation_id IN (SELECT id FROM demo_claim_ops WHERE demo_id=? AND phase NOT IN ('committed','done','aborted'))`, d.ID); err != nil {
+ if _, err = tx.ExecContext(ctx, `UPDATE demo_claim_progress SET reason='operator',retry_at=0,retry_delay=0 WHERE operation_id IN (SELECT id FROM demo_claim_ops WHERE demo_id=? AND phase NOT IN ('committed','done','aborted'))`, d.ID); err != nil {
return err
}
if _, err = tx.ExecContext(ctx, `UPDATE demo_claim_ops SET phase='aborting' WHERE demo_id=? AND phase NOT IN ('committed','done','aborted')`, d.ID); err != nil {
diff --git a/internal/console/demo_jobs.go b/internal/console/demo_jobs.go
index a7288020f..65d259e47 100644
--- a/internal/console/demo_jobs.go
+++ b/internal/console/demo_jobs.go
@@ -425,7 +425,7 @@ func (s *Server) ReconcileDemoJobs(ctx context.Context, restart bool) error {
// ObserveDemoJobs reads only the existing watch's memory. Failed dispatches
// retain their old generation. It adds no Poll or object-store timer.
func (s *Server) ObserveDemoJobs(ctx context.Context, watch *release.ChangeWatch) error {
- if !s.cfg.Demo.Enabled || watch == nil {
+ if watch == nil {
return nil
}
s.demoJobs.dispatch.Lock()
@@ -445,6 +445,9 @@ func (s *Server) ObserveDemoJobs(ctx context.Context, watch *release.ChangeWatch
}
sort.Strings(scopes)
for _, scope := range scopes {
+ if err := s.dispatchDemoClaimChanges(ctx, scope, obs[scope]); err != nil {
+ return err
+ }
if err := s.DispatchDemoChanges(ctx, []string{scope}); err != nil {
return err
}
@@ -478,7 +481,7 @@ func (s *Server) RunDemoJobs(ctx context.Context, watch *release.ChangeWatch) {
log.Printf("console: %s: %v", demoClaimPending, err)
}
var claimNext sql.NullInt64
- _ = s.store.db.QueryRowContext(ctx, `SELECT min(CASE WHEN o.phase='freezing' AND p.hold_ready=1 AND p.hold_ack=0 OR o.phase='copying' AND p.snapshot_sha='' THEN min(p.phase_until,o.deadline*1000000000) WHEN o.phase='aborting' AND p.cleanup=1 AND p.hold_cleared=1 AND p.abort_ack=0 AND p.action='abort' AND p.reason!='operator' THEN min(p.phase_until,o.source_expires_at*1000000000) ELSE max(coalesce(p.retry_at,0),?) END) FROM demo_claim_ops o LEFT JOIN demo_claim_progress p ON p.operation_id=o.id WHERE o.phase NOT IN ('done','aborted')`, time.Now().Add(time.Second).UnixNano()).Scan(&claimNext)
+ _ = s.store.db.QueryRowContext(ctx, `SELECT min(max(coalesce(p.retry_at,0),?)) FROM demo_claim_ops o LEFT JOIN demo_claim_progress p ON p.operation_id=o.id WHERE o.phase NOT IN ('done','aborted')`, time.Now().Add(time.Second).UnixNano()).Scan(&claimNext)
if claimNext.Valid {
// A busy upload may leave an overdue operation for the next pass.
claimNext.Int64 = max(claimNext.Int64, time.Now().Add(time.Second).UnixNano())