activator: current inputs and per-process launch inputs, published when current
CurrentInputs fingerprints rt.Version and the two web env layers, read as a spawn reads them, cached on both files' stamps. Each spawn (flat, nested, rootfs) computes its launch inputs once from the env it captured and the build it runs, and carries them on its handle. A live-link spawn publishes at once; every other process publishes at noteCurrent. The edge cache holds the published table and the current-inputs hook.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/activator/activator.go+1 −1internal/activator/backend_exec.go+54 −12internal/activator/exec_gate_test.go+3 −3internal/activator/genbackend.go+2 −2internal/activator/genservice.go+11 −4internal/activator/inputs.go+211 −0internal/activator/inputs_test.go+548 −0internal/activator/recoveryprobe.go+1 −1internal/activator/rootfs.go+4 −0internal/activator/swap.go+1 −1internal/activator/unitproc.go+7 −0internal/edge/cache.go+70 −0internal/edge/cache_test.go+57 −0
Intent
<task-notification> <task-id>aa0066cb4064bd83e</task-id> <tool-use-id>toolu_01VXaNcb28uBh6oK8E7skGTB</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/d79ef2b4-4291-4945-bd45-b3f16796c4ba/tasks/aa0066cb4064bd83e.output</output-file> <status>completed</status> <summary>Agent "Implement Task 5: scrub list and marker" 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>Status: DONE. All three review points are fixed. Commits: - `b5ae1ad1 edge: one client scrub list; read and strip Carlos-Page-Cache everywhere` - `1ce5ed54 edge: page mark holder before every proxying branch; per-leg holders` (new commit, no amend) What changed: - **Holder attachment:** it now happens once the final route is settled, before the hop asset fill, held streams, upgrades, the local asset catch, the activator and the plain proxy. - **Held stream legs:** each leg now gets its own holder. Leg contexts derive from the browser request's, so without this they would all share one. - **Demo traffic:** it also attaches a holder before it proxies. - **Guard:** it now checks that announced trailer names are gone right after the hook, before the body is read. - **Backhaul test:** its comment now says that "armed" means the asset cache, because page caching has no arming until Task 10. Tests: the new `TestPageMarkHolderOnEveryProxiedPath` passes all 10 subtests, and its held-stream part passes with `-race`. The brief's covering set passes, and so does a wide batch of neighbouring held, demo, upgrade, cache and asset tests. Three mutations each failed the test they target: moving the holder back to the old spot, removing the per-leg holder, and scrubbing trailer names only at close. Concerns: - The demo traffic holder has no test. - I added a test-only hook to `Edge` (`pageMarkSeen`, nil in production) so tests can see the holder on each path. - Earlier concerns still stand: a malformed marker can still enter the LRU, parsing is case-insensitive, and the LRU refusal depends on each transport passing the request through to the response. Report (fix round appended): /home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-page-cache-1/.superpowers/sdd/2026-11-08-edge-page-cache-plan-1-home/task-5-report.md</result> <usage><subagent_tokens>261429</subagent_tokens><tool_uses>35</tool_uses><duration_ms>743318</duration_ms></usage> </task-notification>
<task-notification> <task-id>bn1chtpb0</task-id> <tool-use-id>toolu_013PX57Je5rqTVnMWeC6GRCQ</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/d79ef2b4-4291-4945-bd45-b3f16796c4ba/tasks/bn1chtpb0.output</output-file> <status>completed</status> <summary>Background command "Run scoped Astra re-review of Task 5 fix" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>btlq8l9mm</task-id> <tool-use-id>toolu_013BYjU3fD4aZVRSQbDpghMF</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/d79ef2b4-4291-4945-bd45-b3f16796c4ba/tasks/btlq8l9mm.output</output-file> <status>killed</status> <summary>Background command "Wait for the copy review result" 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>
Attributed to this commit: 21.8 g CO₂e (2,859,913 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on edge-page-cache-1, 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/activator/activator.go b/internal/activator/activator.go| index b0528e92e..b6929ab3d 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -2242,7 +2242,7 @@ func (a *Service) wake(e *actEntry) { |
| // transitions below can stop it (Plan 3 Task 8, C7). |
| a.installProcLocked(e, w.rep, w.proc, g) |
| if e.gen.N != 0 { |
| - a.noteCurrent(e.host, e.gen.N) |
| + a.noteCurrent(e) |
| } |
| // An instance's current generation is in the generations file from |
| // here (spec §8.5). A worker's build was published at its install. |
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go| index 516a4a456..0a26c8356 100644 |
| --- a/internal/activator/backend_exec.go |
| +++ b/internal/activator/backend_exec.go |
| @@ -355,6 +355,14 @@ type ExecBackend struct { |
| // review F1). |
| launchHook func(host string) |
| + // inputsMu guards inputsCache, CurrentInputs' per-route read of the |
| + // two env layers (inputs.go), and nothing else. |
| + inputsMu sync.Mutex |
| + inputsCache map[string]*currentInputsEntry |
| + // currentInputsRead, when set, replaces instanceEnvParts as |
| + // CurrentInputs' read. Test-only: it counts reads. |
| + currentInputsRead func(rt registry.Route) (cfgEnv, ownEnv map[string]string, err error) |
| + |
| // Registry is the box's registry, which an HA host's restore imports its |
| // published wake state into (hostfiles.ImportWake). Nil: an HA restore |
| // whose manifest carries wake state fails. |
| @@ -2114,7 +2122,7 @@ func (b *ExecBackend) Start(ctx context.Context, rt registry.Route) (Proc, strin |
| case LayoutFenced, LayoutConflict: |
| return nil, "", fmt.Errorf("%s: refusing to wake: %s", rt.Host, p.reason) |
| } |
| - return b.startChildAt(ctx, rt, rt.Socket, 0, "", cgroup.Limit{}) |
| + return b.startChildAt(ctx, rt, rt.Socket, 0, "", "", cgroup.Limit{}) |
| } |
| // StartGen is Start for generation n (zero-downtime spec §7.1). perGen false |
| @@ -2191,11 +2199,11 @@ func (b *ExecBackend) startGenFrom(ctx context.Context, rt registry.Route, n uin |
| return nil, Gen{}, err |
| } |
| var ( |
| - flatExe string |
| - unitExe *instancectl.StagedExe |
| + flatExe, flatBuild string |
| + unitExe *instancectl.StagedExe |
| ) |
| if id != nil { |
| - flatExe, unitExe = id.StagedPath, stagedExeOf(*id) |
| + flatExe, flatBuild, unitExe = id.StagedPath, id.Version, stagedExeOf(*id) |
| } |
| p := b.pathsFor(rt) |
| sock := rt.Socket |
| @@ -2241,7 +2249,7 @@ func (b *ExecBackend) startGenFrom(ctx context.Context, rt registry.Route, n uin |
| return nil, Gen{}, fmt.Errorf("%s: generation socket: %w", rt.Host, err) |
| } |
| } |
| - proc, ver, err = b.startChildAt(ctx, rt, sock, n, flatExe, tier) |
| + proc, ver, err = b.startChildAt(ctx, rt, sock, n, flatExe, flatBuild, tier) |
| } |
| g := Gen{N: n, Socket: sock, Control: sock + ".control", Stateless: rt.Stateless} |
| if err != nil { |
| @@ -2288,9 +2296,10 @@ func clearOwnGenSocket(sock string) error { |
| // (StartGenExe). spawnChildFrom leaves a staged spawn's cache purge to the |
| // swap's switch, but a wake's staged spawn is the host's only process, so |
| // its purge happens here, at the same moment, before the health wait. |
| -// tier is exe's own; zero is the live tier (b.tier). |
| -func (b *ExecBackend) startChildAt(ctx context.Context, rt registry.Route, sock string, n uint64, exe string, tier cgroup.Limit) (Proc, string, error) { |
| - p, spawnVer, err := b.spawnChildFrom(ctx, rt, sock, n, exe, tier) |
| +// tier is exe's own; zero is the live tier (b.tier). build is exe's |
| +// version, "" for the live link. |
| +func (b *ExecBackend) startChildAt(ctx context.Context, rt registry.Route, sock string, n uint64, exe, build string, tier cgroup.Limit) (Proc, string, error) { |
| + p, spawnVer, err := b.spawnChildFrom(ctx, rt, sock, n, exe, build, tier) |
| if err != nil { |
| return p, "", err |
| } |
| @@ -2347,8 +2356,11 @@ func (b *ExecBackend) killGenAfterFailedStart(ctx context.Context, rt registry.R |
| // root does to the live link meanwhile, with the caller owning the health |
| // deadline and the termination. tier is that artifact's own tier; zero is |
| // the live tier (b.tier). n is the generation number plan 2's containment |
| -// places the child by. |
| -func (b *ExecBackend) spawnChildFrom(ctx context.Context, rt registry.Route, sock string, n uint64, exe string, tier cgroup.Limit) (Proc, string, error) { |
| +// places the child by. build is the version a staged exe is (its |
| +// generation's Build); the live link's is resolved here. The process |
| +// carries its launch inputs (launchInputs) over that build and the env |
| +// read below, and a live-link spawn publishes them at once, as it purges. |
| +func (b *ExecBackend) spawnChildFrom(ctx context.Context, rt registry.Route, sock string, n uint64, exe, build string, tier cgroup.Limit) (Proc, string, error) { |
| host := rt.Host |
| paths := b.pathsFor(rt) |
| dbPath := paths.dbPath |
| @@ -2518,6 +2530,17 @@ func (b *ExecBackend) spawnChildFrom(ctx context.Context, rt registry.Route, soc |
| } else if exe == "" { |
| spawnVer, _ = b.LiveVersion(host) |
| } |
| + // The page cache's launch inputs (inputs.go): computed once, here, |
| + // from the env this spawn read (fileEnv, before any agent-owned |
| + // variable) and the build it is about to exec. A live-link spawn names |
| + // the build it resolved above, a staged one the build its caller named. |
| + // Never recomputed: a file rewritten after this read is not what the |
| + // process was handed. |
| + ranBuild := build |
| + if exe == "" { |
| + ranBuild = spawnVer |
| + } |
| + inputs := launchInputs(ranBuild, fileEnv) |
| // Spawned through the cgroup manager (nil-tolerant: no delegation means |
| // a plain start, exactly as before) so the child lands in |
| // carlos-exec@<host> and the sampler can account it. build may run |
| @@ -2561,10 +2584,15 @@ func (b *ExecBackend) spawnChildFrom(ctx context.Context, rt registry.Route, soc |
| return nil, "", err |
| } |
| - p := &childProc{cmd: cmd, done: make(chan struct{}), ctl: ctl} |
| + p := &childProc{cmd: cmd, done: make(chan struct{}), ctl: ctl, inputs: inputs} |
| // A staged successor spawns while the incumbent still serves, and its |
| - // purge happens at the switch (GenSwitched), not here. |
| + // purge happens at the switch (GenSwitched), not here. So does the |
| + // publish of its inputs: a staged process's are published only when it |
| + // becomes current (noteCurrent). |
| if b.Cache != nil && exe == "" { |
| + // The live link's process is the host's only one: it is current |
| + // from here, so the inputs it was started from are the host's. |
| + b.Cache.NoteProcessInputs(rt.Host, inputs) |
| // A fresh process for this host is exactly the moment its cached |
| // content becomes suspect: a deploy/redeploy means new code and |
| // potentially new pages, and nothing else would invalidate them until |
| @@ -2757,6 +2785,14 @@ func (b *ExecBackend) spawnUnitFrom(ctx context.Context, rt registry.Route, sock |
| if spawnVer == "" { |
| spawnVer, _ = b.LiveVersion(rt.Host) |
| } |
| + // The page cache's launch inputs (inputs.go), once, from this read's |
| + // env and the build root is asked to bind: a staged or pinned exe's |
| + // own version, else the live link's, read just above. |
| + ranBuild := spawnVer |
| + if exe != nil { |
| + ranBuild = exe.Version |
| + } |
| + inputs := launchInputs(ranBuild, fileEnv) |
| // The caller's exec gate (final review F1), right before root is asked |
| // to start the unit: the config read, the listeners and the launch file |
| // above all take time. A refusal starts nothing; the generation's own |
| @@ -2846,6 +2882,7 @@ func (b *ExecBackend) spawnUnitFrom(ctx context.Context, rt registry.Route, sock |
| // kept with it, decided by the same read (instance-key ruling 29), so |
| // a run's command passes the replica gate on exactly what it is given. |
| up.launchEnv, up.launchKeyLayer = maps.Clone(fileEnv), keyLayer |
| + up.inputs = inputs |
| if b.Cache != nil { |
| // A fresh process for this host is exactly the moment its cached |
| // content becomes suspect, same rule as startChild. |
| @@ -3724,8 +3761,13 @@ type childProc struct { |
| done chan struct{} |
| err error |
| ctl *edge.ControlListener // nil only if the pre-spawn bind failed |
| + // inputs is the page cache's launch inputs (launchInputs), set at the |
| + // spawn and never again; "" when the spawn did not know its build. |
| + inputs string |
| } |
| +func (p *childProc) launchedFrom() string { return p.inputs } |
| + |
| func (p *childProc) Exited() bool { |
| select { |
| case <-p.done: |
diff --git a/internal/activator/exec_gate_test.go b/internal/activator/exec_gate_test.go| index 4499ede11..078420ec5 100644 |
| --- a/internal/activator/exec_gate_test.go |
| +++ b/internal/activator/exec_gate_test.go |
| @@ -696,7 +696,7 @@ func TestALiveExecGateGatesTheFlatLiveLinkSpawn(t *testing.T) { |
| // Root repoints at held v2 after the gate has been asked about v1 and |
| // before the exec. |
| b.launchHook = onCall(1, func() { repointLive(t, b, rt.Host, v2) }) |
| - p, ver, err := b.spawnChildFrom(context.Background(), rt, rt.Socket, 0, "", cgroup.Limit{}) |
| + p, ver, err := b.spawnChildFrom(context.Background(), rt, rt.Socket, 0, "", "", cgroup.Limit{}) |
| if err != nil { |
| t.Fatalf("spawn = %v", err) |
| } |
| @@ -713,7 +713,7 @@ func TestALiveExecGateGatesTheFlatLiveLinkSpawn(t *testing.T) { |
| repointLive(t, b, rt.Host, v2) |
| g := &liveGate{refuse: map[string]bool{"v2": true}} |
| b.LiveExecGate = g.gate |
| - p, _, err := b.spawnChildFrom(context.Background(), rt, rt.Socket, 0, "", cgroup.Limit{}) |
| + p, _, err := b.spawnChildFrom(context.Background(), rt, rt.Socket, 0, "", "", cgroup.Limit{}) |
| if p != nil { |
| _ = p.Stop(context.Background()) |
| } |
| @@ -733,7 +733,7 @@ func TestALiveExecGateGatesTheFlatLiveLinkSpawn(t *testing.T) { |
| }) |
| t.Run("no gate is today's spawn", func(t *testing.T) { |
| b, rt, _, _, out := flatLiveFixture(t) |
| - p, ver, err := b.spawnChildFrom(context.Background(), rt, rt.Socket, 0, "", cgroup.Limit{}) |
| + p, ver, err := b.spawnChildFrom(context.Background(), rt, rt.Socket, 0, "", "", cgroup.Limit{}) |
| if err != nil { |
| t.Fatalf("spawn = %v", err) |
| } |
diff --git a/internal/activator/genbackend.go b/internal/activator/genbackend.go| index 2d05c8399..28ca84dc3 100644 |
| --- a/internal/activator/genbackend.go |
| +++ b/internal/activator/genbackend.go |
| @@ -271,7 +271,7 @@ func (b *ExecBackend) StartStaged(ctx context.Context, rt registry.Route, g Gen) |
| if err := clearOwnGenSocket(sock); err != nil { |
| return g, nil, fmt.Errorf("%s: generation socket: %w", rt.Host, err) |
| } |
| - proc, _, err := b.spawnChildFrom(ctx, rt, sock, g.N, g.StagedPath, g.Tier) |
| + proc, _, err := b.spawnChildFrom(ctx, rt, sock, g.N, g.StagedPath, g.Build, g.Tier) |
| if err != nil { |
| return g, proc, err |
| } |
| @@ -283,7 +283,7 @@ func (b *ExecBackend) StartStaged(ctx context.Context, rt registry.Route, g Gen) |
| if err := clearLeftoverCanonicalLink(rt.Socket); err != nil { |
| return g, nil, fmt.Errorf("%s: leftover canonical link: %w", rt.Host, err) |
| } |
| - proc, _, err := b.spawnChildFrom(ctx, rt, rt.Socket, g.N, g.StagedPath, g.Tier) |
| + proc, _, err := b.spawnChildFrom(ctx, rt, rt.Socket, g.N, g.StagedPath, g.Build, g.Tier) |
| if err != nil { |
| return g, proc, err |
| } |
diff --git a/internal/activator/genservice.go b/internal/activator/genservice.go| index 6bd297ba4..8de60d0e6 100644 |
| --- a/internal/activator/genservice.go |
| +++ b/internal/activator/genservice.go |
| @@ -92,10 +92,17 @@ func (a *Service) CacheGen(host string) (uint64, bool) { |
| return v.(*atomic.Uint64).Load(), true |
| } |
| -// noteCurrent records that generation n of host has become current. |
| -func (a *Service) noteCurrent(host string, n uint64) { |
| - v, _ := a.cacheGens.LoadOrStore(host, new(atomic.Uint64)) |
| - v.(*atomic.Uint64).Store(n) |
| +// noteCurrent records that e's generation has become current: its number |
| +// for the cache's generation tag, and the inputs its process was started |
| +// from for the page cache (inputs.go), published here and never at |
| +// staging. A process whose inputs are not known withdraws the host's. The |
| +// caller holds a.mu; the publish takes only the cache's own inputs lock. |
| +func (a *Service) noteCurrent(e *actEntry) { |
| + v, _ := a.cacheGens.LoadOrStore(e.host, new(atomic.Uint64)) |
| + v.(*atomic.Uint64).Store(e.gen.N) |
| + if ip, ok := a.backend.(inputsPublisher); ok { |
| + ip.publishLaunchInputs(e.route, e.proc) |
| + } |
| } |
| // OnGenRetired registers fn for every generation that stops being current |
diff --git a/internal/activator/inputs.go b/internal/activator/inputs.go| new file mode 100644 |
| index 000000000..51933d521 |
| --- /dev/null |
| +++ b/internal/activator/inputs.go |
| @@ -0,0 +1,211 @@ |
| +package activator |
| + |
| +import ( |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "errors" |
| + "os" |
| + "slices" |
| + "strconv" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// The page cache's one freshness invariant (edge page cache plan 1, Task |
| +// 6; Paul's "One invariant + gate units"). An exec-backed instance's |
| +// current inputs are its installed build and its two web env layers, read |
| +// from box-local state. A process's launch inputs are the build it runs |
| +// and the env it was handed. The edge serves a cached page only while its |
| +// tag equals the current inputs, and stores one only when the answering |
| +// process's published inputs equal them. Both sides use inputsFingerprint, |
| +// so a fresh spawn with nothing changed publishes exactly CurrentInputs. |
| + |
| +// inputsFingerprint is the one encoding of an instance's inputs (R3-2): |
| +// hex sha256 over the build and the env in sorted key order. Every field |
| +// is length-prefixed, so no build or value can be read as the structure |
| +// around it. |
| +func inputsFingerprint(build string, env map[string]string) string { |
| + h := sha256.New() |
| + field := func(s string) { |
| + h.Write([]byte(strconv.Itoa(len(s)))) |
| + h.Write([]byte{':'}) |
| + h.Write([]byte(s)) |
| + } |
| + h.Write([]byte("carlos-inputs-v1\n")) |
| + field(build) |
| + keys := make([]string, 0, len(env)) |
| + for k := range env { |
| + keys = append(keys, k) |
| + } |
| + slices.Sort(keys) |
| + for _, k := range keys { |
| + field(k) |
| + field(env[k]) |
| + } |
| + return hex.EncodeToString(h.Sum(nil)) |
| +} |
| + |
| +// launchInputs is a process's inputs at its launch: the build it actually |
| +// executes and fileEnv, the env its spawn read from the instance's files |
| +// (launchEnvLayer's answer), before the platform's own CARLOS_* variables |
| +// are added. Computed once, at the spawn, and carried on the process |
| +// handle, never recomputed. An unknown build is unknown inputs: "". |
| +func launchInputs(build string, fileEnv map[string]string) string { |
| + if build == "" { |
| + return "" |
| + } |
| + return inputsFingerprint(build, fileEnv) |
| +} |
| + |
| +// launchInputsCarrier is a process handle that knows the inputs it was |
| +// started from: childProc and unitProc, set once at their spawn. |
| +type launchInputsCarrier interface { |
| + launchedFrom() string |
| +} |
| + |
| +// procLaunchInputs is p's launch inputs, "" when p does not know them (a |
| +// handle another backend made, or a spawn whose build was not known). |
| +func procLaunchInputs(p Proc) string { |
| + if c, ok := p.(launchInputsCarrier); ok { |
| + return c.launchedFrom() |
| + } |
| + return "" |
| +} |
| + |
| +// inputsPublisher is a backend that publishes a process's launch inputs |
| +// to the edge's cache as it becomes host's current process (noteCurrent). |
| +type inputsPublisher interface { |
| + publishLaunchInputs(rt registry.Route, p Proc) |
| +} |
| + |
| +// publishLaunchInputs records p's launch inputs as rt's current process's. |
| +// A process with none withdraws the host's, so nothing it answers is |
| +// stored. A no-op with no cache. |
| +func (b *ExecBackend) publishLaunchInputs(rt registry.Route, p Proc) { |
| + if b.Cache == nil { |
| + return |
| + } |
| + b.Cache.NoteProcessInputs(rt.Host, procLaunchInputs(p)) |
| +} |
| + |
| +// publishLaunchInputs forwards to the exec half for an exec row. A |
| +// unit-backed row publishes nothing: the page cache refuses it (R2-3). |
| +func (b *SplitBackend) publishLaunchInputs(rt registry.Route, p Proc) { |
| + if rt.Backing == registry.BackingUnit { |
| + return |
| + } |
| + if ip, ok := b.Exec.(inputsPublisher); ok { |
| + ip.publishLaunchInputs(rt, p) |
| + } |
| +} |
| + |
| +// inputsStampRacy is how recent a file's change may be for its stamp not |
| +// to be kept: a same-size rewrite within one timestamp tick of the read |
| +// would keep the stamp the read took. escrowStampRacy's rule. A var so a |
| +// test can shrink it. |
| +var inputsStampRacy = escrowStampRacy |
| + |
| +// currentInputsEntry is one route's cached read of its two env layers, |
| +// valid while both files keep the stamps taken before the read. |
| +type currentInputsEntry struct { |
| + cfgPath, ownPath string |
| + cfgStamp, ownStamp statStamp |
| + env map[string]string // mergeEnv of the two layers |
| + // build and stateless are what fp was computed for. |
| + build string |
| + stateless bool |
| + fp string |
| +} |
| + |
| +// CurrentInputs is rt's current inputs (R3-4): the fingerprint of |
| +// rt.Version and the instance's two web env layers, read exactly as a |
| +// spawn reads them (instanceEnvParts, then mergeEnv): paths.configEnv, |
| +// the delivered <host>.config.env, under paths.envFile (R3-1). A missing |
| +// file is a valid, empty layer. An unreadable one, or a route with no |
| +// version, is false. A stateless row's spawn hands its process the env |
| +// without CARLOS_DB (statelessLaunchEnv), so this does the same. |
| +// |
| +// It is asked on every page lookup, so the read is cached per route on |
| +// both files' stamps (path, size, mtime, ctime, inode), taken before the |
| +// read, and the files are read again only when one moves. A stamp too |
| +// recent to trust (inputsStampRacy) is not kept. |
| +func (b *ExecBackend) CurrentInputs(rt registry.Route) (string, bool) { |
| + if rt.Version == "" { |
| + return "", false |
| + } |
| + p := b.pathsFor(rt) |
| + now := time.Now() |
| + cfgStamp, err := inputsStamp(p.configEnv, p.layout) |
| + if err != nil { |
| + return "", false |
| + } |
| + ownStamp, err := inputsStamp(p.envFile, p.layout) |
| + if err != nil { |
| + return "", false |
| + } |
| + b.inputsMu.Lock() |
| + e, ok := b.inputsCache[rt.Host] |
| + if ok && e.cfgPath == p.configEnv && e.ownPath == p.envFile && e.cfgStamp == cfgStamp && e.ownStamp == ownStamp { |
| + if e.build != rt.Version || e.stateless != rt.Stateless { |
| + e.build, e.stateless = rt.Version, rt.Stateless |
| + e.fp = inputsFingerprint(rt.Version, storageVars(rt, e.env)) |
| + } |
| + fp := e.fp |
| + b.inputsMu.Unlock() |
| + return fp, true |
| + } |
| + b.inputsMu.Unlock() |
| + |
| + read := b.currentInputsRead |
| + if read == nil { |
| + read = b.instanceEnvParts |
| + } |
| + cfgEnv, ownEnv, err := read(rt) |
| + if err != nil { |
| + return "", false |
| + } |
| + env := mergeEnv(cfgEnv, ownEnv) |
| + fp := inputsFingerprint(rt.Version, storageVars(rt, env)) |
| + cutoff := now.Add(-inputsStampRacy).UnixNano() |
| + b.inputsMu.Lock() |
| + defer b.inputsMu.Unlock() |
| + if stampSettled(cfgStamp, cutoff) && stampSettled(ownStamp, cutoff) { |
| + if b.inputsCache == nil { |
| + b.inputsCache = make(map[string]*currentInputsEntry) |
| + } |
| + b.inputsCache[rt.Host] = ¤tInputsEntry{ |
| + cfgPath: p.configEnv, ownPath: p.envFile, |
| + cfgStamp: cfgStamp, ownStamp: ownStamp, |
| + env: env, build: rt.Version, stateless: rt.Stateless, fp: fp, |
| + } |
| + } else { |
| + delete(b.inputsCache, rt.Host) |
| + } |
| + return fp, true |
| +} |
| + |
| +// inputsStamp is path's stamp, absent for a missing file. A nested row's |
| +// files are read without following a link (instanceEnvParts), so the |
| +// stamp is the entry's own; a flat row's read follows one, so its stamp |
| +// is the target's. |
| +func inputsStamp(path string, l Layout) (statStamp, error) { |
| + stat := os.Stat |
| + if l == LayoutNested { |
| + stat = os.Lstat |
| + } |
| + fi, err := stat(path) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return statStamp{absent: true}, nil |
| + } |
| + if err != nil { |
| + return statStamp{}, err |
| + } |
| + return stampOf(fi), nil |
| +} |
| + |
| +// stampSettled reports whether st is old enough to keep: absent, or last |
| +// changed before cutoff. |
| +func stampSettled(st statStamp, cutoff int64) bool { |
| + return st.absent || st.mtime < cutoff && st.ctime < cutoff |
| +} |
diff --git a/internal/activator/inputs_test.go b/internal/activator/inputs_test.go| new file mode 100644 |
| index 000000000..fd4c6dc4e |
| --- /dev/null |
| +++ b/internal/activator/inputs_test.go |
| @@ -0,0 +1,548 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// Page cache Task 6: the current inputs of an exec-backed instance (its |
| +// installed build and its two web env layers, read from box-local state) |
| +// and each process's launch inputs (the build it runs and the env it was |
| +// handed), published to the edge's cache only when that process becomes |
| +// current. |
| + |
| +// publishLaunchInputs maps the activator's row onto the real backend's, |
| +// as StartStaged does: the Service's publish at noteCurrent reaches the |
| +// real backend's cache under the real backend's host. |
| +func (b *launchBackend) publishLaunchInputs(_ registry.Route, p Proc) { |
| + b.eb.publishLaunchInputs(b.rt, p) |
| +} |
| + |
| +// inputsKit is a flat backend, its route (account acme, app shop, at |
| +// version v1) in a registry, and the bucket config sync delivers from. |
| +type inputsKit struct { |
| + b *ExecBackend |
| + rt registry.Route |
| + reg *registry.Registry |
| + s release.Store |
| +} |
| + |
| +func newInputsKit(t *testing.T) *inputsKit { |
| + t.Helper() |
| + b := testExecBackend(t) |
| + b.RunDirOverride = shortRunDir(t) |
| + host := "shop.example.com" |
| + rt := flatGenRoute(b, host) |
| + rt.Account, rt.App, rt.Status, rt.Version = "acme", "shop", "ready", "v1" |
| + if l, _ := b.Layout(rt); l != LayoutFlat { |
| + t.Fatalf("fixture classifies %q, want flat", l) |
| + } |
| + reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { reg.Close() }) |
| + if err := reg.Upsert(rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + return &inputsKit{b: b, rt: rt, reg: reg, s: release.NewDirStore(t.TempDir())} |
| +} |
| + |
| +// deliver sets kv in the app's config and runs the real config delivery, |
| +// which writes paths.configEnv. |
| +func (k *inputsKit) deliver(t *testing.T, kv map[string]string) { |
| + t.Helper() |
| + ctx := context.Background() |
| + if err := appconfig.SetEnv(ctx, k.s, k.rt.Account, k.rt.App, kv); err != nil { |
| + t.Fatal(err) |
| + } |
| + k.sync(t) |
| + raw, err := os.ReadFile(k.b.pathsFor(k.rt).configEnv) |
| + if err != nil { |
| + t.Fatalf("config sync wrote no %s: %v", k.b.pathsFor(k.rt).configEnv, err) |
| + } |
| + for name, v := range kv { |
| + if !strings.Contains(string(raw), name+"="+v) { |
| + t.Fatalf("delivered config %q lacks %s=%s", raw, name, v) |
| + } |
| + } |
| +} |
| + |
| +// undeliver removes the app's config from the bucket and runs the real |
| +// config delivery, which removes paths.configEnv. |
| +func (k *inputsKit) undeliver(t *testing.T) { |
| + t.Helper() |
| + if err := k.s.Delete(context.Background(), appconfig.Key(k.rt.Account, k.rt.App)); err != nil { |
| + t.Fatal(err) |
| + } |
| + k.sync(t) |
| + if _, err := os.Stat(k.b.pathsFor(k.rt).configEnv); !os.IsNotExist(err) { |
| + t.Fatalf("config sync left %s: %v", k.b.pathsFor(k.rt).configEnv, err) |
| + } |
| +} |
| + |
| +func (k *inputsKit) sync(t *testing.T) { |
| + t.Helper() |
| + if err := appconfig.SyncExec(context.Background(), k.reg, k.s, nil, k.b.DataDir, func(string) error { return nil }, "", nil); err != nil { |
| + t.Fatalf("SyncExec: %v", err) |
| + } |
| +} |
| + |
| +// writeOwnEnv replaces the instance's own <host>.env by rename. |
| +func writeOwnEnv(t *testing.T, b *ExecBackend, rt registry.Route, body string) { |
| + t.Helper() |
| + writeByRename(t, b.pathsFor(rt).envFile, body) |
| +} |
| + |
| +// writeConfigEnv replaces the delivered <host>.config.env by rename, at the |
| +// exact path pathsFor names (for a layout config sync's test kit cannot |
| +// reach: a nested or rootfs row under the test's run directory). |
| +func writeConfigEnv(t *testing.T, b *ExecBackend, rt registry.Route, body string) { |
| + t.Helper() |
| + writeByRename(t, b.pathsFor(rt).configEnv, body) |
| +} |
| + |
| +func writeByRename(t *testing.T, path, body string) { |
| + t.Helper() |
| + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + tmp := path + ".tmp" |
| + if err := os.WriteFile(tmp, []byte(body), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Rename(tmp, path); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func mustCurrent(t *testing.T, b *ExecBackend, rt registry.Route) string { |
| + t.Helper() |
| + got, ok := b.CurrentInputs(rt) |
| + if !ok || got == "" { |
| + t.Fatalf("CurrentInputs(%s at %s) = %q, %v; want known", rt.Host, rt.Version, got, ok) |
| + } |
| + return got |
| +} |
| + |
| +// stageServingLiveAt is stageServingLive with the live link through |
| +// <OptDir>/versions/<ver>/app, so the spawn resolves ver as its build. |
| +func stageServingLiveAt(t *testing.T, b *ExecBackend, host, ver string) { |
| + t.Helper() |
| + self, err := os.Executable() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Setenv("ACTIVATOR_FAKE_APP", "1") |
| + vdir := filepath.Join(b.OptDir, "versions", ver) |
| + if err := os.MkdirAll(vdir, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + bin := filepath.Join(vdir, "app") |
| + os.Remove(bin) |
| + if err := os.Symlink(self, bin); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.MkdirAll(filepath.Join(b.OptDir, "live"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + os.Remove(b.liveLink(host)) |
| + if err := os.Symlink(bin, b.liveLink(host)); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestCurrentInputsStable(t *testing.T) { |
| + k := newInputsKit(t) |
| + k.deliver(t, map[string]string{"LOG_LEVEL": "debug"}) |
| + writeOwnEnv(t, k.b, k.rt, "OWN=1\n") |
| + first := mustCurrent(t, k.b, k.rt) |
| + if second := mustCurrent(t, k.b, k.rt); second != first { |
| + t.Fatalf("the same version and files gave %q then %q", first, second) |
| + } |
| + // A missing file is a valid, empty layer. |
| + bare := newInputsKit(t) |
| + a, b := mustCurrent(t, bare.b, bare.rt), mustCurrent(t, bare.b, bare.rt) |
| + if a != b { |
| + t.Fatalf("no files: %q then %q", a, b) |
| + } |
| + // One encoding: the fingerprint is the build and the merged env. |
| + if want := inputsFingerprint("v1", map[string]string{"LOG_LEVEL": "debug", "OWN": "1"}); first != want { |
| + t.Fatalf("CurrentInputs = %q, want inputsFingerprint over v1 and the merged layers %q", first, want) |
| + } |
| + // A stateless row's spawn is handed its env without CARLOS_DB |
| + // (statelessLaunchEnv), so its current inputs leave it out too. |
| + writeOwnEnv(t, k.b, k.rt, "OWN=1\nCARLOS_DB=/data/app.db\n") |
| + stateless := k.rt |
| + stateless.Stateless = true |
| + if got, want := mustCurrent(t, k.b, stateless), inputsFingerprint("v1", map[string]string{"LOG_LEVEL": "debug", "OWN": "1"}); got != want { |
| + t.Fatalf("stateless CurrentInputs = %q, want the fingerprint without CARLOS_DB %q", got, want) |
| + } |
| +} |
| + |
| +func TestCurrentInputsChanges(t *testing.T) { |
| + k := newInputsKit(t) |
| + k.deliver(t, map[string]string{"LOG_LEVEL": "debug"}) |
| + writeOwnEnv(t, k.b, k.rt, "OWN=1\n") |
| + seen := map[string]string{} |
| + step := func(name string) { |
| + t.Helper() |
| + got := mustCurrent(t, k.b, k.rt) |
| + for prev, v := range seen { |
| + if v == got { |
| + t.Fatalf("%s: CurrentInputs %q equals the value after %s", name, got, prev) |
| + } |
| + } |
| + seen[name] = got |
| + } |
| + step("start") |
| + |
| + v2 := k.rt |
| + v2.Version = "v2" |
| + if a, b := mustCurrent(t, k.b, k.rt), mustCurrent(t, k.b, v2); a == b { |
| + t.Fatalf("a version change kept the inputs %q", a) |
| + } |
| + |
| + k.deliver(t, map[string]string{"LOG_LEVEL": "info"}) |
| + step("a config edit") |
| + k.undeliver(t) |
| + step("a config removal") |
| + writeOwnEnv(t, k.b, k.rt, "OWN=2\n") |
| + step("an own env edit") |
| + |
| + // An unreadable layer is false, never a fingerprint of what could be |
| + // read. |
| + if err := os.Mkdir(k.b.pathsFor(k.rt).configEnv, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, ok := k.b.CurrentInputs(k.rt); ok { |
| + t.Fatalf("an unreadable config layer gave %q, true", got) |
| + } |
| + // An unknown build is unknown inputs. |
| + noVer := k.rt |
| + noVer.Version = "" |
| + if got, ok := k.b.CurrentInputs(noVer); ok { |
| + t.Fatalf("a route with no version gave %q, true", got) |
| + } |
| +} |
| + |
| +func TestCurrentInputsStatCache(t *testing.T) { |
| + defer func(d time.Duration) { inputsStampRacy = d }(inputsStampRacy) |
| + inputsStampRacy = 0 // every stamp old enough to keep |
| + k := newInputsKit(t) |
| + k.deliver(t, map[string]string{"LOG_LEVEL": "debug"}) |
| + writeOwnEnv(t, k.b, k.rt, "OWN=1\n") |
| + var reads atomic.Int32 |
| + k.b.currentInputsRead = func(rt registry.Route) (map[string]string, map[string]string, error) { |
| + reads.Add(1) |
| + return k.b.instanceEnvParts(rt) |
| + } |
| + first := mustCurrent(t, k.b, k.rt) |
| + for range 5 { |
| + if got := mustCurrent(t, k.b, k.rt); got != first { |
| + t.Fatalf("unchanged files: %q, want %q", got, first) |
| + } |
| + } |
| + if n := reads.Load(); n != 1 { |
| + t.Fatalf("%d reads for six lookups over unchanged files, want 1", n) |
| + } |
| + // A version change re-fingerprints, but reads nothing. |
| + v2 := k.rt |
| + v2.Version = "v2" |
| + if got := mustCurrent(t, k.b, v2); got == first { |
| + t.Fatal("a version change kept the inputs") |
| + } |
| + if n := reads.Load(); n != 1 { |
| + t.Fatalf("a version change read the files again (%d reads)", n) |
| + } |
| + // A changed stamp reads again. |
| + k.deliver(t, map[string]string{"LOG_LEVEL": "info"}) |
| + if got := mustCurrent(t, k.b, k.rt); got == first { |
| + t.Fatal("a config edit kept the inputs") |
| + } |
| + if n := reads.Load(); n != 2 { |
| + t.Fatalf("%d reads after a config edit, want 2", n) |
| + } |
| + // A stamp too recent to trust is never kept: it is read every time. |
| + inputsStampRacy = time.Hour |
| + writeOwnEnv(t, k.b, k.rt, "OWN=2\n") |
| + mustCurrent(t, k.b, k.rt) |
| + mustCurrent(t, k.b, k.rt) |
| + if n := reads.Load(); n != 4 { |
| + t.Fatalf("%d reads over a just-written file, want 4 (no stamp kept)", n) |
| + } |
| +} |
| + |
| +// R3-2: the published inputs are the fingerprint of the env the spawn |
| +// captured, never a re-read. The config file is replaced after the |
| +// capture and before the exec. |
| +func TestLaunchInputsUseCapturedEnv(t *testing.T) { |
| + requireUnixSockets(t) |
| + k := newInputsKit(t) |
| + k.b.Cache = edge.NewCache(10, 1<<20) |
| + stageServingLiveAt(t, k.b, k.rt.Host, "v1") |
| + k.deliver(t, map[string]string{"LOG_LEVEL": "debug"}) |
| + k.b.launchHook = onCall(1, func() { k.deliver(t, map[string]string{"LOG_LEVEL": "info"}) }) |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + defer cancel() |
| + proc, _, err := k.b.Start(ctx, k.rt) |
| + if err != nil { |
| + t.Fatalf("Start: %v", err) |
| + } |
| + defer proc.Stop(context.Background()) |
| + published, ok := k.b.Cache.ProcessInputs(k.rt.Host) |
| + if !ok { |
| + t.Fatal("the spawn published no inputs") |
| + } |
| + if cur := mustCurrent(t, k.b, k.rt); published == cur { |
| + t.Fatalf("the published inputs %q equal the config delivered after the capture", published) |
| + } |
| + // Delivering the captured bytes again makes the current inputs the |
| + // published ones: what was published is the capture's fingerprint. |
| + k.deliver(t, map[string]string{"LOG_LEVEL": "debug"}) |
| + if cur := mustCurrent(t, k.b, k.rt); published != cur { |
| + t.Fatalf("published %q, current over the captured config %q", published, cur) |
| + } |
| +} |
| + |
| +// R3-2: a generation whose build is not the installed one publishes inputs |
| +// that never equal the current ones. |
| +func TestRetainedBuildNeverMatches(t *testing.T) { |
| + requireUnixSockets(t) |
| + lb := newLaunchBackend(t, "flat", &fakeSwapBackend{fakeBackend: &fakeBackend{}}) |
| + eb := lb.eb |
| + eb.Cache = edge.NewCache(10, 1<<20) |
| + rt := lb.rt |
| + rt.Version = "v2" // installed |
| + writeConfigEnv(t, eb, rt, "LOG_LEVEL=debug\n") |
| + id := markerScript(t, t.TempDir(), "v1", filepath.Join(t.TempDir(), "v1.ran")) |
| + g, p, err := eb.StartStaged(context.Background(), rt, Gen{N: nextGen(), Build: id.Version, StagedPath: id.StagedPath, Digest: id.Digest}) |
| + if err != nil { |
| + t.Fatalf("StartStaged: %v", err) |
| + } |
| + lb.procs[g.N] = p |
| + got := procLaunchInputs(p) |
| + if got == "" { |
| + t.Fatal("the staged generation carries no launch inputs") |
| + } |
| + if cur := mustCurrent(t, eb, rt); got == cur { |
| + t.Fatalf("a v1 generation's inputs %q equal the current inputs of installed v2", got) |
| + } |
| + ran := rt |
| + ran.Version = "v1" |
| + if cur := mustCurrent(t, eb, ran); got != cur { |
| + t.Fatalf("launch inputs %q, want the build it ran over the same files %q", got, cur) |
| + } |
| + if _, ok := eb.Cache.ProcessInputs(rt.Host); ok { |
| + t.Fatal("a staged spawn published its inputs before becoming current") |
| + } |
| + eb.publishLaunchInputs(rt, p) |
| + if pub, _ := eb.Cache.ProcessInputs(rt.Host); pub != got || pub == mustCurrent(t, eb, rt) { |
| + t.Fatalf("published %q, want the generation's %q, unequal to the current", pub, got) |
| + } |
| +} |
| + |
| +// A fresh spawn on the live link publishes, at the spawn, inputs equal to |
| +// CurrentInputs: the current side reads and fingerprints the same two |
| +// layers the same way. |
| +func TestNonStagedSpawnPublishesInputs(t *testing.T) { |
| + requireUnixSockets(t) |
| + k := newInputsKit(t) |
| + k.b.Cache = edge.NewCache(10, 1<<20) |
| + stageServingLiveAt(t, k.b, k.rt.Host, "v1") |
| + k.deliver(t, map[string]string{"LOG_LEVEL": "debug"}) |
| + writeOwnEnv(t, k.b, k.rt, "OWN=1\n") |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + defer cancel() |
| + proc, ver, err := k.b.Start(ctx, k.rt) |
| + if err != nil { |
| + t.Fatalf("Start: %v", err) |
| + } |
| + defer proc.Stop(context.Background()) |
| + if ver != "v1" { |
| + t.Fatalf("spawn version %q, want v1", ver) |
| + } |
| + published, ok := k.b.Cache.ProcessInputs(k.rt.Host) |
| + if !ok { |
| + t.Fatal("a live-link spawn published no inputs") |
| + } |
| + if cur := mustCurrent(t, k.b, k.rt); published != cur { |
| + t.Fatalf("published %q, current %q: a fresh spawn with nothing changed must match", published, cur) |
| + } |
| + if procLaunchInputs(proc) != published { |
| + t.Fatalf("the process carries %q, published %q", procLaunchInputs(proc), published) |
| + } |
| +} |
| + |
| +// Sleep, then wake with nothing changed: the second process publishes the |
| +// inputs the first did (the admin token and instance key minted at the |
| +// first spawn are read by both). |
| +func TestWakeSameInputsSameValue(t *testing.T) { |
| + requireUnixSockets(t) |
| + k := newInputsKit(t) |
| + k.b.Cache = edge.NewCache(10, 1<<20) |
| + stageServingLiveAt(t, k.b, k.rt.Host, "v1") |
| + k.deliver(t, map[string]string{"LOG_LEVEL": "debug"}) |
| + wake := func() (Proc, string) { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + defer cancel() |
| + proc, _, err := k.b.StartGen(ctx, k.rt, nextGen(), true) |
| + if err != nil { |
| + t.Fatalf("StartGen: %v", err) |
| + } |
| + got, ok := k.b.Cache.ProcessInputs(k.rt.Host) |
| + if !ok { |
| + t.Fatal("the wake published no inputs") |
| + } |
| + return proc, got |
| + } |
| + p1, first := wake() |
| + sctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + if err := p1.Stop(sctx); err != nil { |
| + t.Fatalf("sleep: %v", err) |
| + } |
| + cancel() |
| + k.b.Cache.NoteProcessInputs(k.rt.Host, "") // the second wake must publish its own |
| + p2, second := wake() |
| + defer p2.Stop(context.Background()) |
| + if first != second { |
| + t.Fatalf("published %q at the first wake and %q at the second, nothing changed", first, second) |
| + } |
| + if cur := mustCurrent(t, k.b, k.rt); second != cur { |
| + t.Fatalf("published %q, current %q", second, cur) |
| + } |
| +} |
| + |
| +// A staged successor's inputs are captured at its launch and published at |
| +// the switch, not before: until then the incumbent's stand. After the |
| +// switch they are its launch-time inputs, even though the config changed |
| +// again after it launched. |
| +func TestStagedSuccessorPublishesAtSwitch(t *testing.T) { |
| + type rig struct { |
| + f *swapFixture |
| + lb *launchBackend |
| + at Attempt |
| + } |
| + rigs := map[string]func(t *testing.T) rig{ |
| + "flat": func(t *testing.T) rig { |
| + f := newSwapFixture(t) |
| + lb := newLaunchBackend(t, "flat", f.b) |
| + f.a.backend = lb |
| + id := markerScript(t, t.TempDir(), "v2", filepath.Join(t.TempDir(), "v2.ran")) |
| + at := f.attempt(ModeOverlap) |
| + at.StagedPath, at.Digest = id.StagedPath, id.Digest |
| + return rig{f, lb, at} |
| + }, |
| + "native nested": func(t *testing.T) rig { |
| + f := newSwapFixture(t) |
| + lb := newLaunchBackend(t, "nested", f.b) |
| + f.a.backend = lb |
| + id := markerScript(t, t.TempDir(), "v2", filepath.Join(t.TempDir(), "v2.ran")) |
| + at := f.attempt(ModeOverlap) |
| + at.StagedPath, at.Digest = id.StagedPath, id.Digest |
| + return rig{f, lb, at} |
| + }, |
| + "rootfs": func(t *testing.T) rig { |
| + f, lb, ctl, at := rootfsSwapFixture(t, ModeOverlap) |
| + ctl.setServe(serveVersions(t, lb.eb, lb.rt, 0, "v2")) |
| + return rig{f, lb.launchBackend, at} |
| + }, |
| + } |
| + for name, mk := range rigs { |
| + t.Run(name, func(t *testing.T) { |
| + requireUnixSockets(t) |
| + r := mk(t) |
| + eb := r.lb.eb |
| + eb.Cache = edge.NewCache(10, 1<<20) |
| + host := r.lb.rt.Host |
| + installed := r.lb.rt |
| + installed.Version = "v2" |
| + writeConfigEnv(t, eb, installed, "LOG_LEVEL=debug\n") |
| + eb.Cache.NoteProcessInputs(host, "incumbent") |
| + var atLaunch string |
| + checked := false |
| + r.f.a.genHealth = func(context.Context, Gen) error { |
| + // The successor runs; the switch has not happened. |
| + if got, _ := eb.Cache.ProcessInputs(host); got != "incumbent" { |
| + t.Errorf("before the switch ProcessInputs = %q, want the incumbent's", got) |
| + } |
| + atLaunch = mustCurrent(t, eb, installed) |
| + writeConfigEnv(t, eb, installed, "LOG_LEVEL=info\n") |
| + checked = true |
| + return nil |
| + } |
| + res := r.f.a.Swap(context.Background(), r.at, r.f.newest) |
| + if res.Outcome != SwapDone { |
| + t.Fatalf("Swap = %+v, want done", res) |
| + } |
| + if !checked { |
| + t.Fatal("the successor's health was never asked") |
| + } |
| + got, ok := eb.Cache.ProcessInputs(host) |
| + if !ok || got != atLaunch { |
| + t.Fatalf("after the switch ProcessInputs = %q, %v; want the successor's launch-time %q", got, ok, atLaunch) |
| + } |
| + if cur := mustCurrent(t, eb, installed); got == cur { |
| + t.Fatalf("published %q equals the current inputs after the later config change", got) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A planned wake's staged spawn publishes nothing at the spawn; the wake |
| +// publishes its inputs when it becomes current (noteCurrent). |
| +func TestStagedWakePublishesInputsWhenCurrent(t *testing.T) { |
| + requireUnixSockets(t) |
| + b := newLaunchBackend(t, "flat", &fakeSwapBackend{fakeBackend: &fakeBackend{}}) |
| + b.eb.Cache = edge.NewCache(10, 1<<20) |
| + dir := t.TempDir() |
| + next := markerScript(t, dir, "v2", filepath.Join(t.TempDir(), "v2.ran")) |
| + good := markerScript(t, dir, "v1", filepath.Join(t.TempDir(), "v1.ran")) |
| + installed := b.rt |
| + installed.Version = "v2" |
| + writeConfigEnv(t, b.eb, installed, "LOG_LEVEL=debug\n") |
| + b.eb.Cache.NoteProcessInputs(b.rt.Host, "a process before this wake") |
| + a, _ := launchActivator(t, b, WakePlan{Boot: next, Mode: ModeOverlap, FirstWake: true, Fallback: &good}) |
| + done, err := a.beginRequest(context.Background(), testRoute("one.example.com")) |
| + if err != nil { |
| + t.Fatalf("wake: %v", err) |
| + } |
| + done() |
| + got, ok := b.eb.Cache.ProcessInputs(b.rt.Host) |
| + if !ok || got != mustCurrent(t, b.eb, installed) { |
| + t.Fatalf("after the wake ProcessInputs = %q, %v; want v2's current inputs", got, ok) |
| + } |
| +} |
| + |
| +// SplitBackend forwards the publish to its exec half for an exec row, and |
| +// publishes nothing for a unit-backed one. |
| +func TestSplitBackendPublishesInputsForExecRowsOnly(t *testing.T) { |
| + eb := testExecBackend(t) |
| + eb.Cache = edge.NewCache(10, 1<<20) |
| + split := &SplitBackend{Exec: eb, Unit: &UnitBackend{}} |
| + p := &childProc{inputs: "in-1"} |
| + split.publishLaunchInputs(registry.Route{Host: "a.example.com"}, p) |
| + if got, ok := eb.Cache.ProcessInputs("a.example.com"); !ok || got != "in-1" { |
| + t.Fatalf("exec row: ProcessInputs = %q, %v; want in-1", got, ok) |
| + } |
| + split.publishLaunchInputs(registry.Route{Host: "u.example.com", Backing: registry.BackingUnit}, p) |
| + if got, ok := eb.Cache.ProcessInputs("u.example.com"); ok { |
| + t.Fatalf("unit-backed row: ProcessInputs = %q, true; want nothing published", got) |
| + } |
| + // A process whose inputs are unknown withdraws the host's. |
| + split.publishLaunchInputs(registry.Route{Host: "a.example.com"}, &fakeProc{}) |
| + if got, ok := eb.Cache.ProcessInputs("a.example.com"); ok { |
| + t.Fatalf("a process with unknown inputs left %q published", got) |
| + } |
| +} |
diff --git a/internal/activator/recoveryprobe.go b/internal/activator/recoveryprobe.go| index 60e4fb24c..3c0027dcc 100644 |
| --- a/internal/activator/recoveryprobe.go |
| +++ b/internal/activator/recoveryprobe.go |
| @@ -343,7 +343,7 @@ func (a *Service) reviewRecoveryHold(e *actEntry) { |
| } |
| log.Printf("activator: %s source opened on the recovery probe's session; serving", e.host) |
| if e.gen.N != 0 { |
| - a.noteCurrent(e.host, e.gen.N) |
| + a.noteCurrent(e) |
| } |
| if a.gens && linksCanonical(e.route, e.gen) { |
| if err := swapCanonicalLink(e.route.Socket, e.gen.Socket); err != nil { |
diff --git a/internal/activator/rootfs.go b/internal/activator/rootfs.go| index d2f9096aa..6d4ffeb36 100644 |
| --- a/internal/activator/rootfs.go |
| +++ b/internal/activator/rootfs.go |
| @@ -423,6 +423,10 @@ func (b *ExecBackend) spawnRootfs(ctx context.Context, rt registry.Route, sock s |
| // layer, kept on the handle as spawnUnitFrom keeps them (merge ruling |
| // M3, instance-key ruling 29). |
| up.launchEnv, up.launchKeyLayer = maps.Clone(fileEnv), keyLayer |
| + // The page cache's launch inputs (inputs.go): the image's version and |
| + // the env this spawn read, before the agent-owned and rootfs |
| + // variables. Published when the generation becomes current. |
| + up.inputs = launchInputs(id.Version, fileEnv) |
| if b.Cache != nil { |
| if n := b.Cache.PurgeHost(rt.Host); n > 0 { |
| log.Printf("activator: purged %d cached response(s) for %s on spawn", n, rt.Host) |
diff --git a/internal/activator/swap.go b/internal/activator/swap.go| index 1492690e0..de6e4fa19 100644 |
| --- a/internal/activator/swap.go |
| +++ b/internal/activator/swap.go |
| @@ -793,7 +793,7 @@ func (a *Service) swapOverlap(ctx context.Context, gb SwapBackend, at Attempt, n |
| a.addMemberLocked(e, retiring) // swapsim:M2 |
| a.installProcLocked(e, nil, m.proc, m.gen) |
| e.spawnVersion, e.staleSince, e.spawnedAt = m.gen.Build, time.Time{}, a.now() |
| - a.noteCurrent(e.host, m.gen.N) // plan 1's cache generation (C4) |
| + a.noteCurrent(e) // plan 1's cache generation (C4), and the page cache's inputs |
| // Runs admitted against the retiring generation are interrupted |
| // with it, as a scheduled restart's stop interrupts them (merge |
| // ruling M2): a command never outlives the build it was started |
diff --git a/internal/activator/unitproc.go b/internal/activator/unitproc.go| index 33dead22c..c7d5574e8 100644 |
| --- a/internal/activator/unitproc.go |
| +++ b/internal/activator/unitproc.go |
| @@ -83,6 +83,11 @@ type unitProc struct { |
| // from, decided by the read that composed launchEnv (instance-key |
| // ruling 29). Written with launchEnv, never again. |
| launchKeyLayer instancekey.Layer |
| + // inputs is the page cache's launch inputs (launchInputs) of a run |
| + // role's unit: its build and launchEnv, set with launchEnv and never |
| + // again. "" for every other role, and for a spawn that did not know |
| + // its build. |
| + inputs string |
| // worker is the rootfs worker this handle watches (rootfs apps Plan 3, |
| // W1), "" for every other handle. A worker's unit is its own |
| // (rootfsUnitFor), its stop names it, and observe tells the member |
| @@ -120,6 +125,8 @@ type launchEnvProc interface { |
| // it. |
| func (p *unitProc) LaunchEnv() map[string]string { return p.launchEnv } |
| +func (p *unitProc) launchedFrom() string { return p.inputs } |
| + |
| // launchKeyLayerProc is a generation handle that also kept where its |
| // launch environment's instance key came from. |
| type launchKeyLayerProc interface { |
diff --git a/internal/edge/cache.go b/internal/edge/cache.go| index 0bebc2c0d..ee385503a 100644 |
| --- a/internal/edge/cache.go |
| +++ b/internal/edge/cache.go |
| @@ -5,6 +5,8 @@ import ( |
| "net/http" |
| "sync" |
| "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| ) |
| // Admission caps that bound how much of the cache any single URL or path can |
| @@ -77,6 +79,17 @@ type Cache struct { |
| // (SetGenerations); nil with generations off. Called under mu, so it |
| // must take no lock its own side holds while calling into the cache. |
| genOf func(route string) (uint64, bool) |
| + |
| + // inputsMu guards the page cache's two inputs (page cache Task 6), |
| + // and nothing else: it is never held with mu, and never while a hook |
| + // runs, so the activator can publish under its own lock. |
| + inputsMu sync.Mutex |
| + // inputs is host -> the inputs the host's current process was started |
| + // from (NoteProcessInputs). A host with none has no known inputs. |
| + inputs map[string]string |
| + // currentInputs answers a route's current inputs (SetCurrentInputs); |
| + // nil answers none. |
| + currentInputs func(registry.Route) (string, bool) |
| } |
| type cacheURLKey struct { |
| @@ -151,7 +164,64 @@ func NewCache(maxEntries, maxBodyBytes int) *Cache { |
| byURL: make(map[cacheURLKey]map[cacheFullKey]*list.Element), |
| byPath: make(map[cachePathKey]map[cacheFullKey]*list.Element), |
| byHost: make(map[string]map[cacheFullKey]*list.Element), |
| + inputs: make(map[string]string), |
| + } |
| +} |
| + |
| +// NoteProcessInputs records that host's current process was started from |
| +// inputs: the activator calls it when a process becomes current, never at |
| +// staging. An empty inputs withdraws the host's: a process whose inputs |
| +// are not known answers nothing that may be stored. |
| +func (c *Cache) NoteProcessInputs(host, inputs string) { |
| + if c == nil { |
| + return |
| + } |
| + c.inputsMu.Lock() |
| + defer c.inputsMu.Unlock() |
| + if inputs == "" { |
| + delete(c.inputs, host) |
| + return |
| + } |
| + if c.inputs == nil { |
| + c.inputs = make(map[string]string) |
| + } |
| + c.inputs[host] = inputs |
| +} |
| + |
| +// ProcessInputs is the inputs host's current process was started from, as |
| +// last published by NoteProcessInputs. false: none are known. |
| +func (c *Cache) ProcessInputs(host string) (string, bool) { |
| + if c == nil { |
| + return "", false |
| + } |
| + c.inputsMu.Lock() |
| + defer c.inputsMu.Unlock() |
| + in, ok := c.inputs[host] |
| + return in, ok |
| +} |
| + |
| +// SetCurrentInputs installs the answer to a route's current inputs: the |
| +// host wires the exec backend's CurrentInputs here. |
| +func (c *Cache) SetCurrentInputs(f func(registry.Route) (string, bool)) { |
| + c.inputsMu.Lock() |
| + defer c.inputsMu.Unlock() |
| + c.currentInputs = f |
| +} |
| + |
| +// CurrentInputs is rt's current inputs from the installed hook, asked with |
| +// no lock of the cache's held. false with no hook, or when the hook does |
| +// not know them. |
| +func (c *Cache) CurrentInputs(rt registry.Route) (string, bool) { |
| + if c == nil { |
| + return "", false |
| + } |
| + c.inputsMu.Lock() |
| + f := c.currentInputs |
| + c.inputsMu.Unlock() |
| + if f == nil { |
| + return "", false |
| } |
| + return f(rt) |
| } |
| // SetGenerations arms the generation guard (spec §7.2): a tagged entry is |
diff --git a/internal/edge/cache_test.go b/internal/edge/cache_test.go| index 28b321531..23c0d9369 100644 |
| --- a/internal/edge/cache_test.go |
| +++ b/internal/edge/cache_test.go |
| @@ -6,6 +6,8 @@ import ( |
| "net/http/httptest" |
| "testing" |
| "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| ) |
| func TestCacheGetMissOnEmpty(t *testing.T) { |
| @@ -543,3 +545,58 @@ func TestCachePurgeURLRemovesAllVaryVariants(t *testing.T) { |
| t.Fatal("expected unrelated URL to survive purge") |
| } |
| } |
| + |
| +// The published inputs table (page cache Task 6): a round trip, an unknown |
| +// host, an empty publish that withdraws a host's inputs, and the current |
| +// side's hook, which answers false until it is set. |
| +func TestCacheProcessInputs(t *testing.T) { |
| + c := NewCache(10, 1<<20) |
| + if got, ok := c.ProcessInputs("a.example.com"); ok || got != "" { |
| + t.Fatalf("unknown host: ProcessInputs = %q, %v; want \"\", false", got, ok) |
| + } |
| + c.NoteProcessInputs("a.example.com", "in-1") |
| + c.NoteProcessInputs("b.example.com", "in-2") |
| + if got, ok := c.ProcessInputs("a.example.com"); !ok || got != "in-1" { |
| + t.Fatalf("after a publish: ProcessInputs = %q, %v; want in-1", got, ok) |
| + } |
| + c.NoteProcessInputs("a.example.com", "in-3") |
| + if got, ok := c.ProcessInputs("a.example.com"); !ok || got != "in-3" { |
| + t.Fatalf("after a second publish: ProcessInputs = %q, %v; want in-3", got, ok) |
| + } |
| + // A process that became current with unknown inputs withdraws the |
| + // host's: nothing it answers may be stored. |
| + c.NoteProcessInputs("a.example.com", "") |
| + if got, ok := c.ProcessInputs("a.example.com"); ok { |
| + t.Fatalf("after an empty publish: ProcessInputs = %q, true; want false", got) |
| + } |
| + if got, ok := c.ProcessInputs("b.example.com"); !ok || got != "in-2" { |
| + t.Fatalf("another host: ProcessInputs = %q, %v; want in-2", got, ok) |
| + } |
| + |
| + rt := registry.Route{Host: "a.example.com", Version: "v1"} |
| + if got, ok := c.CurrentInputs(rt); ok || got != "" { |
| + t.Fatalf("no hook: CurrentInputs = %q, %v; want \"\", false", got, ok) |
| + } |
| + var asked []string |
| + c.SetCurrentInputs(func(r registry.Route) (string, bool) { |
| + asked = append(asked, r.Host) |
| + return "cur-" + r.Version, r.Version != "" |
| + }) |
| + if got, ok := c.CurrentInputs(rt); !ok || got != "cur-v1" { |
| + t.Fatalf("hook set: CurrentInputs = %q, %v; want cur-v1", got, ok) |
| + } |
| + if _, ok := c.CurrentInputs(registry.Route{Host: "c.example.com"}); ok { |
| + t.Fatal("hook's false was answered as known") |
| + } |
| + if len(asked) != 2 || asked[0] != "a.example.com" { |
| + t.Fatalf("the hook was asked for %v", asked) |
| + } |
| + |
| + var nilCache *Cache |
| + if _, ok := nilCache.ProcessInputs("a.example.com"); ok { |
| + t.Fatal("a nil cache answered process inputs") |
| + } |
| + if _, ok := nilCache.CurrentInputs(rt); ok { |
| + t.Fatal("a nil cache answered current inputs") |
| + } |
| +} |