feat: branch verified stateless wakes before database acquisition
Select the staged identity before database work and add the database-free wake path, generation mode, environment stripping and binary arguments. Exercise web and declared workers without a serving replica. Fallback, transition and durable release integration follow in this continuation.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
13 files changed,
+407
−73
approved_stateless_replicas_copy_test.go+1 −1internal/activator/activator.go+90 −62internal/activator/backend_exec.go+10 −3internal/activator/cmdunit.go+1 −1internal/activator/genbackend.go+1 −0internal/activator/hasecrets.go+9 −1internal/activator/maintenance.go+8 −0internal/activator/rootfs.go+1 −1internal/activator/rootfsenv.go+4 −3internal/activator/stateless.go+123 −0internal/activator/stateless_test.go+150 −0internal/activator/swapadmit.go+1 −1internal/host/agent.go+8 −0
Intent
Human
<task-notification> <task-id>beh2akqr6</task-id> <tool-use-id>toolu_01UCfcTRLRoECVxWGXLTTGFe</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/412bbef6-9468-4e8d-b9fe-5343bad21de8/tasks/beh2akqr6.output</output-file> <status>completed</status> <summary>Background command "Wait for 3a continuation 2" completed (exit code 0)</summary> </task-notification>
diff --git a/approved_stateless_replicas_copy_test.go b/approved_stateless_replicas_copy_test.go| index cff3fa2e9..fb9b3df36 100644 |
| --- a/approved_stateless_replicas_copy_test.go |
| +++ b/approved_stateless_replicas_copy_test.go |
| @@ -9,7 +9,7 @@ import ( |
| const statelessReplicaCopyDeck = "docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md" |
| -var statelessReplicaBuiltCopy = []string{"SR-1-C01", "SR-1-C02", "SR-1-C03", "SR-1-C04", "SR-1-C05", "SR-1-C12", "SR-1-C09", "SR-1-C10", "SR-1-C13"} |
| +var statelessReplicaBuiltCopy = []string{"SR-1-C07", "SR-1-C01", "SR-1-C02", "SR-1-C03", "SR-1-C04", "SR-1-C05", "SR-1-C12", "SR-1-C09", "SR-1-C10", "SR-1-C13"} |
| func statelessReplicaCopyRows(t *testing.T) []copyRow { |
| t.Helper() |
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index dfc07aec8..cbbfcea0a 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -1246,6 +1246,8 @@ type Service struct { |
| // record observation and supplies the canonical manifest digest, not |
| // the staged artifact digest. Missing observations refuse execution. |
| Coordinator CoordinatorClient |
| + StorageDeclaration func(context.Context, registry.Route, release.StagedIdentity) (bool, string, error) |
| + ReplicaDeployID func(replicas.Identity, replicas.Build, *replicas.Deploy) (string, error) |
| ObserveReplicaRelease func(context.Context, registry.Route) (replicas.Identity, replicas.Build, *replicas.Deploy, error) |
| replicaReleaseLocks sync.Map |
| @@ -1782,7 +1784,7 @@ func (a *Service) begin(ctx context.Context, rt registry.Route, stamp bool, req |
| // lost lease found at request time turns into a stop, and the |
| // request waits for it then re-wakes — recovery is the routine |
| // wake path. |
| - if repErr := e.rep.Err(); repErr != nil || e.proc.Exited() { |
| + if repErr := servingError(e); repErr != nil || e.proc.Exited() { |
| why := StopExited |
| if repErr != nil { |
| log.Printf("activator: LEASE LOST for %s (%v) — standing down", e.host, repErr) |
| @@ -1914,7 +1916,7 @@ func (a *Service) BeginSidecarRequest(ctx context.Context, rt registry.Route) er |
| // the recovery stops at the stop: the loop then finds a stopping |
| // (or absent) entry and turns this request away instead of |
| // chaining into a re-wake. |
| - if repErr := e.rep.Err(); repErr != nil || e.proc.Exited() { |
| + if repErr := servingError(e); repErr != nil || e.proc.Exited() { |
| why := StopExited |
| if repErr != nil { |
| log.Printf("activator: LEASE LOST for %s (%v) — standing down", e.host, repErr) |
| @@ -2561,6 +2563,11 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro |
| e.plan, e.firstWake = plan, plan.FirstWake |
| a.mu.Unlock() |
| } |
| + if g, ok := a.backend.(configAdmitter); ok { |
| + if err := g.AdmitConfig(ctx, rt); err != nil { |
| + return w, err |
| + } |
| + } |
| // 0.8. A staged build, planned or pinned, is published before anything |
| // execs it (spec §4.2, §8.5): the entry now names it (and a plan's |
| // fallback), so the write puts both in root's pin set. A failed write |
| @@ -2586,6 +2593,80 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro |
| } |
| } |
| + // 2b. One executable identity for this wake (settings spec §4.2, Astra |
| + // I1 #5): chosen now, recorded now, under the lease taken in step 1 and |
| + // before the seed and the spawn, and the only file this wake runs, its |
| + // seed included (settleWakeIdentity). A route whose backend cannot pin |
| + // an executable (identityFor nil: a unit-backed row, which systemd execs |
| + // from the live link itself) keeps today's calls and records nothing. |
| + // Any refusal here has run nothing: the lease goes back and the wake |
| + // fails, never blaming the build. |
| + // |
| + // A planned wake asks its selection gate first (checkPlan, ruling |
| + // R-REPLAN), so a replan lands before the identity is chosen and the |
| + // seed and the boot run one build. spawnPlanned asks again at the exec, |
| + // and startPinnedAt records again if that later replan changes the |
| + // build. |
| + if plan.planned() { |
| + next, err := a.checkPlan(ctx, e, rt, plan) |
| + if err != nil { |
| + return w, fmt.Errorf("start %s: %w", host, err) |
| + } |
| + plan = next |
| + } |
| + ib := identityFor(a.backend, rt) |
| + var id release.StagedIdentity |
| + if ib == nil && held != "" && !plan.planned() { |
| + // A held route whose backend cannot pin an executable (a unit row: |
| + // systemd execs the live link itself): nothing here can capture the |
| + // file, so the link is read once more just before the start. It |
| + // narrows a repoint after the wait; it cannot close it. |
| + if v := a.liveVersion(host); v != held { |
| + return w, fmt.Errorf("start %s: %w: %s is on %q, wants %s", host, errStaleLink, host, v, held) |
| + } |
| + } |
| + if ib != nil { |
| + var ( |
| + idErr error |
| + wctx context.Context |
| + ) |
| + id, w.pend, wctx, idErr = a.settleWakeIdentity(ctx, ib, e, rt, held, heldID) |
| + if idErr != nil { |
| + return w, fmt.Errorf("start %s: %w", host, idErr) |
| + } |
| + if id.StagedPath == "" { |
| + // A live link outside the version store with no hook (ruling |
| + // R-EXEC-NOVERSION-2): today's live-link wake, nothing recorded. |
| + ib = nil |
| + } else { |
| + // The record is pending on wctx, written at the first exec |
| + // (amadan #272). |
| + ctx = wctx |
| + } |
| + } |
| + w.steps.mark(a.now(), "identity") |
| + |
| + modeID := id |
| + if plan.planned() { |
| + modeID = plan.Boot |
| + } |
| + if e.pin != nil { |
| + modeID, _ = stagedIdentityOf(*e.pin) |
| + } |
| + if modeID.StagedPath != "" { |
| + mode, digest, modeErr := a.storageMode(ctx, rt, modeID) |
| + if modeErr != nil { |
| + return w, modeErr |
| + } |
| + if mode { |
| + ctx = context.WithValue(ctx, statelessWakeKey{}, statelessWakeInput{rt: rt, plan: plan, w: w, digest: digest}) |
| + return a.doStatelessWake(ctx, e, modeID) |
| + } |
| + } else if rt.Stateless { |
| + return w, errStorageDeclaration |
| + } |
| + |
| + rt.Stateless = false |
| // 1. The lease first: everything after this line is done as the prefix's |
| // single writer. Contention is not retried here — on one box it means a |
| // previous incarnation hasn't released; tell the client to come back after |
| @@ -2723,62 +2804,6 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro |
| } |
| } |
| - // 2b. One executable identity for this wake (settings spec §4.2, Astra |
| - // I1 #5): chosen now, recorded now, under the lease taken in step 1 and |
| - // before the seed and the spawn, and the only file this wake runs, its |
| - // seed included (settleWakeIdentity). A route whose backend cannot pin |
| - // an executable (identityFor nil: a unit-backed row, which systemd execs |
| - // from the live link itself) keeps today's calls and records nothing. |
| - // Any refusal here has run nothing: the lease goes back and the wake |
| - // fails, never blaming the build. |
| - // |
| - // A planned wake asks its selection gate first (checkPlan, ruling |
| - // R-REPLAN), so a replan lands before the identity is chosen and the |
| - // seed and the boot run one build. spawnPlanned asks again at the exec, |
| - // and startPinnedAt records again if that later replan changes the |
| - // build. |
| - if plan.planned() { |
| - next, err := a.checkPlan(ctx, e, rt, plan) |
| - if err != nil { |
| - w.stopOutcome.leaseReleased = a.giveBack(ctx, host, lease) |
| - return w, fmt.Errorf("start %s: %w", host, err) |
| - } |
| - plan = next |
| - } |
| - ib := identityFor(a.backend, rt) |
| - var id release.StagedIdentity |
| - if ib == nil && held != "" && !plan.planned() { |
| - // A held route whose backend cannot pin an executable (a unit row: |
| - // systemd execs the live link itself): nothing here can capture the |
| - // file, so the link is read once more just before the start. It |
| - // narrows a repoint after the wait; it cannot close it. |
| - if v := a.liveVersion(host); v != held { |
| - w.stopOutcome.leaseReleased = a.giveBack(ctx, host, lease) |
| - return w, fmt.Errorf("start %s: %w: %s is on %q, wants %s", host, errStaleLink, host, v, held) |
| - } |
| - } |
| - if ib != nil { |
| - var ( |
| - idErr error |
| - wctx context.Context |
| - ) |
| - id, w.pend, wctx, idErr = a.settleWakeIdentity(ctx, ib, e, rt, held, heldID) |
| - if idErr != nil { |
| - w.stopOutcome.leaseReleased = a.giveBack(ctx, host, lease) |
| - return w, fmt.Errorf("start %s: %w", host, idErr) |
| - } |
| - if id.StagedPath == "" { |
| - // A live link outside the version store with no hook (ruling |
| - // R-EXEC-NOVERSION-2): today's live-link wake, nothing recorded. |
| - ib = nil |
| - } else { |
| - // The record is pending on wctx, written at the first exec |
| - // (amadan #272). |
| - ctx = wctx |
| - } |
| - } |
| - w.steps.mark(a.now(), "identity") |
| - |
| // 3. First-boot seed, strictly between the restore and the spawn — so it |
| // runs before Start's first health probe, and a brand-new instance is born |
| // seeded rather than briefly serving an empty database. fresh is the |
| @@ -3181,6 +3206,7 @@ func (a *Service) installProcLocked(e *actEntry, rep Rep, proc Proc, g Gen) { |
| } |
| e.proc = proc |
| e.gen = g |
| + e.route.Stateless = g.Stateless |
| if e.route.Rootfs() { |
| a.watchResidentLeaseLocked(e) |
| } |
| @@ -3778,7 +3804,7 @@ func (a *Service) WakeWorker(rt registry.Route) error { |
| // makes a broken sidecar look healthy. A respawn in flight is not a |
| // dead child: its proc is mid-replacement, so leave it be. |
| if !e.workerRespawning { |
| - if repErr := e.rep.Err(); repErr != nil || e.proc.Exited() { |
| + if repErr := servingError(e); repErr != nil || e.proc.Exited() { |
| why := StopExited |
| if repErr != nil { |
| log.Printf("activator: LEASE LOST for %s (%v) — standing down", e.host, repErr) |
| @@ -4947,7 +4973,9 @@ func (a *Service) finishStop(e *actEntry, outcome *stopObservation) { |
| ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| defer cancel() |
| repErr := ErrStopUnproven |
| - if _, ha := haEntryRep(e); ha { |
| + if e.gen.Stateless { |
| + repErr = nil |
| + } else if _, ha := haEntryRep(e); ha { |
| // An HA host releases with a marker, written last and only over a |
| // proven stop and an empty host slice (releaseHAClean, r3.2). |
| // Unproven, nothing is written: the stop stays pending, with the |
| @@ -5099,7 +5127,7 @@ func (a *Service) LastSweep() time.Time { |
| // conditions are checked here again so the mark never depends on the |
| // caller's order. The caller holds a.mu. |
| func (a *Service) markCleanParkLocked(e *actEntry) { |
| - if a.fences[e.host] != 0 || e.rep == nil || e.rep.Err() != nil || procCrashed(e.proc) { |
| + if a.fences[e.host] != 0 || servingError(e) != nil || procCrashed(e.proc) { |
| return |
| } |
| e.parkedInc = e.workerInc |
| @@ -5185,7 +5213,7 @@ func (a *Service) sweepOnce() { |
| if e.workerRespawning { |
| continue |
| } |
| - if err := e.rep.Err(); err != nil { |
| + if err := servingError(e); err != nil { |
| log.Printf("activator: LEASE LOST for %s (%v) — standing down", e.host, err) |
| a.beginStopLocked(e, StopLeaseLost) |
| continue |
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go| index c24d42b94..cca688230 100644 |
| --- a/internal/activator/backend_exec.go |
| +++ b/internal/activator/backend_exec.go |
| @@ -2194,7 +2194,7 @@ func (b *ExecBackend) startGenFrom(ctx context.Context, rt registry.Route, n uin |
| } |
| proc, ver, err = b.startChildAt(ctx, rt, sock, n, flatExe, tier) |
| } |
| - g := Gen{N: n, Socket: sock, Control: sock + ".control"} |
| + g := Gen{N: n, Socket: sock, Control: sock + ".control", Stateless: rt.Stateless} |
| if err != nil { |
| // The handle goes back with the error (P2-13): a spawn that failed |
| // may have left generation n running, and its number is what the |
| @@ -2488,7 +2488,11 @@ func (b *ExecBackend) spawnChildFrom(ctx context.Context, rt registry.Route, soc |
| // then its check of the resolved build (liveGate) is the hook, asked at |
| // the same point. |
| cmd, settle, err := b.spawnInCgroupAtTier(rt, child, ownTier, tier, func() *exec.Cmd { |
| - cmd := exec.Command(bin, "--socket", sock, "--db", dbPath) |
| + argv := []string{bin, "--socket", sock, "--db", dbPath} |
| + if rt.Stateless { |
| + argv = b.statelessArgv(rt, bin, sock) |
| + } |
| + cmd := exec.Command(argv[0], argv[1:]...) |
| cmd.Env = childEnv(childVars) |
| // The child logs through the agent's own stderr/stdout (journald |
| // under systemd); there's no per-instance unit to own a log stream |
| @@ -2579,7 +2583,7 @@ func (b *ExecBackend) agentOwnedVars(rt registry.Route, control string, fileEnv |
| // crashed at start over that on the first roll. Agent-owned like the |
| // three above: a tenant's env file does not get to tell an app it is |
| // some other host. |
| - return withVar(childVars, "CARLOS_HOST", rt.Host) |
| + return storageVars(rt, withVar(childVars, "CARLOS_HOST", rt.Host)) |
| } |
| // seedVars is the seed's environment over fileEnv: the control-channel |
| @@ -2688,6 +2692,9 @@ func (b *ExecBackend) spawnUnitFrom(ctx context.Context, rt registry.Route, sock |
| } |
| childVars := b.agentOwnedVars(rt, sock+".control", fileEnv, ctl != nil) |
| argv := []string{b.liveLink(rt.Host), "--socket", sock, "--db", p.dbPath} |
| + if rt.Stateless { |
| + argv = b.statelessArgv(rt, b.liveLink(rt.Host), sock) |
| + } |
| steps.mark(time.Now(), "prepare ("+prep.String()+")") |
| if err := b.writeLaunchFor(p, instancectl.RoleRun, gen, rt.Host, argv, childEnv(childVars)); err != nil { |
| return fail(err) |
diff --git a/internal/activator/cmdunit.go b/internal/activator/cmdunit.go| index c88a60ee8..5fefd398e 100644 |
| --- a/internal/activator/cmdunit.go |
| +++ b/internal/activator/cmdunit.go |
| @@ -224,7 +224,7 @@ func (b *ExecBackend) cmdVars(rt registry.Route, fileEnv map[string]string, dbPa |
| v = withVar(v, "CARLOS_HOST", rt.Host) |
| v = withVar(v, "CARLOS_DB", dbPath) |
| v = withVar(v, "CARLOS_RUN_ID", runID) |
| - return withVar(v, "CARLOS_RUN_DIR", runDir) |
| + return storageVars(rt, withVar(v, "CARLOS_RUN_DIR", runDir)) |
| } |
| // ttyVars is a session's environment over fileEnv: cmdVars without a |
diff --git a/internal/activator/genbackend.go b/internal/activator/genbackend.go| index c210bccc5..1f4fee56a 100644 |
| --- a/internal/activator/genbackend.go |
| +++ b/internal/activator/genbackend.go |
| @@ -234,6 +234,7 @@ func (a *Service) SetLiveExecGate(gate func(rt registry.Route, build string) err |
| // a runtime this agent does not know is refused. Neither ever reaches a |
| // binary arm, where a flat row would exec its staged path as a program. |
| func (b *ExecBackend) StartStaged(ctx context.Context, rt registry.Route, g Gen) (Gen, Proc, error) { |
| + rt.Stateless = g.Stateless |
| if err := refuseUnknownRuntime(rt); err != nil { |
| return g, nil, err |
| } |
diff --git a/internal/activator/hasecrets.go b/internal/activator/hasecrets.go| index 9424cf724..2ff1f5a8b 100644 |
| --- a/internal/activator/hasecrets.go |
| +++ b/internal/activator/hasecrets.go |
| @@ -5,6 +5,7 @@ import ( |
| "encoding/json" |
| "errors" |
| "fmt" |
| + "github.com/carlosframework/platform/internal/release" |
| "net/http" |
| "os" |
| "path/filepath" |
| @@ -195,7 +196,7 @@ func (b *ExecBackend) captureLaunchEnv(rt registry.Route) (capturedEnv, error) { |
| // after the read is never what the launch is handed. An eligible host's |
| // takes the same capture into its escrow (escrowedLaunchEnv). Any other |
| // host's is instanceEnvLayer, unchanged. |
| -func (b *ExecBackend) launchEnvLayer(ctx context.Context, rt registry.Route) (map[string]string, instancekey.Layer, error) { |
| +func (b *ExecBackend) launchEnvLayerForMode(ctx context.Context, rt registry.Route) (map[string]string, instancekey.Layer, error) { |
| ha, err := b.haHostNow(ctx, rt) |
| if err != nil { |
| return nil, instancekey.LayerNone, fmt.Errorf("secrets for %s: %w", rt.Host, err) |
| @@ -415,3 +416,10 @@ func (a *Service) IsHA(ctx context.Context, rt registry.Route) (bool, error) { |
| } |
| return rt.HA, nil |
| } |
| + |
| +func (b *ExecBackend) launchEnvLayer(ctx context.Context, rt registry.Route) (map[string]string, instancekey.Layer, error) { |
| + if rt.Stateless { |
| + return b.statelessLaunchEnv(ctx, rt, release.StagedIdentity{}) |
| + } |
| + return b.launchEnvLayerForMode(ctx, rt) |
| +} |
diff --git a/internal/activator/maintenance.go b/internal/activator/maintenance.go| index 4baba261e..1c8054087 100644 |
| --- a/internal/activator/maintenance.go |
| +++ b/internal/activator/maintenance.go |
| @@ -487,6 +487,10 @@ func (a *Service) cleanupFailedWake(ctx context.Context, e *actEntry, rt registr |
| w.stopOutcome.leaseReleased = w.stopOutcome.replicaClosed |
| return |
| } |
| + if w.gen.Stateless && lease == nil { |
| + w.stopOutcome.replicaClosed, w.stopOutcome.leaseReleased = true, true |
| + return |
| + } |
| w.stopOutcome.leaseReleased = a.giveBack(ctx, rt.Host, lease) |
| } |
| @@ -505,6 +509,10 @@ func (a *Service) giveBackAfterStart(ctx context.Context, rt registry.Route, w * |
| return |
| } |
| } |
| + if w.gen.Stateless && lease == nil { |
| + w.stopOutcome.replicaClosed, w.stopOutcome.leaseReleased = true, true |
| + return |
| + } |
| w.stopOutcome.leaseReleased = a.giveBack(ctx, rt.Host, lease) |
| } |
diff --git a/internal/activator/rootfs.go b/internal/activator/rootfs.go| index e4a67779c..d2f9096aa 100644 |
| --- a/internal/activator/rootfs.go |
| +++ b/internal/activator/rootfs.go |
| @@ -364,7 +364,7 @@ func (b *ExecBackend) spawnRootfs(ctx context.Context, rt registry.Route, sock s |
| _ = os.Remove(filepath.Join(p.dataDir, instancectl.GenLaunchFileName(gen))) |
| } |
| } |
| - childVars := rootfsVars(b.agentOwnedVars(rt, sock+".control", fileEnv, ctl != nil), sock, p.dbPath) |
| + childVars := storageVars(rt, rootfsVars(b.agentOwnedVars(rt, sock+".control", fileEnv, ctl != nil), sock, p.dbPath)) |
| steps.mark(time.Now(), "prepare ("+prep.String()+")") |
| if err := b.writeRootfsLaunchFor(p, instancectl.RoleRun, gen, rt.Host, release.ProcessWeb, rootfsLaunchEnv(childVars)); err != nil { |
| return fail(err) |
diff --git a/internal/activator/rootfsenv.go b/internal/activator/rootfsenv.go| index a5db0ffaf..1c82e25c3 100644 |
| --- a/internal/activator/rootfsenv.go |
| +++ b/internal/activator/rootfsenv.go |
| @@ -18,7 +18,7 @@ import "github.com/carlosframework/platform/internal/registry" |
| // run's id and directory set), then rootfsVars with the row's canonical |
| // socket and dbPath. |
| func (b *ExecBackend) rootfsCmdVars(rt registry.Route, fileEnv map[string]string, dbPath, runID, runDir string) map[string]string { |
| - return rootfsVars(b.cmdVars(rt, fileEnv, dbPath, runID, runDir), rt.Socket, dbPath) |
| + return storageVars(rt, rootfsVars(b.cmdVars(rt, fileEnv, dbPath, runID, runDir), rt.Socket, dbPath)) |
| } |
| // rootfsTTYVars is a session's environment on a rootfs row (Plan 6 Task |
| @@ -26,7 +26,7 @@ func (b *ExecBackend) rootfsCmdVars(rt registry.Route, fileEnv map[string]string |
| // launched with (no run id or directory; TERM and CARLOS_SESSION_ID set), |
| // then rootfsVars with the row's canonical socket and dbPath. |
| func (b *ExecBackend) rootfsTTYVars(rt registry.Route, fileEnv map[string]string, dbPath, sessionID, term string) map[string]string { |
| - return rootfsVars(b.ttyVars(rt, fileEnv, dbPath, sessionID, term), rt.Socket, dbPath) |
| + return storageVars(rt, rootfsVars(b.ttyVars(rt, fileEnv, dbPath, sessionID, term), rt.Socket, dbPath)) |
| } |
| // rootfsReleaseVars is a release command's environment on a rootfs row |
| @@ -46,5 +46,6 @@ func (b *ExecBackend) rootfsReleaseVars(rt registry.Route, fileEnv map[string]st |
| // launch file is web's, CARLOS_SOCKET aside: a worker serves nothing, and |
| // names the instance's socket, never a generation's. |
| func (b *ExecBackend) rootfsWorkerVars(rt registry.Route, g Gen, dbPath string, genEnv map[string]string, haveControl bool) map[string]string { |
| - return rootfsVars(b.agentOwnedVars(rt, g.Control, genEnv, haveControl), rt.Socket, dbPath) |
| + rt.Stateless = g.Stateless |
| + return storageVars(rt, rootfsVars(b.agentOwnedVars(rt, g.Control, genEnv, haveControl), rt.Socket, dbPath)) |
| } |
diff --git a/internal/activator/stateless.go b/internal/activator/stateless.go| index a5c1d7d15..93018d04a 100644 |
| --- a/internal/activator/stateless.go |
| +++ b/internal/activator/stateless.go |
| @@ -2,7 +2,12 @@ package activator |
| import ( |
| "context" |
| + "errors" |
| + "fmt" |
| + "github.com/carlosframework/platform/internal/instancekey" |
| + "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/replicas" |
| + "time" |
| "github.com/carlosframework/platform/internal/registry" |
| ) |
| @@ -60,3 +65,121 @@ func (b *ExecBackend) coordinationAuthority(host string) replicas.Authority { |
| } |
| return b.Coordination.HeldForHost(host) |
| } |
| + |
| +var errStorageDeclaration = errors.New("could not verify this build's storage declaration, so it was not started") |
| + |
| +func (a *Service) storageMode(ctx context.Context, rt registry.Route, id release.StagedIdentity) (bool, string, error) { |
| + if a.StorageDeclaration == nil { |
| + if rt.Stateless { |
| + return false, "", errStorageDeclaration |
| + } |
| + return false, "", nil |
| + } |
| + if err := release.VerifyStaged(id); err != nil { |
| + return false, "", fmt.Errorf("%w: %w", errStorageDeclaration, err) |
| + } |
| + mode, digest, err := a.StorageDeclaration(ctx, rt, id) |
| + if err != nil { |
| + return false, "", fmt.Errorf("%w: %w", errStorageDeclaration, err) |
| + } |
| + return mode, digest, nil |
| +} |
| + |
| +type statelessWakeKey struct{} |
| +type statelessWakeInput struct { |
| + rt registry.Route |
| + plan WakePlan |
| + w *wokenInstance |
| + digest string |
| +} |
| + |
| +func (a *Service) doStatelessWake(ctx context.Context, e *actEntry, id release.StagedIdentity) (*wokenInstance, error) { |
| + in, ok := ctx.Value(statelessWakeKey{}).(statelessWakeInput) |
| + if !ok { |
| + return nil, errStorageDeclaration |
| + } |
| + rt, w := in.rt, in.w |
| + if a.cfg.Record == nil { |
| + return w, ErrFenced |
| + } |
| + facts, err := a.cfg.Record(ctx, rt) |
| + if err != nil { |
| + return w, err |
| + } |
| + ctx = WithReplicaReleaseObservation(ctx, facts, replicas.Build{Version: id.Version, Digest: in.digest}, true) |
| + if err := a.wakeHostProven(ctx, e, rt); err != nil { |
| + return w, err |
| + } |
| + gate := func() error { |
| + if ctx.Err() != nil || !a.wakeGoesOn(e) { |
| + return ErrFenced |
| + } |
| + if e.pinCheck != nil { |
| + if err := e.pinCheck(); err != nil { |
| + return err |
| + } |
| + } |
| + return a.statelessCurrent(ctx, in.rt) |
| + } |
| + if err := gate(); err != nil { |
| + return w, err |
| + } |
| + rt.Stateless = true |
| + if c, ok := a.backend.(Classifier); ok { |
| + w.launchLayout, _ = c.Layout(rt) |
| + } |
| + pin := genOf(id) |
| + pin.Stateless = true |
| + started := a.now() |
| + w.proc, w.spawnVersion, w.gen, err = a.startPinnedAt(ctx, rt, pin, gate, time.Time{}) |
| + w.spawnTook = a.now().Sub(started) |
| + w.spawnIdentity = id |
| + w.bootRan = err == nil || startMayHaveRun(w.proc, err) |
| + if in.plan.planned() { |
| + w.planned = w.gen |
| + } |
| + if err != nil { |
| + w.genUnproven, w.legacyUncertain = genStartUnproven(err), legacyStartMayRun(err) |
| + if w.proc != nil || w.genUnproven || w.legacyUncertain { |
| + a.cleanupFailedWake(ctx, e, rt, w, nil) |
| + } |
| + return w, err |
| + } |
| + if !a.wakeAllowed(rt.Host) || ctx.Err() != nil { |
| + a.cleanupFailedWake(ctx, e, rt, w, nil) |
| + return w, ErrFenced |
| + } |
| + w.stopOutcome = nil |
| + a.declareRootfsWorkers(e, rt, w) |
| + return w, nil |
| +} |
| + |
| +func servingError(e *actEntry) error { |
| + if e.gen.Stateless { |
| + return nil |
| + } |
| + if e.rep == nil { |
| + return errSwapLeaseLost |
| + } |
| + return e.rep.Err() |
| +} |
| + |
| +func (b *ExecBackend) statelessLaunchEnv(ctx context.Context, rt registry.Route, id release.StagedIdentity) (map[string]string, instancekey.Layer, error) { |
| + if id.StagedPath != "" { |
| + if err := release.VerifyStaged(id); err != nil { |
| + return nil, instancekey.LayerNone, err |
| + } |
| + } |
| + env, layer, err := b.launchEnvLayerForMode(ctx, rt) |
| + if err != nil { |
| + return nil, layer, err |
| + } |
| + return withoutVars(env, "CARLOS_DB"), layer, nil |
| +} |
| + |
| +func storageVars(rt registry.Route, env map[string]string) map[string]string { |
| + if rt.Stateless { |
| + return withoutVars(env, "CARLOS_DB") |
| + } |
| + return env |
| +} |
diff --git a/internal/activator/stateless_test.go b/internal/activator/stateless_test.go| index 9ff856e7f..3eb375a7b 100644 |
| --- a/internal/activator/stateless_test.go |
| +++ b/internal/activator/stateless_test.go |
| @@ -3,12 +3,17 @@ package activator |
| import ( |
| "context" |
| "errors" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "os" |
| + "path/filepath" |
| "slices" |
| + "strings" |
| "testing" |
| "time" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/replicas" |
| ) |
| @@ -105,3 +110,148 @@ func TestStatelessCurrentRequiresFreshEvidence(t *testing.T) { |
| t.Fatal("absent registry accepted") |
| } |
| } |
| + |
| +type statelessWakeBackend struct { |
| + *wakeRelBackend |
| + workers *fakeWorkerBackend |
| +} |
| + |
| +func (b *statelessWakeBackend) LaunchRootfsWorker(ctx context.Context, rt registry.Route, name string, g Gen, p Proc) (Proc, error) { |
| + return b.workers.LaunchRootfsWorker(ctx, rt, name, g, p) |
| +} |
| +func (b *statelessWakeBackend) RootfsWorkerGone(ctx context.Context, rt registry.Route, name string) error { |
| + return b.workers.RootfsWorkerGone(ctx, rt, name) |
| +} |
| + |
| +func wireStatelessRig(r *wakeRelRig) { |
| + r.a.StorageDeclaration = func(context.Context, registry.Route, release.StagedIdentity) (bool, string, error) { |
| + return true, "canonical", nil |
| + } |
| + r.a.cfg.Record = func(context.Context, registry.Route) (RecordFacts, error) { |
| + return RecordFactsOf(provision.Record{Account: r.rt.Account, App: r.rt.App, Host: r.rt.Host, CreatedAt: time.Unix(1, 0)}) |
| + } |
| +} |
| + |
| +func TestStatelessWakeHasNoDatabaseWork(t *testing.T) { |
| + r := newWakeRelRig(t) |
| + wireStatelessRig(r) |
| + workers := &fakeWorkerBackend{killBackend: &killBackend{fakeBackend: r.b.fakeBackend}} |
| + r.a.backend = &statelessWakeBackend{r.b, workers} |
| + r.b.procs["v2"] = map[string]release.Process{ |
| + release.ProcessWeb: {Command: []string{"serve"}}, |
| + "mail": {Command: []string{"mail"}}, |
| + "jobs": {Command: []string{"jobs"}}, |
| + } |
| + r.b.restoreFresh = true |
| + r.rt.Seed = `["seed"]` |
| + r.routes.set(r.rt) |
| + if err := waitErr(t, r.wake(r.a)); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.a.rootfsTick() |
| + waitFor(t, "declared workers", func() bool { return workers.alive() == 2 }) |
| + acquireCalls, restoreCalls, _ := r.b.counts() |
| + seedCalls := r.b.seedCount() |
| + r.b.mu.Lock() |
| + replicateCalls := len(r.b.syncIntervals) |
| + r.b.mu.Unlock() |
| + for _, ev := range r.b.events() { |
| + if ev == "replicate" { |
| + replicateCalls++ |
| + } |
| + } |
| + // TestStatelessWakeHasNoDatabaseWork |
| + if acquireCalls != 0 || restoreCalls != 0 || seedCalls != 0 || replicateCalls != 0 { |
| + t.Fatal("stateless wake used database machinery") |
| + } |
| + r.a.mu.Lock() |
| + e := r.a.entries[r.rt.Host] |
| + valid := e != nil && e.gen.Stateless && e.rep == nil && e.proc != nil |
| + r.a.mu.Unlock() |
| + if !valid { |
| + t.Fatal("stateless generation missing or owns a serving replica") |
| + } |
| + entries, err := os.ReadDir(filepath.Dir(r.rt.DBPath)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, entry := range entries { |
| + if entry.Name() != filepath.Base(r.rt.Socket) { |
| + t.Fatalf("database/marker write: %s", entry.Name()) |
| + } |
| + } |
| +} |
| + |
| +func TestStatelessEveryEnvironment(t *testing.T) { |
| + b := &ExecBackend{Region: "region"} |
| + rt := testRoute("shop.example.com") |
| + rt.Stateless = true |
| + env := map[string]string{"CARLOS_DB": "user-override", "KEEP": "yes"} |
| + for name, got := range map[string]map[string]string{ |
| + "web": storageVars(rt, rootfsVars(b.agentOwnedVars(rt, "control", env, true), "socket", "old-db")), |
| + "release": b.rootfsReleaseVars(rt, env, "old-db"), |
| + "worker": b.rootfsWorkerVars(rt, Gen{Stateless: true}, "old-db", env, false), |
| + "run": b.rootfsCmdVars(rt, env, "old-db", "run", "dir"), |
| + "tty": b.rootfsTTYVars(rt, env, "old-db", "session", "xterm"), |
| + "binary": b.agentOwnedVars(rt, "control", env, true), |
| + "binary run": b.cmdVars(rt, env, "old-db", "run", "dir"), |
| + "binary tty": b.ttyVars(rt, env, "old-db", "session", "xterm"), |
| + } { |
| + if _, ok := got["CARLOS_DB"]; ok { |
| + t.Errorf("%s retained CARLOS_DB", name) |
| + } |
| + if got["KEEP"] != "yes" { |
| + t.Errorf("%s lost user env", name) |
| + } |
| + } |
| +} |
| + |
| +func TestStatelessBinaryArgumentsAtExec(t *testing.T) { |
| + t.Run("flat", func(t *testing.T) { |
| + b := testExecBackend(t) |
| + b.RunDirOverride = t.TempDir() |
| + host := "shop.example.com" |
| + stageLive(t, b, host, "v1") |
| + marker := filepath.Join(t.TempDir(), "argv") |
| + exe := filepath.Join(b.OptDir, "versions", "v2", "app") |
| + if err := os.MkdirAll(filepath.Dir(exe), 0755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := writeExecutable(exe, []byte("#!/bin/sh\nprintf '%s\\n' \"$@\" > '"+marker+"'\nexec sleep 30\n"), 0755); err != nil { |
| + t.Fatal(err) |
| + } |
| + rt := registry.Route{Host: host, Kind: "instance", DBPath: filepath.Join(b.DataDir, host+".db"), Socket: filepath.Join(b.RunDirOverride, host+".sock")} |
| + g, p, err := b.StartStaged(context.Background(), rt, Gen{N: 5, Build: "v2", StagedPath: exe, Stateless: true}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer p.Stop(context.Background()) |
| + argv := waitForFileContent(t, marker, 2*time.Second) |
| + if strings.Contains(argv, "--db") || !strings.Contains(argv, "--socket") || !strings.Contains(argv, g.Socket) { |
| + t.Fatalf("argv=%q", argv) |
| + } |
| + }) |
| + t.Run("nested", func(t *testing.T) { |
| + ctl := &fakeControl{inv: "inv1"} |
| + unit := &fakeUnit{} |
| + unit.set("active", "inv1", true, true) |
| + ctl.stopHook = func(string, instancectl.Role) { unit.set("inactive", "inv1", false, false) } |
| + b, rt := nestedBackend(t, ctl, unit) |
| + b.GenContainment = true |
| + b.Control = newGoldenControl(ctl) |
| + _, p, err := b.StartStaged(context.Background(), rt, Gen{N: 7, Build: "v2", StagedPath: "/opt/carlos/versions/v2/shop", Digest: strings.Repeat("c", 64), Stateless: true}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer p.Stop(context.Background()) |
| + launch := readLaunchNamed(t, b, rt, instancectl.GenLaunchFileName(7)) |
| + if len(launch.Argv) != 3 || launch.Argv[1] != "--socket" { |
| + t.Fatalf("argv=%q", launch.Argv) |
| + } |
| + for _, v := range launch.Env { |
| + if strings.HasPrefix(v, "CARLOS_DB=") { |
| + t.Fatal("binary has database environment") |
| + } |
| + } |
| + }) |
| +} |
diff --git a/internal/activator/swapadmit.go b/internal/activator/swapadmit.go| index d11532d6e..317e08206 100644 |
| --- a/internal/activator/swapadmit.go |
| +++ b/internal/activator/swapadmit.go |
| @@ -91,7 +91,7 @@ func (a *Service) ownedLocked(e *actEntry, waking bool) error { |
| return errSwapNotAwake |
| case !waking && e.state != actAwake: // swapsim:M5 |
| return errSwapNotAwake |
| - case !waking && (e.rep == nil || e.rep.Err() != nil): |
| + case !waking && servingError(e) != nil: |
| return errSwapLeaseLost |
| case a.fences[e.host] != 0: |
| return errSwapFenced |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index a99e2dafa..7605eeaf2 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -602,6 +602,14 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| eb.Coordination = coordinator |
| } |
| svc.ObserveReplicaRelease = activator.ObservedReplicaRelease |
| + modeStore, modeStoreErr := openDeployStore(context.Background()) |
| + svc.StorageDeclaration = func(ctx context.Context, rt registry.Route, id release.StagedIdentity) (bool, string, error) { |
| + if modeStoreErr != nil { |
| + return false, "", modeStoreErr |
| + } |
| + return release.CanonicalStatelessDigest(ctx, modeStore, release.RouteAccount(rt), rt.App, id) |
| + } |
| + |
| svc.Fleet = fleetWakeFor(os.Getenv, identity, identErr, fleetStore) |
| if svc.Fleet.Mode == activator.FleetWakeUnknown { |
| log.Printf("agent: ERROR this box is on fleet %q but its fleet identity is invalid: %v. every instance assigned to a fleet box is refused until it is fixed and the agent restarted", svc.Fleet.Fleet, svc.Fleet.Err) |