carlos / platform Public

spec: #892 design rev 2, Astra round 1 P2 fixes

Round 1 was READY AFTER FIXES with two P2s and no P1, so the review
stops here (stopping rule 1). S1 now gives each role its own rule:
web the generation's tier, a worker its web generation's tier, and no
variable for release, runs and sessions. S3's drain swap gets explicit
check, withdraw, settle, stop and abort steps, with the drain mark a
state the hub honours at once rather than a health failure.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 8f2aa3ae393bf084ef0666392891065087f45273 parent d526ab0
2 files changed, +3,695 −20
  • docs/superpowers/reviews/CODEX-FINDINGS-STATELESS-REPLICAS-SCALE-R1.md +3,642 −0
  • docs/superpowers/specs/2026-11-11-stateless-replicas-production-scale-design.md +53 −20

CI cancelled — superseded by a newer push — run details

diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-STATELESS-REPLICAS-SCALE-R1.md b/docs/superpowers/reviews/CODEX-FINDINGS-STATELESS-REPLICAS-SCALE-R1.md
new file mode 100644
index 000000000..8ae2f6cc2
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-STATELESS-REPLICAS-SCALE-R1.md
@@ -0,0 +1,3642 @@
+# Astra findings: stateless replicas at production scale design, round 1
+
+Reviewer: Astra (codex exec -m gpt-6-astra, read-only), brief CODEX-REVIEW-BRIEF-STATELESS-REPLICAS-SCALE.md at d526ab09. Final answer verbatim below.
+
+I’ll read the brief and spec, then review only the five checks and use the requested findings and verdict format.
+exec
+/bin/bash -lc 'cat docs/superpowers/reviews/CODEX-REVIEW-BRIEF-STATELESS-REPLICAS-SCALE.md' in /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-stateless-replicas-scale
+ succeeded in 0ms:
+# Review brief: stateless replicas at production scale design (#892), round 1 of 3
+
+Repo carlos/platform, branch `design-stateless-replicas-scale`, commit 8bfc752b.
+Under review: `docs/superpowers/specs/2026-11-11-stateless-replicas-production-scale-design.md`.
+Authorities (merged on main): `docs/superpowers/specs/2026-11-01-stateless-replicas-design.md`
+("11-01"), `docs/superpowers/specs/2026-10-24-rootfs-apps-design.md`, `docs/site/rootfs.md`,
+and the code on this branch (which is main 01d6ca78).
+
+S2 and S3 name #511 Plan 4 (`stateless-replicas-4`, unmerged) as where they will
+be built later. Do not review Plan 4 or its branch. Review S2 and S3 only for
+consistency with the merged 11-01 design and today's code; their plans are written
+after Plan 4 merges.
+
+You are an independent reviewer. Read the document, then the code it names, and
+check every claim against that code.
+
+## Fixed: do not re-argue
+
+- 11-01 §5 (Paul's decisions): one copy per box, a copy may grow to fit its box,
+ workers on every copy, release once per deploy, websockets drop and reconnect.
+- Paul asked for #892 to be done without a live brainstorm; the author's calls are
+ listed in §9 for him. Report a call only if it is unsafe or contradicts a merged
+ authority, not because another call is possible.
+
+## What to check
+
+1. §2's rejection of worker-only instances: does 11-01 §6.6 (and the code) really
+ run the release command once per instance, so two instances of one app run it
+ twice per build?
+2. S1 (`CARLOS_MEMORY_MIB`): can the agent set it on every rootfs launch path from a
+ limit it already computes, with no new reads? Check `internal/activator/rootfs.go`
+ `spawnRootfs` (its `tier`), `rootfsenv.go` (workers inherit web's launch env;
+ release, run and TTY env), `backend_rootfs.go`, and the agent-owned name lists
+ (`agentOwnedNames`, `rootfsOwnedNames`, `moves.AgentOwnedVars` and its pin test).
+ Name any reader that would break or any path where the figure would be wrong
+ (for example a run or session whose unit has a different limit than the instance,
+ or a worker started after a size change against web's older launch env).
+3. S3 (drain swap): is "drain when copies > 1 and the size is a fleet size, never
+ drain a copy with no other copy serving" coherent with 11-01 §6.3-§6.4 and the
+ hub routing on main (`internal/edge`, Plan 3)? Is there a case where a box drains
+ the last serving copy, or where the hub keeps sending to a draining copy?
+4. §3's arithmetic and the 27.3 GiB budget figure.
+5. Anything in the design that contradicts a merged spec or today's code.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+ Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the section, the problem, the evidence
+(file:line, verified), the failure scenario, a concrete fix and the invariant or
+trust boundary it breaks (that is its fault family). End with exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites. Keep to the five checks above.
+
+exec
+/bin/bash -lc 'cat /home/paulca/.agents/skills/plain-writing/SKILL.md' in /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-stateless-replicas-scale
+ succeeded in 0ms:
+---
+name: plain-writing
+description: Plain, direct writing voice — no undefined jargon, no throat-clearing, no showing off — for any prose a person reads (reports, docs, emails, proposals, summaries, chat replies). Use by default when writing or revising prose.
+---
+
+# Plain writing
+
+Vendored from [evanphx/llm-voice](https://github.com/evanphx/llm-voice)
+(`plain-writing/SKILL.md`). Edit upstream first, then re-copy.
+
+Write plain and direct. Apply from the first sentence, to your own replies and
+summaries as much as to drafts you're handed.
+
+## Three vices to cut
+
+**1. Deep jargon.** An acronym or insider term used without defining it, or
+several undefined terms stacked in one sentence. Define each term in a few plain
+words on first use, or don't use it. Covers corporate shorthand, not just
+technical terms.
+- No: "We'll leverage the Q3 GTM motion to move the needle on NRR."
+- Yes: "In the third quarter we'll aim the sales plan at getting current
+ customers to spend more."
+- Reuse the short form after one definition: "annual recurring revenue (ARR) —
+ the subscription income we count on each year" then "ARR."
+
+**2. Throat-clearing.** Preamble and narration about what the text is about to
+do. Don't announce structure, editorialize your reasoning, or warm up. Cut "it's
+worth being concrete," "before we get into it," "the honest truth is," "this is
+the part that matters most."
+- No: "Before the details, it's worth stepping back. The honest truth is
+ onboarding is broken."
+- Yes: "Onboarding is broken: four in ten new users quit before finishing setup."
+- Cousin — claiming a virtue instead of showing it: "the honest answer," "to be
+ fair," "frankly," "the real question." Delete the label, keep the sentence.
+
+**3. Showing off.** Flourish that sounds clever instead of informing. No
+rhetorical triads, aphorisms, italics for drama, cute headings, or punchline
+sentences. Cut any sentence doing rhetorical work rather than carrying
+information.
+- No: "We shipped fast, we shipped hard, and we shipped it *beautiful*."
+- Yes: "We shipped the redesign in six weeks."
+- Also cut the stacked "not X; Y" antithesis and the punchy fragment for emphasis
+ ("Users absorb that as normal. It isn't.").
+
+## Two positive rules
+
+- Plain words, active voice, one idea per sentence in the opening.
+- Readable, not dry: lead with a concrete example and keep the prose flowing.
+
+## Mechanics
+
+- Active voice: "The team missed the deadline," not "was missed by the team."
+ Passive only when the actor is unknown or irrelevant, or when the only
+ subject on offer is an inert thing (next rule).
+- Don't give inert things verbs. A ticket, page, record, widget or setting
+ doesn't show, ask, know or want anything. Use the passive and say where it
+ happens: "Details are shown on the ticket record," not "The ticket shows its
+ details"; "Questions are asked on the widget view," not "The widget asks
+ questions." Software that really runs, like a server, a script or a
+ scheduled job, keeps its verbs: "The script sends the brief to Codex."
+- Present tense: "The sidebar is hidden while this setting is on."
+- Address the reader as "you." "We" only for shared work you're part of.
+- Condition before instruction: "If payment fails, retry once."
+- One idea per sentence: split on a second "and" or a load-bearing "which."
+- Define a term on first use: long form, short form in parentheses, then short
+ form.
+- Cut reader-blaming softeners: "simply," "just," "easy," "obviously," "of
+ course."
+- Cut filler openers: "It's worth noting that," "Basically," "At the end of the
+ day."
+- Sentence case for headings.
+- Unambiguous dates: "2026-08-20" or "August 20, 2026," never "08/09."
+- Technical writing: code, commands, filenames, and literals in monospace; UI
+ names in bold.
+
+## Cutting length
+
+Revision bloats through repetition: a reframing gets patched into every section,
+and one claim ends up stated five ways. Reading straight through won't catch it;
+counting will.
+- List the distinct claims (assertions, not sections); find and count each. Give
+ a repeated claim one home — where the argument is developed, not previewed. A
+ summary restating a developed claim is fine; the same argument at full strength
+ twice is not.
+- Sweep for dangling references — ordinals, comparatives, coined shorthand whose
+ antecedent was cut. Name what each points at; if you can't, it dangles.
+- When cuts run out and it's still too long, don't promise a length you can't
+ hit. Say early: "hitting that length means dropping an argument — here are the
+ candidates; which do you want to lose?"
+
+## Structure is a separate pass
+
+These rules fix prose, not structure. A malformed header, a claim ordered before
+its setup, a section that overpromises — each fails independently. State the
+format's fixed requirements explicitly and run its check or template. Only a
+check guarantees structure.
+
+## Reusable prompt block
+
+Prepend when prompting a model to draft prose:
+
+```text
+Write this in a plain, direct voice. Follow these rules strictly:
+1. No undefined jargon. Define any acronym or insider term in a few plain words on first use, or don't use it. Never stack several undefined terms in one sentence.
+2. No throat-clearing. Don't announce what you're about to do, don't narrate structure, don't editorialize your reasoning. State the thing.
+3. No showing off. No rhetorical triads, aphorisms, italics for drama, cute headings, or lines that exist to sound clever. Cut any sentence doing rhetorical work rather than carrying information.
+4. Plain words, active voice, one idea per sentence in the opening.
+5. Still readable — not choppy or dry. Lead with a concrete example and keep the prose flowing.
+6. Don't give inert things verbs. A ticket, page, record or widget doesn't show, ask or know anything. Use the passive and say where it happens: "Details are shown on the ticket record," not "The ticket shows its details." Software that really runs, like a server or a script, keeps its verbs.
+```
+
+## Self-check
+
+- Any acronym or specialist term undefined on first use?
+- Any sentence announcing what you're about to do instead of doing it?
+- Any line there to sound clever rather than inform?
+- Any ticket, page or widget doing something only a person or a running
+ program can do?
+- Gentle to read, or a list of assertions?
+
+If the project or publication has a style guide, it wins where they disagree.
+
+exec
+/bin/bash -lc 'nl -ba docs/superpowers/specs/2026-11-11-stateless-replicas-production-scale-design.md' in /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-stateless-replicas-scale
+ succeeded in 0ms:
+ 1 # Stateless replicas at production scale: big copies, not many
+ 2
+ 3 Rev 1, 2026-11-11. Discussion #892, a follow-up to #511. Builds on the
+ 4 stateless replicas design (`docs/superpowers/specs/2026-11-01-stateless-replicas-design.md`,
+ 5 "the 11-01 design" below) and changes none of its decisions. Brainstorm:
+ 6 Paul asked for #892 to be taken to done on 2026-11-11 without a live
+ 7 session, so every call here is the author's, marked, and listed in §9 for
+ 8 Paul to confirm or overturn. Boundary agreed with the #511 Plan 4
+ 9 controller the same day (§7).
+ 10
+ 11 ## 1. Intent
+ 12
+ 13 The 11-01 design runs an app as one copy per fleet box. Its first user's
+ 14 staging needs one instance per app, two copies and at most 2 GiB per copy,
+ 15 and v0.35.0 ships exactly that.
+ 16
+ 17 The same user's production is a Rails estate that today runs on another
+ 18 platform as many small processes. Use neutral names (shop, example.com)
+ 19 in everything this design produces; the shape is:
+ 20
+ 21 | App | Web processes | Background workers |
+ 22 |-----|---------------|--------------------|
+ 23 | A (largest) | 20, 1.5 GiB requested, 2 GiB limit, 5 threads, one process each | 10 at 2 GiB, plus 3 mailer workers at 1 GiB |
+ 24 | B | 16 at 1 GiB | 6 at 2 GiB, no limit |
+ 25 | C | 3 at 1 GiB | 1 at 400 MiB |
+ 26 | D | 3 at 1 GiB | 2 at 1 GiB |
+ 27
+ 28 Its production fleet will be three boxes with 8 vCPU and 32 GiB each, one
+ 29 per availability zone. #892 asked for three things to make that fit:
+ 30
+ 31 1. separate worker instances, or worker-only copies, because one worker
+ 32 alone wants about 2 GiB;
+ 33 2. copy counts well above 2;
+ 34 3. a memory and CPU size per process type.
+ 35
+ 36 This design answers all three without giving up "a copy means a box".
+ 37
+ 38 ## 2. The decision: scale a copy up, keep copies to boxes (author's call)
+ 39
+ 40 The 11-01 design §5.4 already chose this for one box ("one copy (more Puma
+ 41 workers, more Sidekiq threads) uses the hardware", Paul, option 1 of two).
+ 42 At production scale it holds, and it is cheaper than every alternative:
+ 43
+ 44 - **Copies stay at most one per box.** On a three-box fleet an app runs 3
+ 45 copies, not 20. The anti-goal stands (11-01 §4): a copy count always
+ 46 means "survives that many boxes minus one". Hub routing (Plan 3) spreads
+ 47 across three upstreams; nothing about it changes with the count.
+ 48 - **A copy is several processes of each kind.** The 20 one-process web pods
+ 49 become, per box, one web process in Puma's cluster mode with about 7
+ 50 workers (`WEB_CONCURRENCY`) of 5 threads each: 21 workers across the
+ 51 fleet. The 10 workers become a Sidekiq swarm, or several worker entries
+ 52 in `processes.json` (up to `release.MaxWorkers`, 4), on every copy.
+ 53 Preloaded Puma workers share their boot memory, which one process per pod
+ 54 cannot. These are the app's own process managers, configured through its
+ 55 environment; the platform adds nothing to run them (§4 S1 gives them
+ 56 their size).
+ 57 - **Web and workers stay in one copy** (11-01 §5.5 unchanged: workers run
+ 58 on every copy). With copies up to most of a box (§4 S2) a 2 GiB worker
+ 59 no longer has to share 2 GiB with web.
+ 60
+ 61 Rejected:
+ 62
+ 63 - **Worker-only instances** (a second instance of the app that runs only
+ 64 its workers). The 11-01 design §6.6 runs the release command once per
+ 65 instance per build. Two instances of one app would run the migrations
+ 66 twice per deploy, at the same time on different boxes; Rails then fails
+ 67 one of them on its migration lock, and that instance's deploy stops.
+ 68 Fixing it needs an order between instances (one runs release, the other
+ 69 waits for its result), which is a new cross-instance protocol for no
+ 70 gain the per-copy processes don't already give.
+ 71 - **Worker-only copies** (a copy runs a chosen subset of the processes).
+ 72 It puts a web copy and a worker copy of one app on one box, which is the
+ 73 packing the 11-01 design refused (§3, §4), and it makes the copy count
+ 74 stop meaning boxes. It comes back, if ever, with autoscaling (11-01 §9).
+ 75 - **Many small copies per box.** The same anti-goal, plus a database pool,
+ 76 a Rails boot and a hub upstream per copy.
+ 77
+ 78 ## 3. Does the estate fit? Worked numbers
+ 79
+ 80 A 32 GiB box reports about 31.2 GiB (t4g.xlarge's 16 GiB reports 15.6).
+ 81 The fleet budget for one copy (Plan 4 Task 4, §4 S2) is the total less
+ 82 max(1 GiB, total/8): about 27.3 GiB.
+ 83
+ 84 At the other platform's requests, each box would carry a third of every
+ 85 app:
+ 86
+ 87 | App | Web per box | Workers per box | Per box |
+ 88 |-----|-------------|-----------------|---------|
+ 89 | A | 20 x 1.5 / 3 = 10.0 GiB | (10 x 2 + 3 x 1) / 3 = 7.7 GiB | 17.7 GiB |
+ 90 | B | 16 x 1 / 3 = 5.3 GiB | 6 x 2 / 3 = 4.0 GiB | 9.3 GiB |
+ 91 | C | 1.0 GiB | 0.1 GiB | 1.1 GiB |
+ 92 | D | 1.0 GiB | 0.7 GiB | 1.7 GiB |
+ 93 | All | | | 29.8 GiB |
+ 94
+ 95 So at request level the estate does not fit three 32 GiB boxes, and there
+ 96 is no room left for a deploy that starts a new copy beside the old one.
+ 97 Two facts move it: requests are not resident memory (the same apps on
+ 98 staging measured 0.1 to 1.2 GiB resident per app), and Puma's preloaded
+ 99 workers share their boot memory. Whether it fits is a measurement, not
+ 100 something this design can settle. **Before cutover, the operator measures
+ 101 each app's resident memory per process at production load**, and sizes
+ 102 the fleet from that (§9 Q5). The docs give this arithmetic (§4 S4).
+ 103
+ 104 What the design must guarantee is that a big copy can deploy at all: see
+ 105 §4 S3.
+ 106
+ 107 ## 4. What gets built, in order
+ 108
+ 109 Four slices, each its own plan. S1 is independent of #511 Plan 4 and
+ 110 starts now. S2 to S4 touch Plan 4's code (sizes, swaps, the floor), so
+ 111 their plans are written after Plan 4 merges (stopping rule 4).
+ 112
+ 113 ### S1. Every process learns its size (now)
+ 114
+ 115 Each rootfs process gets `CARLOS_MEMORY_MIB`: the memory limit, in MiB,
+ 116 that the instance runs at on this start. Web, workers and release see the
+ 117 same number, because they share it (rootfs spec: "All of an instance's
+ 118 processes share one memory and CPU limit"), and so do a `carlos run` and
+ 119 an interactive session. It is agent-owned like
+ 120 `CARLOS_HOST`: set on every launch, whatever the instance's files say.
+ 121
+ 122 With it, one `processes.json` and one Puma config serve every size: for
+ 123 example `workers ENV.fetch("WEB_CONCURRENCY") { [ENV["CARLOS_MEMORY_MIB"].to_i / 1024, 1].max }`.
+ 124 A Sidekiq swarm's count and its per-process memory restart limit derive
+ 125 the same way. A size change takes effect at the next start, as sizes do
+ 126 today, and the variable follows it.
+ 127
+ 128 CPU is not added: Puma and concurrent-ruby already count the CPUs the
+ 129 process can use.
+ 130
+ 131 Author's call on the name and unit. MiB, not bytes, because every app
+ 132 divides it by a process size, and it matches the size table's own figures.
+ 133
+ 134 ### S2. Larger sizes on owned fleets (after Plan 4 merges)
+ 135
+ 136 Plan 4 Task 4 as reviewed on `stateless-replicas-4` (its text and rulings
+ 137 R6, R11, R12; R17 deferred it from v0.35.0 and the Plan 4 controller
+ 138 handed it to #892 on 2026-11-11):
+ 139
+ 140 - new named sizes, for copies on an owned fleet only;
+ 141 - a copy may use its box's memory less max(1 GiB, total/8);
+ 142 - existing sizes keep the quarter rule everywhere;
+ 143 - the new sizes need the replica floor on every destination and the
+ 144 console;
+ 145 - an overlap reserves its memory before it starts, and a refusal leaves
+ 146 the old build serving.
+ 147
+ 148 One change to its table (author's call): add 4g, 8g, 16g and 32g between
+ 149 Task 4's 6g, 12g, 24g and 48g, so a 32 GiB box (27.3 GiB budget) is not
+ 150 left choosing between 12g and 24g for its largest app. CPU follows the
+ 151 same 200 percent per GiB. The rows above 48g stay as Task 4 wrote them.
+ 152
+ 153 No check sums the sizes of every app's copies on one box. A size is a
+ 154 limit, not a reservation, today and here; the size door's reply already
+ 155 shows each box's committed total beside its memory, and the docs say to
+ 156 keep it under the budget (S4). Refusing over-commit is §9 Q4.
+ 157
+ 158 ### S3. A copy too big to overlap swaps by drain (after S2)
+ 159
+ 160 Raised by the Plan 4 controller. Today a deploy starts the new build
+ 161 beside the old one on the same box, then moves traffic (the overlap swap),
+ 162 and 11-01 §6.4 does the same per copy, one box at a time. A copy sized to
+ 163 most of its box cannot have a second copy beside it, so with S2 alone
+ 164 every deploy of a big copy would stop at the memory check.
+ 165
+ 166 The drain swap replaces the overlap for those copies:
+ 167
+ 168 1. The box takes its copy out of the hub's set (its health answer stops
+ 169 counting it as up) and waits, for a bounded time the plan sets, until
+ 170 the hub has stopped sending and its requests in flight have finished.
+ 171 2. It stops the old copy: web, then the workers, proven gone as today.
+ 172 3. It starts the new build and, once web is healthy, puts the copy back in
+ 173 the hub's set. Its workers start after web, as today.
+ 174 4. The next box's permit (Plan 4) follows only then.
+ 175
+ 176 Release still runs once, before any box swaps (11-01 §5.3). While one box
+ 177 swaps, the other copies carry the traffic, so the docs say to size an app
+ 178 so that its copies less one carry its peak, as on any platform that rolls
+ 179 one machine at a time. Websockets on the swapping copy drop and reconnect
+ 180 (11-01 §5.6, accepted).
+ 181
+ 182 Which swap a copy uses (author's call): the drain swap when the instance
+ 183 has copies above 1 and its size is a fleet size (S2); the overlap swap
+ 184 otherwise, exactly as today. That is fixed by the instance's settings, so
+ 185 a deploy never changes mode because of how full a box happens to be. A
+ 186 copy that has no other copy serving (copies 1, or the others down) is
+ 187 never drained: an overlap that does not fit is refused and the old build
+ 188 keeps serving, as Task 4 says, and the operator can ship `--swap hold`.
+ 189
+ 190 S3 ships in the same release as S2 and behind the same floor, so a box
+ 191 that could be handed a fleet size always knows the drain swap.
+ 192
+ 193 ### S4. Three boxes, and the guide (after S3)
+ 194
+ 195 - The 11-01 drill (§5.7) on three boxes: spread within 28 to 38 percent
+ 196 per box, one box hard-stopped ("2 of 3", no failed reads among requests
+ 197 not yet answered), its return, and a deploy under load with drain swaps:
+ 198 release once, one box at a time, no failed reads. It runs in a #421
+ 199 window booked with the release controller, as Plan 4's drill does.
+ 200 - A production sizing page in the docs: §2's process model (Puma cluster
+ 201 mode, a Sidekiq swarm, worker entries), §3's arithmetic with the
+ 202 measure-first rule, the budget, "copies less one carry the peak", one
+ 203 app deployed at a time, and the hub as the one box that is not yet
+ 204 redundant (11-01 §3). Through copy review.
+ 205
+ 206 ## 5. Per-process sizes (#892 item 3): inside the copy
+ 207
+ 208 The copy's size covers all its processes. Bounds per process are the
+ 209 app's own process managers' (Puma's worker restarts, a Sidekiq swarm's
+ 210 memory limit), set from `CARLOS_MEMORY_MIB` (S1). That matches how the
+ 211 other platform's limit worked per pod, without a platform field per
+ 212 process type.
+ 213
+ 214 A platform limit per process (each worker unit with its own memory limit,
+ 215 a share of the copy's) is not in this design. It would need a new policy
+ 216 field, a root-side change to the worker units, and a census review, for a
+ 217 case (one worker starving web inside a copy) the app's managers already
+ 218 cover. It comes back if the drill or production shows the need (§9 Q3).
+ 219
+ 220 ## 6. Constraints
+ 221
+ 222 - 11-01 §7 applies whole: copy review with no em dashes, the census for any
+ 223 change to the root binary, a provider-neutral core, no new per-box or
+ 224 per-copy bucket polling, the release floor, dev first.
+ 225 - S1's variable is set by the agent from the size it already computes for
+ 226 the start; it reads nothing new.
+ 227 - Neutral names in code, copy, tests and comments.
+ 228 - Region HA guards (Plan 4 D11) apply to S2 to S4: they touch the activator
+ 229 and placement, so they read region HA spec §25 and §7.5 first and run the
+ 230 grouproll and region HA boundary tests.
+ 231
+ 232 ## 7. Boundary with #511 (agreed 2026-11-11 with the Plan 4 controller)
+ 233
+ 234 - #892 does not touch `stateless-replicas-4` or any file Plan 4 lists until
+ 235 Plan 4 merges.
+ 236 - Plan 4 Task 4 is #892's S2, built after Plan 4 merges.
+ 237 - S1 is independent: Plan 4 does not touch the rootfs environment.
+ 238 - S3's drain swap changes Plan 4's swap code, so it is built after Plan 4
+ 239 merges.
+ 240
+ 241 ## 8. Not in this design
+ 242
+ 243 - Worker-only instances and worker-only copies (§2).
+ 244 - Copies above the fleet's box count, or two copies on one box.
+ 245 - Platform limits per process (§5).
+ 246 - Hub redundancy and autoscaling (11-01 §3 and §9 unchanged).
+ 247
+ 248 ## 9. For Paul
+ 249
+ 250 Q1. Scale by size and keep one copy per box (§2), rather than worker
+ 251 instances or worker-only copies. Recommended; it is §5.4's choice carried
+ 252 to production.
+ 253
+ 254 Q2. The drain swap for copies above 1 at fleet sizes (S3), chosen by
+ 255 settings rather than by how full the box is. Recommended.
+ 256
+ 257 Q3. No platform limit per process for now (§5). Recommended; the
+ 258 alternative is a per-worker memory share at root, about one plan's work.
+ 259
+ 260 Q4. Allow over-commit of sizes across apps on one box (S2), showing the
+ 261 committed total rather than refusing. Recommended, as it is today.
+ 262
+ 263 Q5. The production fleet's size is the operator's to measure (§3): at
+ 264 request level the estate needs about 29.8 GiB per box against a 27.3 GiB
+ 265 budget. This is information for the deployment, not a platform change.
+ 266
+ 267 Q6. The S2 table adds 4g, 8g, 16g and 32g to Task 4's tiers.
+
+exec
+/bin/bash -lc 'nl -ba docs/superpowers/specs/2026-11-01-stateless-replicas-design.md' in /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-stateless-replicas-scale
+ succeeded in 0ms:
+ 1 # Stateless replicas: several copies of one app on a fleet
+ 2
+ 3 Rev 2, 2026-11-01 (rev 1 plus the builder check: §6.3 corrected, §6.6 added). Brainstormed with Paul in the session that closed rootfs
+ 4 apps Plan 6. Discussion: to be filed on amadan carlos/platform; related
+ 5 #366 (rootfs apps), #457 (managed fleets), region HA (spec
+ 6 2026-10-26-region-ha-without-claims-design.md).
+ 7
+ 8 ## 1. Intent
+ 9
+ 10 Today every CARLOS instance runs on exactly one box. If that box dies, the
+ 11 app is down until it comes back or moves. And one app can only use what one
+ 12 copy on one box can do.
+ 13
+ 14 This design lets an app that keeps no state on its box run as several
+ 15 copies, each on a different box of a fleet. The hub spreads requests across
+ 16 the copies, and when a box dies the other copies carry on. Paul wants two
+ 17 things from it, both his words: "if it dies, the whole app goes down" is the
+ 18 problem, and handling more traffic matters too. When a box dies, "ideally
+ 19 someone wouldn't notice".
+ 20
+ 21 It is the prerequisite Paul set (2026-10-24, rootfs spec §13 Q1) for moving
+ 22 a Rails app off Kubernetes. It is also region HA's "part 2".
+ 23
+ 24 ### The first user
+ 25
+ 26 A single-tenant deployment adds a fleet of two boxes in eu-west-1 (Ireland),
+ 27 in different availability zones. It runs its Rails apps on them side by
+ 28 side, as rootfs apps:
+ 29
+ 30 - The apps keep their data outside the platform: MySQL or Postgres and
+ 31 Redis in the same region, reached through the operator's egress allow
+ 32 (#328).
+ 33 - Background jobs run in Sidekiq Enterprise. Its periodic jobs elect a
+ 34 leader through Redis, so each fires once however many Sidekiq processes
+ 35 run.
+ 36 - Migrations run in a release hook on Kubernetes today.
+ 37 - Some apps use Action Cable, with Redis as the broadcast adapter.
+ 38
+ 39 Use neutral names in everything this design produces (shop, example.com):
+ 40 no tenant names in code, copy, tests or comments.
+ 41
+ 42 ## 2. Goals
+ 43
+ 44 1. An app declared as keeping no local database can run as N copies, each
+ 45 on a different box of its fleet (`--copies N`).
+ 46 2. The hub spreads requests across the copies that are up, and stops
+ 47 sending to a copy within seconds of its box dying.
+ 48 3. Losing one fleet box loses no reads, and the app keeps serving from the
+ 49 other copies with nobody touching anything.
+ 50 4. A deploy runs the release command once, then switches the copies one
+ 51 box at a time, so one copy always serves.
+ 52 5. Every copy runs the app's declared workers.
+ 53 6. People can see how many copies are running and where.
+ 54
+ 55 ## 3. Non-goals for the first version
+ 56
+ 57 Each of these is wanted later. None is part of this build.
+ 58
+ 59 - **Hub redundancy.** Traffic to a fleet still enters through the hub (the
+ 60 console's box). A dead hub makes every copy unreachable. Paul,
+ 61 2026-11-01: "hub redundancy is what we'll want, so for first version this
+ 62 is fine". The first version survives losing a fleet box, not the hub.
+ 63 - **Autoscaling.** No load-based scaling, and nothing that starts or stops
+ 64 machines. Nothing in the platform launches EC2 today. Paul finds
+ 65 autoscaling up and down "highly appealing"; it comes after copies work.
+ 66 `--copies` is the number autoscaling will later move between a minimum
+ 67 and a maximum.
+ 68 - **Carloku's shared regions and platform boxes.** Copies run on fleets
+ 69 only. Shared regions need plans, caps and billing to count copies, an
+ 70 outside load balancer (region HA, mostly unbuilt), and rootfs is not
+ 71 allowed on shared boxes.
+ 72 - **Several copies of one app on one box** ("packing"). See §5.4.
+ 73 - **Apps with a local SQLite database.** They stay single-writer with a
+ 74 lease, as today.
+ 75 - **Moving websockets gently between copies.** A dropped websocket
+ 76 reconnects (§5.6).
+ 77 - **More than one region per app.**
+ 78
+ 79 ## 4. Anti-goals: failures even if it technically works
+ 80
+ 81 - **Two copies on one box.** It looks like high availability without being
+ 82 it (Paul, 2026-10-24). A copy count must always mean "survives that many
+ 83 boxes minus one".
+ 84 - **Two copies of an app that keeps a local database.** Each would get its
+ 85 own SQLite file and they would quietly diverge.
+ 86 - **A release command running twice at once,** or a copy serving a new
+ 87 build before its release command succeeded.
+ 88 - **A copy reported or routed as up when its box is down,** or a hub that
+ 89 keeps sending a share of requests into a dead box.
+ 90 - **New per-box polling of the bucket.** S3 requests cost money (about $3
+ 91 per app per month from box polling today). Ride existing reads and
+ 92 reports; don't add a poll per copy.
+ 93
+ 94 ## 5. What Paul decided
+ 95
+ 96 ### 5.1 Where it runs first
+ 97
+ 98 On a fleet, starting with the two-box fleet in §1. Rootfs apps already run
+ 99 on fleets, so that deployment needs no single-tenant setting for this. The
+ 100 console's managed-fleets machinery (1b: box choice, assignment, drain,
+ 101 relabel on box loss) is the base for placement.
+ 102
+ 103 ### 5.2 The number of copies is set per app
+ 104
+ 105 - `carlos apps set shop --copies 2`. The default is 1, which is today's
+ 106 behaviour, so nothing changes until an app opts in.
+ 107 - Never more copies than the fleet has boxes able to run them. A larger
+ 108 number is refused when it is set.
+ 109 - When a box is lost, the app runs short ("1 of 2 copies running") until
+ 110 the box is back or replaced. It never puts two copies on one box to make
+ 111 up the number.
+ 112 - An app may go above 1 only if its serving release declares that it
+ 113 keeps no local database (§6.1).
+ 114
+ 115 ### 5.3 Release runs once per deploy
+ 116
+ 117 Like the Kubernetes release hook it replaces:
+ 118 - It runs once, on one box, from the new build, before any copy switches
+ 119 to that build.
+ 120 - If it fails, the deploy stops and every copy keeps serving the old
+ 121 build.
+ 122 - After it succeeds, the copies switch one box at a time, each with the
+ 123 overlap swap an instance gets today. For a short time old and new code
+ 124 serve side by side, which the app's migrations must already allow (they
+ 125 do on Kubernetes).
+ 126
+ 127 ### 5.4 One copy per box, and a copy may grow to fit its box
+ 128
+ 129 Today an instance gets at most `xlarge` (2 GiB), and a size above
+ 130 `standard` is refused when it is more than a quarter of the smallest box's
+ 131 memory. On a fleet the customer owns, a copy may be sized up to most of its
+ 132 box, so one copy (more Puma workers, more Sidekiq threads) uses the
+ 133 hardware. Paul chose this over packing several copies onto one box (option
+ 134 1 of two, 2026-11-01): one Rails boot, preloaded workers sharing memory, one
+ 135 database pool per box, and copies keep meaning boxes.
+ 136
+ 137 ### 5.5 Workers run on every copy
+ 138
+ 139 Every copy runs the app's declared workers. Sidekiq Enterprise's leader
+ 140 election keeps periodic jobs firing once. The platform does not pick a
+ 141 worker box.
+ 142
+ 143 ### 5.6 Websockets drop and reconnect
+ 144
+ 145 When a box dies or a copy switches during a deploy, its websockets drop.
+ 146 The Action Cable client reconnects and lands on another copy within
+ 147 seconds. Paul: "Seems fine." Broadcasts reach every copy through the app's
+ 148 Redis adapter; that is the app's concern, not the platform's.
+ 149
+ 150 ### 5.7 The drill that says it's done
+ 151
+ 152 On the first user's two-box fleet (or a dev fleet built the same way),
+ 153 under steady traffic to a replicated Rails app:
+ 154
+ 155 1. **Spread.** Both boxes serve close to half the requests, measured at the
+ 156 hub and in each box's own request records.
+ 157 2. **A box dies.** Stop one box's machine outright, not a graceful drain.
+ 158 Reads don't fail. The app shows "1 of 2 copies". Workers keep running on
+ 159 the survivor. Websockets reconnect within seconds.
+ 160 3. **The box returns.** Traffic spreads evenly again with nobody touching
+ 161 anything.
+ 162 4. **A deploy under load.**
+ 163 - The release command runs exactly once.
+ 164 - The copies switch one at a time with no failed requests.
+ 165 - A failing release leaves every copy on the old build.
+ 166
+ 167 ## 6. How it works
+ 168
+ 169 Decided above, or the author's calls (marked). The builder settles the rest
+ 170 (§8).
+ 171
+ 172 ### 6.1 Declaring "no local database"
+ 173
+ 174 A release declares that the app keeps no state on its box. Author's call:
+ 175 it lives in the release manifest, set at ship time (for rootfs apps beside
+ 176 the processes file, for example `carlos ship --stateless`), so it travels
+ 177 with the build. The builder names the flag and field.
+ 178
+ 179 A release that declares it:
+ 180 - gets no SQLite database, no `CARLOS_DB`, no placeholder file, no restore,
+ 181 and no Litestream;
+ 182 - takes no serving lease.
+ 183
+ 184 Binary apps that keep all their state in S3 with compare-and-swap use the
+ 185 same declaration (author's call). The drill covers Rails only.
+ 186
+ 187 Every place that relies on the lease today needs an answer for these
+ 188 apps. The recon found these:
+ 189 - a wake's lease, restore and replicate (`internal/activator/activator.go`
+ 190 doWake);
+ 191 - the rootfs replica-missing refusal (`rootfs_service.go`) and the
+ 192 placeholder database (`rootfsdb.go`);
+ 193 - the release command and workers, which run under the lease and stop when
+ 194 it is lost (`rootfsrelease.go`, `rootfsworkers.go`);
+ 195 - secret escrow and instance-key minting (Durability 3a, #477,
+ 196 `errEscrowNoLease`);
+ 197 - fleet bindings, which the lease winner writes.
+ 198
+ 199 Author's call: one-writer work that is not serving keeps a lease of its own,
+ 200 a *coordinator* lease per app instance with no Litestream behind it. These
+ 201 are the release command, escrow and key minting, and binding writes. One
+ 202 copy holds it at a time; serving never waits on it.
+ 203
+ 204 ### 6.2 One instance, several boxes
+ 205
+ 206 Author's call: a replicated app keeps one instance record (one host), and
+ 207 its fleet assignment becomes a set of boxes instead of one. Today 1b writes
+ 208 one `FleetBox` per record. Placement:
+ 209 - picks N distinct, ready, non-draining boxes;
+ 210 - uses 1b's box checks (freshness, label floor, rootfs-ready);
+ 211 - moves a lost or draining box's copy to a spare box when the fleet has
+ 212 one, or leaves the app running short.
+ 213
+ 214 Only the boxes in the set run a copy. The start rule for labelled rows
+ 215 (`startrule.go`) does not apply to stateless rows, which have no local copy
+ 216 to set aside.
+ 217
+ 218 ### 6.3 The hub spreads requests and skips a dead copy
+ 219
+ 220 Today the hub forwards a fleet app's host down one box's tunnel channel
+ 221 (`fleetChannelFor`, `internal/edge/edge.go`). An unlabelled route falls back
+ 222 to another connected fleet box. A labelled route (managed fleets 1b, which a
+ 223 multi-box fleet uses) is bound to its box, and a dead box gives 503 with no
+ 224 failover. For a replicated app the hub:
+ 225 - holds the set of copies that are up;
+ 226 - sends each request to one of them, round-robin;
+ 227 - drops a copy from the set within seconds of its tunnel closing or its
+ 228 health check failing, and adds it back once it passes again.
+ 229
+ 230 The health check is the one a single instance already has: web answers
+ 231 `GET /` with a status below 500. The edge's multi-upstream routes
+ 232 (`internal/edge/prober.go`, `multiProxy`) already do probing, round-robin,
+ 233 ejection and retry for fixed addresses. They are the starting point;
+ 234 they are not wired to platform instances today.
+ 235
+ 236 Retries (author's call, which Paul did not object to): a request is retried
+ 237 on another copy only when that is safe. That means GET and HEAD, or a
+ 238 request that never reached the app (the tunnel or dial failed first). Any
+ 239 other request caught on a dying box returns an error rather than risking
+ 240 running twice.
+ 241
+ 242 ### 6.4 Deploys
+ 243
+ 244 1. The coordinator copy (§6.1) runs the release command from the new build
+ 245 (§5.3).
+ 246 2. On success, each box switches its copy with the existing overlap swap,
+ 247 one box at a time. The next box starts only once the previous copy is
+ 248 healthy on the new build.
+ 249 3. On a failed release, nothing switches.
+ 250
+ 251 Workers follow each copy's swap as they do today (Plan 3 Group W). A deploy
+ 252 with one copy left (the other box lost) switches that copy alone.
+ 253
+ 254 ### 6.5 Seeing it
+ 255
+ 256 - `carlos instances list` shows one line per copy: its box, build, state
+ 257 and health.
+ 258 - The app shows "2 of 2 copies running", or "1 of 2" while short. This is
+ 259 copy; it goes through Paul's copy review.
+ 260 - Logs and metrics carry the box (`carlos logs` already tags rootfs lines
+ 261 with the process), so copies can be told apart.
+ 262 - `carlos run` and interactive sessions open on one copy: a healthy one the
+ 263 platform picks, or the one named with a flag (author's call).
+ 264
+ 265 ### 6.6 Edge cases (author's calls after the builder check)
+ 266
+ 267 - **A release whose result is unknown.** Say the coordinator's box dies
+ 268 while the release command runs. The command may have committed
+ 269 migrations before its success was recorded. The unknown result counts as
+ 270 a failure, so the deploy stops and every copy keeps the old build. Running
+ 271 the deploy again runs the command again. Release commands must therefore
+ 272 be safe to run twice, as Rails migrations are (schema_migrations). The
+ 273 docs say so. Nothing asks an operator to step in.
+ 274 - **What "reads don't fail" promises.** A read is retried on another copy
+ 275 when the box died before it started answering. A response already
+ 276 streaming to the client when its box dies is cut, because the hub cannot
+ 277 restart it elsewhere without buffering every response, which this design
+ 278 does not do. The drill measures failures among requests the dying box had
+ 279 not started answering. Those must be zero. A cut mid-stream response is
+ 280 counted and reported, not failed.
+ 281 - **Apps with several instance records.** `--copies` is set on the app and
+ 282 applies to each of its instances. Each instance has its own copies, its
+ 283 own coordinator lease and its own release run: "once per deploy" means
+ 284 once per instance per build, as a single instance's release runs today.
+ 285 Two instances of one app sharing a database is the app's concern, as it
+ 286 is today.
+ 287 - **Moving between stateful and stateless releases.** It is refused rather
+ 288 than converted. While an app has more than one copy, promoting, deploying
+ 289 or rolling back to a release that does not declare "no local database"
+ 290 is refused, with a message saying to set `--copies 1` first. An app going
+ 291 from a local database to stateless keeps its old database file and
+ 292 replica untouched. They are simply no longer used.
+ 293 - **Hibernation.** More than one copy requires an always-on release. A
+ 294 release shipped with `--hibernate` is refused while copies are above 1,
+ 295 and setting copies above 1 on a hibernating app is refused. Health checks
+ 296 never wake anything.
+ 297
+ 298 ## 7. Constraints
+ 299
+ 300 - **Copy:** every user-facing string goes through Paul's copy review before
+ 301 it ships, with no em dashes.
+ 302 - **Census:** any change to the root binary needs the census
+ 303 (`make census-card`, an independent reviewer, recorded on #280).
+ 304 - **Provider-neutral core:** nothing here may assume AWS outside an
+ 305 adapter.
+ 306 - **Requests:** no new per-box or per-copy bucket polling (§4).
+ 307 - **Releases:** a release floor in the manner of 1b's label floor
+ 308 (`FleetBoxLabelFloor`). Copies above 1 are refused until every box in
+ 309 the fleet and the console run a release that understands them, so an
+ 310 old box is never handed a copy it can't run.
+ 311 - **Order:** dev first, on a two-box dev fleet, then the first user's
+ 312 fleet, which is a deployment its operator rolls.
+ 313 - **Coordination:** region HA (the session doing HA planning) and managed
+ 314 fleets phase 2 both touch placement and health. Agree who owns the
+ 315 shared pieces (box choice, health answers, forwarding) before the plan,
+ 316 so they are built once.
+ 317
+ 318 ## 8. Left to the builder
+ 319
+ 320 - Names: the flag, the manifest field, the record field for the box set,
+ 321 and how the coordinator lease is keyed.
+ 322 - Where the hub's copy set lives, and how it learns a copy's health
+ 323 (active probes over the tunnel, the boxes' existing status reports, or
+ 324 both), within §4's request rule.
+ 325 - How fast "within seconds" is, as long as the drill passes. Pick concrete
+ 326 probe intervals and fail and rise counts.
+ 327 - How the console marks "release done for build X" so the boxes switch
+ 328 after it, and how a box that was down during a deploy catches up.
+ 329 - The size limits on fleets (§5.4): which tiers or rules, and the headroom
+ 330 left for the box itself.
+ 331 - Whether `--copies` is refused or clamped when a box is detached, and
+ 332 exactly what the short-running state looks like in the console (copy
+ 333 review).
+ 334 - How the drill measures "close to half" (a sensible tolerance).
+ 335
+ 336 ## 9. Later phases (order is the author's suggestion)
+ 337
+ 338 1. This design on fleets (the first user, then any fleet).
+ 339 2. Hub redundancy, so a dead hub is survivable.
+ 340 3. Autoscaling of copies between a minimum and a maximum across existing
+ 341 boxes, then launching and retiring machines (with managed fleets phase 2
+ 342 and region HA's G5).
+ 343 4. Carloku's shared regions, with plans, caps and billing counting copies.
+
+exec
+/bin/bash -lc 'git status --short; git rev-parse HEAD; git show d526ab09:docs/superpowers/reviews/CODEX-REVIEW-BRIEF-STATELESS-REPLICAS-SCALE.md' in /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-stateless-replicas-scale
+ succeeded in 0ms:
+d526ab0951955742855e7a24342c5d5c1441492b
+# Review brief: stateless replicas at production scale design (#892), round 1 of 3
+
+Repo carlos/platform, branch `design-stateless-replicas-scale`, commit 8bfc752b.
+Under review: `docs/superpowers/specs/2026-11-11-stateless-replicas-production-scale-design.md`.
+Authorities (merged on main): `docs/superpowers/specs/2026-11-01-stateless-replicas-design.md`
+("11-01"), `docs/superpowers/specs/2026-10-24-rootfs-apps-design.md`, `docs/site/rootfs.md`,
+and the code on this branch (which is main 01d6ca78).
+
+S2 and S3 name #511 Plan 4 (`stateless-replicas-4`, unmerged) as where they will
+be built later. Do not review Plan 4 or its branch. Review S2 and S3 only for
+consistency with the merged 11-01 design and today's code; their plans are written
+after Plan 4 merges.
+
+You are an independent reviewer. Read the document, then the code it names, and
+check every claim against that code.
+
+## Fixed: do not re-argue
+
+- 11-01 §5 (Paul's decisions): one copy per box, a copy may grow to fit its box,
+ workers on every copy, release once per deploy, websockets drop and reconnect.
+- Paul asked for #892 to be done without a live brainstorm; the author's calls are
+ listed in §9 for him. Report a call only if it is unsafe or contradicts a merged
+ authority, not because another call is possible.
+
+## What to check
+
+1. §2's rejection of worker-only instances: does 11-01 §6.6 (and the code) really
+ run the release command once per instance, so two instances of one app run it
+ twice per build?
+2. S1 (`CARLOS_MEMORY_MIB`): can the agent set it on every rootfs launch path from a
+ limit it already computes, with no new reads? Check `internal/activator/rootfs.go`
+ `spawnRootfs` (its `tier`), `rootfsenv.go` (workers inherit web's launch env;
+ release, run and TTY env), `backend_rootfs.go`, and the agent-owned name lists
+ (`agentOwnedNames`, `rootfsOwnedNames`, `moves.AgentOwnedVars` and its pin test).
+ Name any reader that would break or any path where the figure would be wrong
+ (for example a run or session whose unit has a different limit than the instance,
+ or a worker started after a size change against web's older launch env).
+3. S3 (drain swap): is "drain when copies > 1 and the size is a fleet size, never
+ drain a copy with no other copy serving" coherent with 11-01 §6.3-§6.4 and the
+ hub routing on main (`internal/edge`, Plan 3)? Is there a case where a box drains
+ the last serving copy, or where the hub keeps sending to a draining copy?
+4. §3's arithmetic and the 27.3 GiB budget figure.
+5. Anything in the design that contradicts a merged spec or today's code.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+ Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the section, the problem, the evidence
+(file:line, verified), the failure scenario, a concrete fix and the invariant or
+trust boundary it breaks (that is its fault family). End with exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites. Keep to the five checks above.
+
+exec
+/bin/bash -lc 'nl -ba internal/activator/rootfsenv.go' in /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-stateless-replicas-scale
+ succeeded in 0ms:
+ 1 // rootfsenv.go is the environment contract of a rootfs row's commands
+ 2 // (rootfs apps Plan 3, D1). The web process's half is spawnRootfs's:
+ 3 // rootfsVars over agentOwnedVars, with the generation's own socket. A
+ 4 // rootfs process has no argv of the agent's, so its socket and database
+ 5 // reach it as environment (rootfsVars), set after the file environment so
+ 6 // a tenant's file cannot point either elsewhere. A launch file built from
+ 7 // these variables goes through rootfsLaunchEnv, never childEnv, which
+ 8 // starts from the agent's own environment (INV-5). Binary rows never come
+ 9 // here: their argv carries --socket and --db. The environment is never
+ 10 // logged.
+ 11 package activator
+ 12
+ 13 import "github.com/carlosframework/platform/internal/registry"
+ 14
+ 15 // rootfsCmdVars is a carlos run's environment on a rootfs row: cmdVars over
+ 16 // fileEnv, the file environment the run's generation launched with (no
+ 17 // control or purge channel; CARLOS_HOST, CARLOS_REGION, CARLOS_DB and the
+ 18 // run's id and directory set), then rootfsVars with the row's canonical
+ 19 // socket and dbPath.
+ 20 func (b *ExecBackend) rootfsCmdVars(rt registry.Route, fileEnv map[string]string, dbPath, runID, runDir string) map[string]string {
+ 21 return storageVars(rt, rootfsVars(b.cmdVars(rt, fileEnv, dbPath, runID, runDir), rt.Socket, dbPath))
+ 22 }
+ 23
+ 24 // rootfsTTYVars is a session's environment on a rootfs row (Plan 6 Task
+ 25 // 8): ttyVars over fileEnv, the file environment the session's generation
+ 26 // launched with (no run id or directory; TERM and CARLOS_SESSION_ID set),
+ 27 // then rootfsVars with the row's canonical socket and dbPath.
+ 28 func (b *ExecBackend) rootfsTTYVars(rt registry.Route, fileEnv map[string]string, dbPath, sessionID, term string) map[string]string {
+ 29 return storageVars(rt, rootfsVars(b.ttyVars(rt, fileEnv, dbPath, sessionID, term), rt.Socket, dbPath))
+ 30 }
+ 31
+ 32 // rootfsReleaseVars is a release command's environment on a rootfs row
+ 33 // (Group R, D1): rootfsCmdVars over fileEnv, the environment the run role
+ 34 // would launch with now (ReleaseEnv), without a run's id or directory: a
+ 35 // release is no carlos run. The row's canonical socket and dbPath are set
+ 36 // after the file environment, as for a run.
+ 37 func (b *ExecBackend) rootfsReleaseVars(rt registry.Route, fileEnv map[string]string, dbPath string) map[string]string {
+ 38 return withoutVars(b.rootfsCmdVars(rt, fileEnv, dbPath, "", ""), "CARLOS_RUN_ID", "CARLOS_RUN_DIR")
+ 39 }
+ 40
+ 41 // rootfsWorkerVars is a rootfs worker's environment (Group W, D1): the
+ 42 // file environment genEnv its web generation g launched with (that
+ 43 // handle's LaunchEnv), the agent-owned variables as web got them, with
+ 44 // g's control socket only when web's listener bound (haveControl), then
+ 45 // rootfsVars with the row's canonical socket and dbPath. So a worker's
+ 46 // launch file is web's, CARLOS_SOCKET aside: a worker serves nothing, and
+ 47 // names the instance's socket, never a generation's.
+ 48 func (b *ExecBackend) rootfsWorkerVars(rt registry.Route, g Gen, dbPath string, genEnv map[string]string, haveControl bool) map[string]string {
+ 49 rt.Stateless = g.Stateless
+ 50 return storageVars(rt, rootfsVars(b.agentOwnedVars(rt, g.Control, genEnv, haveControl), rt.Socket, dbPath))
+ 51 }
+
+exec
+/bin/bash -lc "rg -n 'drain|health|probe|eligible|fallback' internal/edge/fleet*; rg -n 'memory|limit|release|worker' docs/site/rootfs.md docs/superpowers/specs/2026-10-24-rootfs-apps-design.md" in /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-stateless-replicas-scale
+ succeeded in 0ms:
+internal/edge/fleetverdict_test.go:183: t.Cleanup(e.probers.Stop)
+internal/edge/fleetforward_test.go:43:// forwardRow is an eligible forward row's declared fields for host on fleet.
+internal/edge/fleetforward_test.go:84: t.Cleanup(hub.probers.Stop)
+internal/edge/fleetforward_test.go:121: t.Cleanup(box.probers.Stop)
+internal/edge/fleetforward_test.go:256: {"forward: eligible", fwd(nil), true, owners, true, false},
+internal/edge/fleetforward_test.go:312: t.Error("Allowed(a) = false, want true (eligible forward row)")
+internal/edge/fleetforward_test.go:738:// host and answers cacheably, holding the eligible targets good (an
+internal/edge/fleetforward_test.go:740:// eligible forward row), and the refused rows bad (a forward row of an
+internal/edge/fleetforward_test.go:780:// attached hostname of the SAME name targets an eligible route. The alias
+internal/edge/fleetforward_test.go:783:// it down the eligible route's tunnel (and through its cacheable answer).
+internal/edge/fleetforward.go:43:// - A forward row placed on a link (registry.LinkPlacement) is eligible
+internal/edge/fleetforward.go:48:// - A forward row is eligible only on the hub, only inert (every
+internal/edge/fleetforward.go:61:// - Any other row is not this rule's business: eligible, nothing to log.
+internal/edge/fleetforward.go:190: ArmReplica // a validated set, through healthy assigned copies
+internal/edge/fleet_route_test.go:3:// Task 4: edge fleet-route dispatch — the 1-2-3 binding/fallback/dark rule
+internal/edge/fleet_route_test.go:12:// The bound/fallback cases need REAL h2 channels (a fake conn can't answer a
+internal/edge/fleet_route_test.go:90:// connected the fallback rule (rule 2) would ALSO pick "acme/pi-1" — binding
+internal/edge/fleet_route_test.go:94:// can produce "pi-2" here — the fallback alone would answer "pi-1".
+internal/edge/fleet_route_test.go:109: t.Fatalf("got %d %q, want 200 %q (the bound box, which sorts LAST — a fallback-only implementation would answer pi-1 instead)", code, body, "pi-2")
+internal/edge/fleet_route_test.go:156:// skip straight to the fallback rule rather than erroring on an empty bound
+internal/edge/fleet_route_test.go:330: t.Cleanup(e.probers.Stop)
+internal/edge/fleet_route_test.go:353:// and a fallback there would start a second copy.
+internal/edge/fleet_route_test.go:365: t.Fatalf("got %d, want 503 (no fallback to pi-1 for a labelled row)", resp.StatusCode)
+internal/edge/fleet_route_test.go:388: t.Fatalf("got %d %q, want 200 pi-1 (fallback for an unlabelled row)", code, body)
+internal/edge/fleet_route_test.go:394:// fallback.
+internal/edge/fleet_e2e_test.go:256:// disturb the very session whose survival this test also asserts. A probe
+internal/edge/fleet_e2e_test.go:263: t.Fatalf("build probe: %v", err)
+internal/edge/fleet_e2e_test.go:270: t.Fatalf("probe %s: %v", name, err)
+internal/edge/fleet_e2e_test.go:289: t.Fatalf("register probe for %s answered %d, want %d within %s", name, last, want, within)
+internal/edge/fleet_e2e_test.go:300:// Box naming is load-bearing. The fallback rule (rule 2) picks
+internal/edge/fleet_e2e_test.go:302:// fallback-only implementation would always answer:
+internal/edge/fleet_e2e_test.go:394: t.Fatalf("(a) got %d %q, want 200 %q — the BOUND box, which sorts last; a fallback-only edge would answer box-a", code, body, "box-b")
+internal/edge/fleet_e2e_test.go:422: // over to the healthy survivor. That window IS the venue-Wi-Fi failure
+internal/edge/fleet_e2e_test.go:451: t.Fatalf("(b) after the bound box went dark: got %d %q, want 200 %q (the fallback rule)", code, body, "box-a")
+internal/edge/fleet_e2e_test.go:538: // Baseline first, so the probe's two answers are known to be
+internal/edge/fleet_e2e_test.go:542: t.Fatalf("(d) probe baseline = %d, want 400 (credential accepted, wire contract refused)", code)
+internal/edge/fleet_e2e_test.go:555: t.Fatalf("(d) probe with the rotated token = %d, want 400 (the new credential must authorize)", code)
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:7:deploy overlap. Marked **(B1-n)**. Rev 3 adds the `release` process
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:48: same memory tiers, the same egress fence.
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:50: serves requests, and worker processes (Solid Queue, Sidekiq, a queue
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:165: (`linux-arm64`) or `site.tar.gz` (`internal/release/release.go:80`).
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:179:A release may carry a **rootfs artifact** instead of, or beside, a
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:182:declaration** in the manifest naming the web command and any worker
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:189:environment variables, not flags. Declared workers run as co-spawned
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:199:- **Rootfs is a property of the app, fixed by its first release.** A
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:200: release whose kind (binary or rootfs) differs from the app's is refused
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:205: manifest of the release it is created with: always-on unless that
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:206: manifest opts in. A later release that asks for the other setting is
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:211: release happens to be staged.
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:228: not match `adoptPlatform`'s `GOOS-GOARCH` lookup on a release that
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:229: predates this feature, and a release carrying only a rootfs artifact
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:231: skips a release today. The builder picks the key; the test is that a
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:232: previous release's adopt pass, run against a rootfs-only manifest,
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:254: "worker": {"command": ["bin/jobs"]},
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:255: "release": {"command": ["bin/rails", "db:migrate"]}
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:259:- Exactly one `web`, required. At most one `release` (§5.2.1) and at
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:260: most one `console` (§5.10). Zero or more others, which are workers, names matching a
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:283: in the same order: the old generation's workers stop once the new
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:284: `web` is healthy, then the new workers start. So two worker sets never
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:287: release still serves, exactly as in a rolling Kubernetes deploy. Making
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:290:### 5.2.1 The `release` process: migrations on deploy
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:292:The equivalent of a Helm pre-upgrade hook or Heroku's release phase.
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:294:- The activator runs `release` during an instance's swap to a new
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:300:- **Exit 0:** the new `web` starts, then workers are handed over (§5.2).
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:308: - `overlap` (default): `release` runs while the old version still
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:311: - `hold`: stop the old version, run `release`, start the new one. Safe
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:316: run-once Job. A run-once-per-release scope for many copies sharing one
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:320:- **A hibernating instance** runs `release` at its next wake, before it
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:322:- **Rollback** of a release does not roll back the schema, as on
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:325: `release` runs on every deploy, including the first, after the seed.
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:361: only `<host>-sidecar.env` and no database path; rootfs workers get
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:364: first. With an always-on instance (§5.6) that means workers run all
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:366:- Several workers per instance are allowed. The builder bounds the
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:367: count (my call: 4) and defines what one crashing worker does to its
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:368: siblings and to `web`. My call: a crashed worker is restarted with
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:384: output about a second behind). The `release` process (§5.2.1) uses the
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:422:- **Version floor.** A box running a release without rootfs support
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:473:- the default memory tier as the memory limit;
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:475:- each worker process started and seen alive after a few seconds;
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:477: writing outside the instance directory, running out of memory, an
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:547: and the JVM write machine code into memory and then make it
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:551:- **Declaration.** The release manifest carries `"jit": true` (rootfs
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:552: releases only; refused on binary releases in v1). It is per release:
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:553: changing it between releases is an ordinary deploy, because nothing
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:555:- **Effect.** Every process of that release (web, workers, release,
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:561: the release it is starting, never from tenant config or the record.
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:565: effective `MemoryDenyWriteExecute` matches the release's `jit` value,
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:577: `carlos store`, one `web` and one `worker` process. Proves §5.1 to
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:585: declared worker, existing uploads through env keys, several copies on
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:586: several boxes, `release` run once per release (§5.2.1), and
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:594:- A job enqueued by a request and run by the worker.
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:597:- A crash of the worker and of `web`, each recovered without a visitor.
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:608:- C5. Every rootfs process (web, workers, seed, run) is inside the
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:612:- C8. A failed or timed-out `release` never lets the new `web` serve,
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:617:- C10. Only a release that declares `jit` runs without
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:630:- Adopt: a previous release's adopt pass against a rootfs-only manifest
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:648: paths, memory tiers, no JIT.
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:670:- Kind and hibernation fixed at creation; kind-changing releases refused
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:675:- Deploys overlap as today; workers are handed over after the new `web`
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:678:- Upload cap of 2 GiB for the rootfs part; worker cap of 4 per instance.
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:683:- `release` timeout 10 minutes by default (§5.2.1).
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:694: move, Paul 2026-10-24). It must also define `release`'s run-once
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:701: (clustered Puma, workers sized to the box's vCPUs), and a second copy of
+docs/superpowers/specs/2026-10-24-rootfs-apps-design.md:702: the same app on the same box adds a Rails boot and memory but no
+docs/site/rootfs.md:11:An app's first release makes it a binary app or a rootfs app, and it stays that kind. A release of the other kind is refused when you ship it. To change kinds, create a new app.
+docs/site/rootfs.md:13:Each instance takes its hibernation setting from the release it is created with, and keeps it. A rootfs app is always on unless that release was shipped with carlos ship --hibernate. A later release that asks for the other setting is refused when you ship it.
+docs/site/rootfs.md:22: "worker": {"command": ["/rails/bin/jobs"]},
+docs/site/rootfs.md:23: "release": {"command": ["/rails/bin/rails", "db:migrate"]},
+docs/site/rootfs.md:30:- release is optional, at most one. It runs on every deploy, the first included, before the new web starts. It may run for ten minutes unless it sets timeout_sec.
+docs/site/rootfs.md:34:- Any other name is a worker, up to four of them. A name is lowercase letters, digits and hyphens, starts with a letter, and is at most 16 characters long.
+docs/site/rootfs.md:40:Every process of the instance gets the same environment: web, the workers and release alike. That is the app's config bundle, the instance's own variables and secrets, its store's coordinates, and these:
+docs/site/rootfs.md:52:web must answer GET / on CARLOS_SOCKET with a status below 500 within 120 seconds of starting. Until it does, the instance does not serve and its workers do not start.
+docs/site/rootfs.md:56:The image is the instance's root filesystem, and it is read-only. An instance writes in two places: the directory CARLOS_DB is in, which is kept across restarts and deploys, and /tmp, which is empty at every start. /tmp is held in memory, so what is in it counts against the instance's memory.
+docs/site/rootfs.md:60:All of an instance's processes share one memory and CPU limit, the same tiers a binary instance gets, 1 GB by default. A process that goes over it is stopped and started again.
+docs/site/rootfs.md:64:Memory is never writable and executable at once, unless the release is shipped with carlos ship --jit. A JIT compiler needs that: Node, Bun and Deno, the JVM, Ruby's YJIT and PHP's opcache JIT. Ruby, PHP and Python run well without one.
+docs/site/rootfs.md:66:A release shipped with --jit has jit set in its manifest, and every process of its instances runs with that protection off: web, the workers and release. Nothing else about the instance changes. The setting belongs to the release, so a later release can turn it on or off.
+docs/site/rootfs.md:70:carlos ship --check warns when a process runs Node, Bun or Deno and the release is not shipped with --jit, because the check passes on your machine and the box then stops the process at start.
+docs/site/rootfs.md:96:carlos ship fills in console when a release declares none: bin/rails console for Rails, php artisan tinker for Laravel and python manage.py shell for Django. Any other app declares its own in processes.json.
+docs/site/rootfs.md:98:A session can read and change everything the instance can. It ends after 30 minutes without a keystroke, and a deploy or a restart ends it too. [carlos run](/docs/cli#carlos-run) has the limits, the exit statuses and how to run commands from CI.
+
+exec
+/bin/bash -lc "rg -n 'tier|Memory|Env|Limit' internal/activator/rootfs.go internal/activator/backend_rootfs.go; rg -n 'agentOwnedNames|rootfsOwnedNames|AgentOwnedVars' internal" in /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-stateless-replicas-scale
+ succeeded in 0ms:
+internal/activator/backend_rootfs.go:105: // ReleaseEnv is the environment a release of rt launches with [pf
+internal/activator/backend_rootfs.go:109: ReleaseEnv(ctx context.Context, rt registry.Route) (map[string]string, error)
+internal/activator/backend_rootfs.go:131:// ReleaseEnv implements ReleaseBackend [pf R1.3]. It takes the three
+internal/activator/backend_rootfs.go:137:func (b *ExecBackend) ReleaseEnv(ctx context.Context, rt registry.Route) (map[string]string, error) {
+internal/activator/backend_rootfs.go:163: env, layer, err := b.launchEnvLayer(hctx, rt)
+internal/activator/backend_rootfs.go:220:// for role with env alone (rootfsLaunchEnv, never the agent's own
+internal/activator/backend_rootfs.go:223:// TTYRootfs at the row's tier naming the image with l's process or argv.
+internal/activator/backend_rootfs.go:271: if err := b.writeRootfsLaunchFor(p, role, 0, rt.Host, process, rootfsLaunchEnv(env)); err != nil {
+internal/activator/backend_rootfs.go:282: memMax := b.tier(rt).MemoryMax
+internal/activator/backend_rootfs.go:316:// launched with is required (errNoGenEnv), and the replica gate is asked
+internal/activator/backend_rootfs.go:332: if spec.genEnv == nil {
+internal/activator/backend_rootfs.go:333: return nil, fmt.Errorf("%s: %w", rt.Host, errNoGenEnv)
+internal/activator/backend_rootfs.go:337: if err := b.replicaKeyGate(rt, spec.genEnv, spec.genKeyLayer, false); err != nil {
+internal/activator/backend_rootfs.go:342: env := b.rootfsTTYVars(rt, spec.genEnv, dbPath, spec.RunID, spec.TTY.Term)
+internal/activator/backend_rootfs.go:345: env := b.rootfsCmdVars(rt, spec.genEnv, dbPath, spec.RunID, spec.RunDir)
+internal/activator/backend_rootfs.go:496:// rootfsLaunchEnv); the caller's exec gate, the last thing before root is
+internal/activator/backend_rootfs.go:513: var genEnv map[string]string
+internal/activator/backend_rootfs.go:514: if le, ok := web.(launchEnvProc); ok {
+internal/activator/backend_rootfs.go:515: genEnv = le.LaunchEnv()
+internal/activator/backend_rootfs.go:517: if genEnv == nil {
+internal/activator/backend_rootfs.go:552: env := rootfsLaunchEnv(b.rootfsWorkerVars(rt, g, p.dbPath, genEnv, haveControl))
+internal/activator/backend_rootfs.go:562: inv, err := rc.StartRootfsWorker(ctx, rt.Host, name, g.Tier.MemoryMax, img)
+internal/activator/backend_rootfs.go:584: log.Printf("activator: %s: started %s (worker %s of build %s) memory.max=%d", rt.Host, unit, name, id.Version, g.Tier.MemoryMax)
+internal/activator/rootfs.go:42:// rootfsTier is a rootfs row's memory tier (R9, deviation 9): tier and
+internal/activator/rootfs.go:44:// It is the base tier, which #328's operator sizes wrap (SizedLimit(rt,
+internal/activator/rootfs.go:46:// (ExecBackend.tier).
+internal/activator/rootfs.go:87:// rootfsLaunchEnv is a rootfs launch file's environment: vars alone, one
+internal/activator/rootfs.go:88:// entry per name, sorted. Unlike childEnv it inherits nothing from the
+internal/activator/rootfs.go:92:// MergeRootfsEnv). A tenant that sets PATH in its own files means to.
+internal/activator/rootfs.go:93:func rootfsLaunchEnv(vars map[string]string) []string {
+internal/activator/rootfs.go:261: if g.Tier == (cgroup.Limit{}) {
+internal/activator/rootfs.go:269: // larger tier while a shrink waits for a cold start): root is asked
+internal/activator/rootfs.go:288: up, ver, err := b.spawnRootfs(ctx, rt, sock, n, id, cgroup.Limit{})
+internal/activator/rootfs.go:328:// tier is the limit root is asked for; a zero tier means GenTier's, so a
+internal/activator/rootfs.go:331:func (b *ExecBackend) spawnRootfs(ctx context.Context, rt registry.Route, sock string, n uint64, id release.StagedIdentity, tier cgroup.Limit) (*unitProc, string, error) {
+internal/activator/rootfs.go:349: if tier == (cgroup.Limit{}) {
+internal/activator/rootfs.go:350: tier = b.GenTier(rt, id.Version)
+internal/activator/rootfs.go:354: p, ctl, logs, fileEnv, keyLayer, err := b.prepareKeyedAt(rt, instancectl.RoleRun, sock, gen, &prep)
+internal/activator/rootfs.go:370: childVars := storageVars(rt, rootfsVars(b.agentOwnedVars(rt, sock+".control", fileEnv, ctl != nil), sock, p.dbPath))
+internal/activator/rootfs.go:372: if err := b.writeRootfsLaunchFor(p, instancectl.RoleRun, gen, rt.Host, release.ProcessWeb, rootfsLaunchEnv(childVars)); err != nil {
+internal/activator/rootfs.go:386: inv, err := rc.StartRootfs(ctx, rt.Host, gen, tier.MemoryMax, img)
+internal/activator/rootfs.go:426: log.Printf("activator: %s: started %s memory.max=%d (%s)", rt.Host, unit, tier.MemoryMax, steps.String())
+internal/activator/rootfs.go:434: up.launchEnv, up.launchKeyLayer = maps.Clone(fileEnv), keyLayer
+internal/activator/rootfs.go:438: up.inputs = launchInputs(id.Version, fileEnv)
+internal/moves/envreport_test.go:68: for _, set := range []map[string]bool{AgentOwnedVars, BoxVars, LayoutVars, AdvisoryVars, {RegionVar: true}} {
+internal/moves/envreport_test.go:76: if !AgentOwnedVars[name] {
+internal/moves/envreport_test.go:111: for name := range AgentOwnedVars {
+internal/moves/envreport.go:55: // AgentOwnedVars are the variables the agent sets, overwrites or
+internal/moves/envreport.go:60: // TestAgentOwnedVarsAreMovesBoxOwned (internal/activator) pins this set
+internal/moves/envreport.go:62: AgentOwnedVars = map[string]bool{RegionVar: true, "CARLOS_CONTROL_SOCKET": true, "CARLOS_PURGE": true, "CARLOS_HOST": true}
+internal/moves/envreport.go:72:func BoxOwned(name string) bool { return AgentOwnedVars[name] || BoxVars[name] }
+internal/activator/rootfs.go:76:// rootfsOwnedNames are set by the agent on every rootfs launch, whatever
+internal/activator/rootfs.go:78:var rootfsOwnedNames = []string{"CARLOS_SOCKET", "CARLOS_DB"}
+internal/activator/agentowned_moves_test.go:15:// TestAgentOwnedVarsAreMovesBoxOwned pins moves.AgentOwnedVars against
+internal/activator/agentowned_moves_test.go:28:// to moves.AgentOwnedVars and to the tenant file below by hand.
+internal/activator/agentowned_moves_test.go:29:func TestAgentOwnedVarsAreMovesBoxOwned(t *testing.T) {
+internal/activator/agentowned_moves_test.go:33: for k := range moves.AgentOwnedVars {
+internal/activator/agentowned_moves_test.go:80: if want := slices.Sorted(maps.Keys(moves.AgentOwnedVars)); !slices.Equal(covered, want) {
+internal/activator/agentowned_moves_test.go:81: t.Fatalf("the test covers %v, moves.AgentOwnedVars is %v", covered, want)
+internal/activator/agentowned_moves_test.go:84: if names := slices.Sorted(slices.Values(agentOwnedNames)); !slices.Equal(names, covered) {
+internal/activator/agentowned_moves_test.go:85: t.Fatalf("agentOwnedNames is %v, the agent decides %v", names, covered)
+internal/activator/backend_exec.go:2732:// agentOwnedNames are the variables agentOwnedVars decides: it sets or
+internal/activator/backend_exec.go:2734:// moves.AgentOwnedVars is the same set (TestAgentOwnedVarsAreMovesBoxOwned
+internal/activator/backend_exec.go:2736:var agentOwnedNames = []string{"CARLOS_CONTROL_SOCKET", "CARLOS_PURGE", "CARLOS_REGION", "CARLOS_HOST"}
+internal/activator/backend_exec.go:3324:// the names agentOwnedVars decides (agentOwnedNames), whose running value
+internal/activator/backend_exec.go:3349: for _, k := range agentOwnedNames {
+internal/activator/rootfsenv_test.go:198: for _, k := range rootfsOwnedNames {
+internal/activator/rootfs_test.go:242:// The names rootfsVars owns are rootfsOwnedNames, and a tenant's PATH (its
+internal/activator/rootfs_test.go:254: want := slices.Clone(rootfsOwnedNames)
+internal/appconfig/sync_test.go:1035:func TestLostKeysIgnoresAgentOwnedVars(t *testing.T) {
+internal/host/movesenvskew_test.go:33: if !moves.AgentOwnedVars[k] && !moves.BoxVars[k] {
+internal/provision/testdata/archive/plan14-root-reads-home-part2.tsv:2:# Task 1: moves.CompareEnv takes targetHome, and T3 (internal/host checkEnv) passes rec.Move.To == "" for it: a home target must set no CARLOS_REGION and fails region-present when it does. Task 2b: internal/moves owns the move-portable env rule once: a name is left out of the pin only when it is box-owned (AgentOwnedVars, BoxVars) and the instance's own layers did not supply its running value (Pinned); ReportLaunch and PortableDigest make the v2 report and pin (EnvReportVersion, "env2:sha256:"), and LocalDigest the whole env for a check made on the box that recorded it. The composer reports the instance's layer names (activator ExecBackend.LaunchLayers, LaunchEnvironment's composition moved into its own unit), never a name the agent decides (agentOwnedNames). The moves launch source (claimMoveLaunchSource) makes the env report from that one composition and returns it with the launch; the probe owners take its digest as the launch's pin (movesReadLaunch passes it through) and keep it in memory for Materialize, bound to the exact env. No layer names cross into the claim: ClaimServingLaunch, ClaimLaunchInputs and ClaimLaunchDigest are main's. T3 refuses a v1 source report and the probe owners a v1 pin, fail closed. The recovery records recoveryInputs and checks localEnvDigest, the whole local env.
+
+codex
+The merged design confirms that release runs once per instance per build. I’m checking the launch limits and hub health handling next, where the proposed behavior depends on details beyond the instance settings. I’m using the plain-writing skill for the report.
+exec
+/bin/bash -lc "nl -ba internal/activator/backend_rootfs.go | sed -n '220,350p;490,585p'; nl -ba internal/activator/rootfs.go | sed -n '40,85p;250,280p;328,355p'" in /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-stateless-replicas-scale
+ succeeded in 0ms:
+ 220 // for role with env alone (rootfsLaunchEnv, never the agent's own
+ 221 // environment), naming l's process or "cmd", never an argv; the caller's
+ 222 // exec gate, the last thing before root is asked; then CmdRootfs or
+ 223 // TTYRootfs at the row's tier naming the image with l's process or argv.
+ 224 // Root's answers given before systemctl start are refusals (marked, no
+ 225 // unit): nothing of the build ran. Any other error after the POST hands
+ 226 // back a unit with the error, since the unit may be running and must
+ 227 // still be stopped and settled. The binary path (StartCmd's binary arm)
+ 228 // is a separate function and stays as it is (INV-6).
+ 229 func (b *ExecBackend) startRootfsCmd(ctx context.Context, rt registry.Route, role instancectl.Role, id release.StagedIdentity, l rootfsCmdLaunch, env map[string]string, sinks oneShotSinks) (CmdUnit, error) {
+ 230 if err := b.sandboxLaunch(rt, string(role), 0, true); err != nil {
+ 231 return nil, err
+ 232 }
+ 233 if !rt.Rootfs() {
+ 234 return nil, refuseRootfs(fmt.Errorf("%s: a rootfs command runs only on a rootfs instance", rt.Host))
+ 235 }
+ 236 if (l.Process == "") == (len(l.Argv) == 0) {
+ 237 return nil, refuseRootfs(fmt.Errorf("%s: a rootfs command names a declared process or an argv, exactly one", rt.Host))
+ 238 }
+ 239 if !instancectl.OneShot(role) || (role == instancectl.RoleTTY) != (sinks.TTY != nil) {
+ 240 return nil, refuseRootfs(fmt.Errorf("%s: role %s with a terminal %t is no rootfs one-shot", rt.Host, role, sinks.TTY != nil))
+ 241 }
+ 242 process := l.processName()
+ 243 if err := b.rootfsGates(ctx, rt); err != nil {
+ 244 return nil, err
+ 245 }
+ 246 if id.Version == "" || id.StagedPath == "" || id.Digest == "" {
+ 247 return nil, refuseRootfs(fmt.Errorf("%s: %w (build %q, path %q, digest %q)", rt.Host, errPartialStagedIdentity, id.Version, id.StagedPath, id.Digest))
+ 248 }
+ 249 rc, err := b.rootfsControl()
+ 250 if err != nil {
+ 251 return nil, refuseRootfs(fmt.Errorf("%s: %w", rt.Host, err))
+ 252 }
+ 253 var tc TTYControl
+ 254 if role == instancectl.RoleTTY {
+ 255 if tc, err = b.ttyControl(); err != nil {
+ 256 return nil, refuseRootfs(fmt.Errorf("%s: %w", rt.Host, err))
+ 257 }
+ 258 }
+ 259 p, _, _, _, err := b.prepare(rt, role)
+ 260 if err != nil {
+ 261 return nil, err
+ 262 }
+ 263 ios, err := b.listenOneShot(rt.Host, role, sinks.Stdout, sinks.Stderr, sinks.TTY)
+ 264 if err != nil {
+ 265 return nil, err
+ 266 }
+ 267 fail := func(err error) (CmdUnit, error) {
+ 268 ios.close()
+ 269 return nil, err
+ 270 }
+ 271 if err := b.writeRootfsLaunchFor(p, role, 0, rt.Host, process, rootfsLaunchEnv(env)); err != nil {
+ 272 return fail(err)
+ 273 }
+ 274 // The caller's exec gate (withExecGate), right before root is asked;
+ 275 // runExecGate also writes ctx's pending wake record between two asks
+ 276 // of the gate (runPendingRecord). A refusal is launchRefused: no /cmd
+ 277 // or /tty is sent.
+ 278 if err := runExecGate(ctx); err != nil {
+ 279 return fail(err)
+ 280 }
+ 281 unit := instancectl.RootfsUnitName(role, rt.Host)
+ 282 memMax := b.tier(rt).MemoryMax
+ 283 img := stagedImageOf(id, l.Process, l.Argv)
+ 284 var inv instancectl.StartResponse
+ 285 if tc != nil {
+ 286 inv, err = tc.TTYRootfs(ctx, rt.Host, memMax, img)
+ 287 } else {
+ 288 inv, err = rc.CmdRootfs(ctx, rt.Host, memMax, img)
+ 289 }
+ 290 if err == nil {
+ 291 err = instancectl.ValidateStartIdentity(inv, b.SandboxEffective, rt.Host, role, 0, true, "")
+ 292 }
+ 293 if errors.Is(err, instancectl.ErrStagedImage) || errors.Is(err, instancectl.ErrStartRefused) {
+ 294 // Answered before systemctl start: a refusal, never the build's
+ 295 // failure (INV-4).
+ 296 return fail(refuseRootfs(fmt.Errorf("%s: start %s: %w", rt.Host, process, err)))
+ 297 }
+ 298 if err != nil {
+ 299 // The request may have reached systemd before it failed, so the
+ 300 // unit may be running: a unit with no invocation still stops the
+ 301 // host's rootfs unit of role and waits for its cgroup.
+ 302 log.Printf("activator: %s: start of %s (%s of build %s) failed, it may have begun: %v", rt.Host, unit, process, id.Version, err)
+ 303 return &cmdUnit{b: b, rt: rt, role: role, io: ios}, fmt.Errorf("%s: start %s: %w", rt.Host, process, err)
+ 304 }
+ 305 log.Printf("activator: %s: started %s (%s of build %s) memory.max=%d", rt.Host, unit, process, id.Version, memMax)
+ 306 return &cmdUnit{b: b, rt: rt, role: role, inv: inv.InvocationID, unit: inv.Unit, io: ios}, nil
+ 307 }
+ 308
+ 309 // startRootfsRun is StartCmd's rootfs arm, for a run (carlos run on a
+ 310 // rootfs row, rootfs apps Plan 6 Task 7a) and a session (carlos console,
+ 311 // run -it; Task 8), after StartCmd's layout, run-directory or session
+ 312 // shape checks: the serving generation's image is required (spec.serving,
+ 313 // which RunCmd sets from the generation it admitted the command against),
+ 314 // whole, or the command is refused with nothing laid out (errNoCmdExe, or
+ 315 // errPartialStagedIdentity, both marked); the environment that generation
+ 316 // launched with is required (errNoGenEnv), and the replica gate is asked
+ 317 // as for a binary run; then startRootfsCmd runs, in the cmd unit with the
+ 318 // run's two streams, spec.Args exactly as given, with no live-link prefix
+ 319 // (the image's PATH finds its first word), with rootfsCmdVars over that
+ 320 // environment; or, in the tty unit on the session's pty, spec.Process (the
+ 321 // console) or spec.Args, with rootfsTTYVars. No egress step: #328 checks
+ 322 // in root's rootfs start.
+ 323 func (b *ExecBackend) startRootfsRun(ctx context.Context, rt registry.Route, spec CmdSpec) (CmdUnit, error) {
+ 324 x := spec.serving
+ 325 if x == nil {
+ 326 return nil, refuseRootfs(fmt.Errorf("%s: %w", rt.Host, errNoCmdExe))
+ 327 }
+ 328 id := release.StagedIdentity{Version: x.Version, StagedPath: x.Path, Digest: x.Digest}
+ 329 if id.Version == "" || id.StagedPath == "" || id.Digest == "" {
+ 330 return nil, refuseRootfs(fmt.Errorf("%s: %w (build %q, path %q, digest %q)", rt.Host, errPartialStagedIdentity, id.Version, id.StagedPath, id.Digest))
+ 331 }
+ 332 if spec.genEnv == nil {
+ 333 return nil, fmt.Errorf("%s: %w", rt.Host, errNoGenEnv)
+ 334 }
+ 335 // As a binary run's (StartCmd): on a replica the command starts only
+ 336 // with its home's key, checked before anything is laid out.
+ 337 if err := b.replicaKeyGate(rt, spec.genEnv, spec.genKeyLayer, false); err != nil {
+ 338 return nil, err
+ 339 }
+ 340 dbPath := b.pathsFor(rt).dbPath
+ 341 if spec.TTY != nil {
+ 342 env := b.rootfsTTYVars(rt, spec.genEnv, dbPath, spec.RunID, spec.TTY.Term)
+ 343 return b.startRootfsCmd(ctx, rt, instancectl.RoleTTY, id, rootfsCmdLaunch{Process: spec.Process, Argv: spec.Args}, env, oneShotSinks{TTY: spec.TTY})
+ 344 }
+ 345 env := b.rootfsCmdVars(rt, spec.genEnv, dbPath, spec.RunID, spec.RunDir)
+ 346 return b.startRootfsCmd(ctx, rt, instancectl.RoleCmd, id, rootfsCmdLaunch{Argv: spec.Args}, env, oneShotSinks{Stdout: spec.Stdout, Stderr: spec.Stderr})
+ 347 }
+ 348
+ 349 // oneShotKiller is the lease's kill of a rootfs one-shot unit (rootfs apps
+ 350 // Plan 6 Task 7a, Call A1; C7): the unit of role (cmd, or tty) killed
+ 490 // handle that kept none is refused, nothing prepared); every rootfs gate;
+ 491 // a control channel with a rootfs half; g's whole staged identity, its
+ 492 // image checked against its digest and named as rootfsImage names it
+ 493 // (RFS-2-C07 included) with the worker as its process; the worker's
+ 494 // directories, records and log listener (prepareWorker); its launch file,
+ 495 // the composed environment alone (rootfsWorkerVars through
+ 496 // rootfsLaunchEnv); the caller's exec gate, the last thing before root is
+ 497 // asked; then StartRootfsWorker at g's memory.max. Root's answers given
+ 498 // before systemctl start are refusals: the launch file goes and the
+ 499 // listener closes. Any other failure, or no invocation, may have started
+ 500 // the unit: a handle comes back with the error and the files stay, for
+ 501 // the caller's RootfsWorkerGone.
+ 502 func (b *ExecBackend) LaunchRootfsWorker(ctx context.Context, rt registry.Route, name string, g Gen, web Proc) (Proc, error) {
+ 503 if err := b.sandboxLaunch(rt, "worker", 0, true); err != nil {
+ 504 return nil, err
+ 505 }
+ 506 ctx = b.admissionContext(ctx, rt)
+ 507 if !rt.Rootfs() {
+ 508 return nil, refuseRootfs(fmt.Errorf("%s: a worker runs only on a rootfs instance", rt.Host))
+ 509 }
+ 510 if !release.ValidWorkerName(name) {
+ 511 return nil, refuseRootfs(fmt.Errorf("%s: %q is not a worker name", rt.Host, name))
+ 512 }
+ 513 var genEnv map[string]string
+ 514 if le, ok := web.(launchEnvProc); ok {
+ 515 genEnv = le.LaunchEnv()
+ 516 }
+ 517 if genEnv == nil {
+ 518 return nil, refuseRootfs(fmt.Errorf("%s: worker %s: its web generation kept no launch environment", rt.Host, name))
+ 519 }
+ 520 haveControl := false
+ 521 if up, ok := web.(*unitProc); ok && up.ctl != nil {
+ 522 haveControl = true
+ 523 }
+ 524 if err := b.rootfsGates(ctx, rt); err != nil {
+ 525 return nil, err
+ 526 }
+ 527 rc, err := b.rootfsControl()
+ 528 if err != nil {
+ 529 return nil, refuseRootfs(fmt.Errorf("%s: %w", rt.Host, err))
+ 530 }
+ 531 id, err := stagedIdentityOf(g)
+ 532 if err != nil {
+ 533 return nil, refuseRootfs(fmt.Errorf("%s: worker %s: %w", rt.Host, name, err))
+ 534 }
+ 535 if err := release.VerifyStaged(id); err != nil {
+ 536 return nil, fmt.Errorf("%s: worker %s not started on %s: %w", rt.Host, name, id.Version, err)
+ 537 }
+ 538 img, err := b.rootfsImage(rt, id)
+ 539 if err != nil {
+ 540 return nil, err
+ 541 }
+ 542 img.Process = name
+ 543 p, logs, err := b.prepareWorker(rt, name)
+ 544 if err != nil {
+ 545 return nil, err
+ 546 }
+ 547 fail := func(err error) (Proc, error) {
+ 548 _ = os.Remove(filepath.Join(p.dataDir, instancectl.WorkerLaunchFileName(name)))
+ 549 logs.Close()
+ 550 return nil, err
+ 551 }
+ 552 env := rootfsLaunchEnv(b.rootfsWorkerVars(rt, g, p.dbPath, genEnv, haveControl))
+ 553 if err := b.writeRootfsWorkerLaunch(p, rt.Host, name, env); err != nil {
+ 554 return fail(err)
+ 555 }
+ 556 // The caller's exec gate, right before root is asked: a refusal starts
+ 557 // nothing.
+ 558 if err := runExecGate(ctx); err != nil {
+ 559 return fail(err)
+ 560 }
+ 561 unit := rootfsUnitFor(rt, instancectl.RoleWorker, 0, name)
+ 562 inv, err := rc.StartRootfsWorker(ctx, rt.Host, name, g.Tier.MemoryMax, img)
+ 563 if err == nil {
+ 564 err = instancectl.ValidateStartIdentity(inv, b.SandboxEffective, rt.Host, instancectl.RoleWorker, 0, true, name)
+ 565 }
+ 566 if errors.Is(err, instancectl.ErrStagedImage) || errors.Is(err, instancectl.ErrStartRefused) {
+ 567 // Answered before systemctl start: nothing of the build ran
+ 568 // (INV-4).
+ 569 return fail(refuseRootfs(fmt.Errorf("%s: start %s: %w", rt.Host, unit, err)))
+ 570 }
+ 571 if err != nil || inv.InvocationID == "" {
+ 572 if err == nil {
+ 573 err = exitedUnobserved{unit: unit}
+ 574 }
+ 575 // The request may have reached systemd: the unit may run, so its
+ 576 // files and listener stay with a handle the caller proves gone.
+ 577 log.Printf("activator: %s: start of %s (worker %s of build %s) failed, it may have begun: %v", rt.Host, unit, name, id.Version, err)
+ 578 up, perr := b.newRootfsWorkerProc(rt, name, p, inv, logs)
+ 579 if perr != nil {
+ 580 return &uncertainWorkerProc{b: b, rt: rt, name: name, logs: logs}, markStartUncertain(fmt.Errorf("%s: start %s: %w; %v", rt.Host, unit, err, perr))
+ 581 }
+ 582 return up, markStartUncertain(fmt.Errorf("%s: start %s: %w", rt.Host, unit, err))
+ 583 }
+ 584 log.Printf("activator: %s: started %s (worker %s of build %s) memory.max=%d", rt.Host, unit, name, id.Version, g.Tier.MemoryMax)
+ 585 up, err := b.newRootfsWorkerProc(rt, name, p, inv, logs)
+ 40 var rootfsHealthTimeout = release.RootfsHealthTimeout
+ 41
+ 42 // rootfsTier is a rootfs row's memory tier (R9, deviation 9): tier and
+ 43 // GenTier answer it for a rootfs row before Tier or TierOf is consulted.
+ 44 // It is the base tier, which #328's operator sizes wrap (SizedLimit(rt,
+ 45 // base)), so it is answered in the one place the base is computed
+ 46 // (ExecBackend.tier).
+ 47 var rootfsTier = cgroup.TierChildren
+ 48
+ 49 var errNoRootfsControl = errors.New("activator: the instance control channel cannot start a rootfs instance")
+ 50
+ 51 // errRootfsRefused marks every refusal a rootfs start makes before
+ 52 // anything of its build runs or is asked of root: the gates, the agent's
+ 53 // RFS-2-C07 check, a binary launch path refusing a rootfs row. verdictOf
+ 54 // reads it as a refusal, never a failure of the build. It is matched
+ 55 // through rootfsRefusal, which leaves the refusal's own text as it is.
+ 56 var errRootfsRefused = errors.New("activator: rootfs start refused")
+ 57
+ 58 type rootfsRefusal struct{ err error }
+ 59
+ 60 func (e rootfsRefusal) Error() string { return e.err.Error() }
+ 61 func (e rootfsRefusal) Unwrap() error { return e.err }
+ 62 func (e rootfsRefusal) Is(target error) bool { return target == errRootfsRefused }
+ 63
+ 64 // refuseRootfs marks err as a rootfs refusal; nil stays nil.
+ 65 func refuseRootfs(err error) error {
+ 66 if err == nil {
+ 67 return nil
+ 68 }
+ 69 return rootfsRefusal{err: err}
+ 70 }
+ 71
+ 72 // errRootfsBinaryLaunch is a binary unit's start asked for a rootfs row
+ 73 // (nestedGate): the row's processes start only from its image.
+ 74 var errRootfsBinaryLaunch = errors.New("activator: a rootfs instance does not start through a binary unit")
+ 75
+ 76 // rootfsOwnedNames are set by the agent on every rootfs launch, whatever
+ 77 // the instance's files say (rootfsVars).
+ 78 var rootfsOwnedNames = []string{"CARLOS_SOCKET", "CARLOS_DB"}
+ 79
+ 80 // rootfsVars is vars with the web process's socket and database set (spec
+ 81 // §5.2): a rootfs process has no argv of the agent's, so these two reach
+ 82 // it as environment, and a tenant's file cannot redirect either.
+ 83 func rootfsVars(vars map[string]string, sock, dbPath string) map[string]string {
+ 84 return withVar(withVar(vars, "CARLOS_SOCKET", sock), "CARLOS_DB", dbPath)
+ 85 }
+ 250 // asks it right before root is. Errors keep spawnRootfs's contract: a
+ 251 // start whose unit may have run says so (startMayHaveRun,
+ 252 // genStartUnproven); spawnRootfs hands back no process with an error.
+ 253 func (b *ExecBackend) startStagedRootfs(ctx context.Context, rt registry.Route, g Gen) (Gen, Proc, error) {
+ 254 id, err := stagedIdentityOf(g)
+ 255 if err != nil {
+ 256 return g, nil, refuseRootfs(fmt.Errorf("%s: a staged rootfs start: %w", rt.Host, err))
+ 257 }
+ 258 if err := b.rootfsGates(ctx, rt); err != nil {
+ 259 return g, nil, err
+ 260 }
+ 261 if g.Tier == (cgroup.Limit{}) {
+ 262 g.Tier = b.GenTier(rt, g.Build)
+ 263 }
+ 264 if err := release.VerifyStaged(id); err != nil {
+ 265 return g, nil, fmt.Errorf("%s: not started on %s: %w", rt.Host, id.Version, err)
+ 266 }
+ 267 sock := nestedGenSocketIn(b.pathsFor(rt).runDir, g.N)
+ 268 // g.Tier is the limit the caller chose (a swap keeps the incumbent's
+ 269 // larger tier while a shrink waits for a cold start): root is asked
+ 270 // for exactly that limit (census P1-1), never a recomputed one.
+ 271 up, ver, err := b.spawnRootfs(ctx, rt, sock, g.N, id, g.Tier)
+ 272 if err != nil {
+ 273 if up != nil {
+ 274 return g, up, err
+ 275 }
+ 276 return g, nil, err
+ 277 }
+ 278 g.Socket, g.Control, g.Build = sock, sock+".control", ver
+ 279 return g, up, nil
+ 280 }
+ 328 // tier is the limit root is asked for; a zero tier means GenTier's, so a
+ 329 // caller that chose a limit (startStagedRootfs, a swap's successor) has it
+ 330 // kept, as spawnChildFrom and spawnUnitFrom keep theirs.
+ 331 func (b *ExecBackend) spawnRootfs(ctx context.Context, rt registry.Route, sock string, n uint64, id release.StagedIdentity, tier cgroup.Limit) (*unitProc, string, error) {
+ 332 if err := b.sandboxLaunch(rt, "run", n, true); err != nil {
+ 333 return nil, "", err
+ 334 }
+ 335 var steps wakeSteps
+ 336 steps.begin(time.Now())
+ 337 rc, err := b.rootfsControl()
+ 338 if err != nil {
+ 339 return nil, "", fmt.Errorf("%s: %w", rt.Host, err)
+ 340 }
+ 341 gen, err := b.unitGen(n)
+ 342 if err != nil {
+ 343 return nil, "", err
+ 344 }
+ 345 img, err := b.rootfsImage(rt, id)
+ 346 if err != nil {
+ 347 return nil, "", err
+ 348 }
+ 349 if tier == (cgroup.Limit{}) {
+ 350 tier = b.GenTier(rt, id.Version)
+ 351 }
+ 352 steps.mark(time.Now(), "build")
+ 353 var prep wakeSteps
+ 354 p, ctl, logs, fileEnv, keyLayer, err := b.prepareKeyedAt(rt, instancectl.RoleRun, sock, gen, &prep)
+ 355 if err != nil {
+
+exec
+/bin/bash -lc "rg -n 'health|drain|Probe|Ready|ready' internal/edge/replica*; rg -n 'MemoryMax|cmdMemory|RunMemory' internal/activator/backend_rootfs.go; rg -n 'release.*(Host|host)|Release.*(Host|host)|success|Version' internal/activator/rootfsrelease.go" in /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-stateless-replicas-scale
+exec
+/bin/bash -lc "nl -ba internal/activator/agentowned_moves_test.go | head -100; nl -ba internal/activator/backend_exec.go | sed -n '2730,2785p;3320,3360p'; rg -n 'g.Tier|Tier =' internal/activator/*go | head -65" in /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-stateless-replicas-scale
+ succeeded in 0ms:
+internal/edge/replicashutdown_linux_test.go:27: rt := registry.Route{Host: "shop.example.com", Account: "bab", App: "shop", Kind: "instance", Status: "ready", Region: "fleet/pi", Stateless: true, FleetBoxes: `["box-00"]`, Copies: 2, ReplicaRevision: 1, ReplicaIncarnation: "life"}
+internal/edge/replicashutdown_linux_test.go:38: RunWithActivatorReady([]string{"-dev", "-registry", path, "-http", "127.0.0.1:0"}, nil, nil, func(e *Edge) {
+internal/edge/replicashutdown_linux_test.go:40: if e.replicaProbes == nil {
+internal/edge/replicashutdown_linux_test.go:43: e.replicaProbes.mu.Lock()
+internal/edge/replicashutdown_linux_test.go:44: job = e.replicaProbes.jobs[replicaSlot{rt.Host, "box-00"}]
+internal/edge/replicashutdown_linux_test.go:45: e.replicaProbes.mu.Unlock()
+internal/edge/replicashutdown_linux_test.go:63: e.ReplicaProbe = func(ctx context.Context, _, _ string) (replicas.Copy, error) {
+internal/edge/replicashutdown_linux_test.go:69: // Returning from the real listener/drain path must cancel and join the job.
+internal/edge/replicashutdown_linux_test.go:81: running.replicaProbes.mu.Lock()
+internal/edge/replicashutdown_linux_test.go:82: stopped := running.replicaProbes.stopped
+internal/edge/replicashutdown_linux_test.go:83: remaining := len(running.replicaProbes.jobs)
+internal/edge/replicashutdown_linux_test.go:84: running.replicaProbes.mu.Unlock()
+internal/edge/replicaprober_test.go:23:func TestReplicaProbeFailureWithoutTunnelLoss(t *testing.T) {
+internal/edge/replicaprober_test.go:26: var unhealthy atomic.Bool
+internal/edge/replicaprober_test.go:27: p := newReplicaProber(hub, func(context.Context, string, string) (replicas.Copy, error) {
+internal/edge/replicaprober_test.go:29: c.Healthy = !unhealthy.Load()
+internal/edge/replicaprober_test.go:36: t.Fatal("copy started healthy")
+internal/edge/replicaprober_test.go:43: unhealthy.Store(true)
+internal/edge/replicaprober_test.go:51: healthyAfterTwoFailures := len(p.Live(rt.Host)) != 0
+internal/edge/replicaprober_test.go:52: unhealthy.Store(false)
+internal/edge/replicaprober_test.go:60: healthyAfterTwoPasses := len(p.Live(rt.Host)) == 1
+internal/edge/replicaprober_test.go:62: // TestReplicaProbeFailureWithoutTunnelLoss
+internal/edge/replicaprober_test.go:63: if !tunnelConnected || healthyAfterTwoFailures || !healthyAfterTwoPasses {
+internal/edge/replicaprober_test.go:64: t.Fatal("probe state did not follow app health")
+internal/edge/replicaprober_test.go:99:func (c *replicaTestClock) Ticker(d time.Duration) replicaProbeTicker {
+internal/edge/replicaprober_test.go:192:func TestReplicaProbeRejectsOldIdentity(t *testing.T) {
+internal/edge/replicaprober_test.go:198: p := newReplicaProber(hub, func(context.Context, string, string) (replicas.Copy, error) {
+internal/edge/replicaprober_test.go:249: p := newReplicaProber(hub, func(context.Context, string, string) (replicas.Copy, error) {
+internal/edge/replicaprober_test.go:303: p := newReplicaProber(hub, func(context.Context, string, string) (replicas.Copy, error) {
+internal/edge/replicaprober_test.go:321: t.Fatal("new build inherited old health")
+internal/edge/replicaprober_test.go:331:func TestReplicaProbeConcurrentBound(t *testing.T) {
+internal/edge/replicaprober_test.go:337: p := newReplicaProber(hub, func(ctx context.Context, channel, host string) (replicas.Copy, error) {
+internal/edge/replicaprober_test.go:356: t.Fatal("started healthy")
+internal/edge/replicaprober_test.go:395:func TestReplicaProbeCancellationAndReplacement(t *testing.T) {
+internal/edge/replicaprober_test.go:400: p := newReplicaProber(hub, func(context.Context, string, string) (replicas.Copy, error) {
+internal/edge/replicaprober_test.go:417: t.Fatal("client cancellation ejected a fresh healthy copy")
+internal/edge/replicaprober_test.go:433: p := newReplicaProber(hub, func(context.Context, string, string) (replicas.Copy, error) {
+internal/edge/replicaprober_test.go:466: t.Fatal("unchanged Sync discarded healthy job")
+internal/edge/replicaprober_test.go:482: t.Fatal("replacement inherited health")
+internal/edge/replicaprober_test.go:487: t.Fatal("replacement did not become healthy")
+internal/edge/replicaprober_test.go:507: t.Fatal("retired job changed or ejected its healthy replacement")
+internal/edge/replicaprober_test.go:512:func TestReplicaProbeStartsUnknown(t *testing.T) {
+internal/edge/replicaprober_test.go:516: p := newReplicaProber(hub, func(ctx context.Context, _, _ string) (replicas.Copy, error) {
+internal/edge/replicaprober_test.go:525: t.Fatal("copy started healthy before any answer")
+internal/edge/replicaprober_test.go:529:func TestReplicaProbeSnapshotAndSync(t *testing.T) {
+internal/edge/replicaprober_test.go:532: p := newReplicaProber(hub, func(context.Context, string, string) (replicas.Copy, error) {
+internal/edge/replicaprober_test.go:593:func TestReplicaProbeStatusRangeHub(t *testing.T) {
+internal/edge/replicaprober_test.go:632: t.Fatalf("invalid status %d healthy", bad)
+internal/edge/replicaprober_test.go:637:func TestReplicaProbeAdapterRefusesNonCopy(t *testing.T) {
+internal/edge/replicaprober_test.go:640: if r.Method != "GET" || r.URL.Path != replicaProbePath || r.Header.Get(tunnelclient.ReplicaProbeHeader) != "1" {
+internal/edge/replicaprober_test.go:663:func TestReplicaProbeTunnelNoticeAndEdgeSnapshot(t *testing.T) {
+internal/edge/replicaprober_test.go:677: t.Cleanup(e.stopReplicaProbes)
+internal/edge/replicaprober_test.go:679: if len(e.ReplicaSnapshots()) != 0 || e.replicaProbes != nil {
+internal/edge/replicaprober_test.go:683: e.ReplicaProbe = func(ctx context.Context, channel, host string) (replicas.Copy, error) {
+internal/edge/replicaprober_test.go:687: e.syncReplicaProbes([]registry.Route{rt})
+internal/edge/replicaprober_test.go:688: replicaAwait(t, "edge snapshot became healthy", func() bool { s := e.ReplicaSnapshots()[rt.Host]; return len(s.Copies) == 1 && s.Copies[0].Healthy })
+internal/edge/replicaprober_test.go:702: t.Fatal("reconnect retained health")
+internal/edge/replicaprober_test.go:715: t.Fatal("closed peer kept healthy snapshot")
+internal/edge/replicaprober_test.go:719:func TestReplicaProbeBootPinSurvivesAssignment(t *testing.T) {
+internal/edge/replicaprober_test.go:724: p := newReplicaProber(hub, func(context.Context, string, string) (replicas.Copy, error) {
+internal/edge/replicaprober_test.go:749:func TestReplicaProbeMixedBuildsStayLive(t *testing.T) {
+internal/edge/replicaprober_test.go:755: p := newReplicaProber(hub, func(_ context.Context, channel, _ string) (replicas.Copy, error) {
+internal/edge/replicaprober_test.go:775:func TestReplicaProbeAssignmentChangesPreserveSurvivors(t *testing.T) {
+internal/edge/replicaprober_test.go:781: p := newReplicaProber(hub, func(_ context.Context, channel, _ string) (replicas.Copy, error) {
+internal/edge/replicaprober_test.go:799: // A revision-only change keeps both jobs and their accepted health intact.
+internal/edge/replicaprober_test.go:863:func TestReplicaProbeRevisionSkewRefreshesHealth(t *testing.T) {
+internal/edge/replicaprober_test.go:870: p := newReplicaProber(hub, func(context.Context, string, string) (replicas.Copy, error) {
+internal/edge/replicaprober_test.go:887: t.Fatalf("skewed health not refreshed at pass %d: %+v", n, live)
+internal/edge/replicaprober_test.go:916: p := newReplicaProber(hub, func(context.Context, string, string) (replicas.Copy, error) {
+internal/edge/replicaprober_test.go:948:func TestReplicaProbeRevisionChangeKeepsServing(t *testing.T) {
+internal/edge/replicaprober_test.go:954: if r.URL.Path == replicaProbePath {
+internal/edge/replicaprober_test.go:973: p := newReplicaProber(hub, nil, clock)
+internal/edge/replicaproxy_test.go:21:func replicaProxyFixture(t *testing.T, handlers ...http.HandlerFunc) (*TunnelHub, *replicaProber, registry.Route) {
+internal/edge/replicaproxy_test.go:25: p := newReplicaProber(hub, nil, clock)
+internal/edge/replicaproxy_test.go:120: hub, p, rt := replicaProxyFixture(t, func(http.ResponseWriter, *http.Request) { t.Error("unhealthy copy dispatched") })
+internal/edge/replicaproxy_test.go:124: if w.Code != 503 || w.Header().Get("Retry-After") != "2" || w.Body.String() != "no healthy copy is available. try again shortly\n" {
+internal/edge/replicaprober.go:19: replicaProbeInterval = time.Second
+internal/edge/replicaprober.go:20: replicaProbeFail = 2
+internal/edge/replicaprober.go:21: replicaProbeRise = 2
+internal/edge/replicaprober.go:23: replicaFailed = "this copy did not pass its health check"
+internal/edge/replicaprober.go:27: replicaWaiting = "waiting for this copy to pass its health check"
+internal/edge/replicaprober.go:29: replicaStale = "this health answer belongs to an earlier instance or assignment"
+internal/edge/replicaprober.go:32:// replicaProbeClock controls cadence and deadlines together. Tests advance both
+internal/edge/replicaprober.go:34:type replicaProbeClock interface {
+internal/edge/replicaprober.go:36: Ticker(time.Duration) replicaProbeTicker
+internal/edge/replicaprober.go:39:type replicaProbeTicker interface {
+internal/edge/replicaprober.go:46:func (replicaRealClock) Ticker(d time.Duration) replicaProbeTicker {
+internal/edge/replicaprober.go:57:type replicaProbeFunc func(context.Context, string, string) (replicas.Copy, error)
+internal/edge/replicaprober.go:64: route registry.Route // guarded by replicaProber.mu
+internal/edge/replicaprober.go:69: // Everything below is guarded by replicaProber.mu.
+internal/edge/replicaprober.go:75:type replicaProber struct {
+internal/edge/replicaprober.go:78: probe replicaProbeFunc
+internal/edge/replicaprober.go:79: clock replicaProbeClock
+internal/edge/replicaprober.go:86:func newReplicaProber(hub *TunnelHub, probe replicaProbeFunc, clock replicaProbeClock) *replicaProber {
+internal/edge/replicaprober.go:93: return &replicaProber{hub: hub, probe: probe, clock: clock, jobs: make(map[replicaSlot]*replicaJob), routes: make(map[string]registry.Route)}
+internal/edge/replicaprober.go:98:func (p *replicaProber) Sync(routes []registry.Route) {
+internal/edge/replicaprober.go:134: // or rewriting its last accepted sample and health counters.
+internal/edge/replicaprober.go:156:func (p *replicaProber) reset(j *replicaJob, conn *tunnelConn, reason string) {
+internal/edge/replicaprober.go:166:func (p *replicaProber) connection(j *replicaJob) *tunnelConn {
+internal/edge/replicaprober.go:179:func (p *replicaProber) run(j *replicaJob) {
+internal/edge/replicaprober.go:182: tick := p.clock.Ticker(replicaProbeInterval)
+internal/edge/replicaprober.go:194: ctx, cancel := p.clock.Timeout(j.ctx, replicaProbeTimeout)
+internal/edge/replicaprober.go:218: // its successor; readers already exclude the closed connection.
+internal/edge/replicaprober.go:227:func (p *replicaProber) record(j *replicaJob, conn *tunnelConn, c replicas.Copy, err, cause error) {
+internal/edge/replicaprober.go:259: // membership; this observation describes the same copy's health.
+internal/edge/replicaprober.go:271: current.count.recordProbe(failure, replicaProbeFail, replicaProbeRise, p.clock.Now())
+internal/edge/replicaprober.go:279: if current.count.fails >= replicaProbeFail {
+internal/edge/replicaprober.go:304:func (p *replicaProber) snapshotLocked(rt registry.Route) replicas.Snapshot {
+internal/edge/replicaprober.go:308: // FleetBoxes is already canonical and sorted. A single-host read visits
+internal/edge/replicaprober.go:318:func (p *replicaProber) snapshots() map[string]replicas.Snapshot {
+internal/edge/replicaprober.go:327:func (p *replicaProber) Snapshot(host string) replicas.Snapshot {
+internal/edge/replicaprober.go:336:func (p *replicaProber) Live(host string) []replicas.Copy {
+internal/edge/replicaprober.go:339: if c.Healthy && !c.ObservedAt.IsZero() && p.clock.Now().Sub(c.ObservedAt) <= replicaProbeFail*replicaProbeInterval+replicaProbeTimeout {
+internal/edge/replicaprober.go:347:// ordinary dispatched request error must be left to the health probes.
+internal/edge/replicaprober.go:348:func (p *replicaProber) Eject(host, box string) {
+internal/edge/replicaprober.go:357:func (p *replicaProber) Stop() {
+internal/edge/replicaprober.go:372: ctx, cancel := context.WithTimeout(ctx, replicaProbeTimeout)
+internal/edge/replicaprober.go:374: req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://"+host+replicaProbePath, nil)
+internal/edge/replicaprober.go:378: req.Header.Set(tunnelclient.ReplicaProbeHeader, "1")
+internal/edge/replicaprober.go:399:func (e *Edge) replicaProberForRouting() *replicaProber {
+internal/edge/replicaprober.go:402: if e.replicaProbes == nil {
+internal/edge/replicaprober.go:403: e.replicaProbes = newReplicaProber(e.tunnels, e.ReplicaProbe, nil)
+internal/edge/replicaprober.go:405: return e.replicaProbes
+internal/edge/replicaprober.go:407:func (e *Edge) syncReplicaProbes(routes []registry.Route) {
+internal/edge/replicaprober.go:409: p := e.replicaProbes
+internal/edge/replicaprober.go:412: p = e.replicaProberForRouting()
+internal/edge/replicaprober.go:420: p := e.replicaProbes
+internal/edge/replicaprober.go:427:func (e *Edge) stopReplicaProbes() {
+internal/edge/replicaprober.go:429: p := e.replicaProbes
+internal/edge/replicaprobe.go:17:const replicaProbePath = "/__carlos/replica-probe"
+internal/edge/replicaprobe.go:18:const replicaProbeTimeout = time.Second
+internal/edge/replicaprobe.go:20:// ReplicaHealth is the hub's current assignment-scoped health view.
+internal/edge/replicaprobe.go:25:type copyProbeSource interface {
+internal/edge/replicaprobe.go:26: ProbeCopy(context.Context, string) (replicas.Copy, error)
+internal/edge/replicaprobe.go:29:func (e *Edge) serveReplicaProbe(w http.ResponseWriter, r *http.Request, host string, rt registry.Route, authenticated bool) {
+internal/edge/replicaprobe.go:35: source, ok := e.act.(copyProbeSource)
+internal/edge/replicaprobe.go:40: ctx, cancel := context.WithTimeout(r.Context(), replicaProbeTimeout)
+internal/edge/replicaprobe.go:42: initial, err := source.ProbeCopy(ctx, host)
+internal/edge/replicaprobe.go:56: c, err := source.ProbeCopy(leg.Context(), host)
+internal/edge/replicaprobe.go:79: after, err := source.ProbeCopy(leg.Context(), host)
+internal/edge/replicaprobe.go:98:func replicaProbeAuthenticated(r *http.Request) bool {
+internal/edge/replicaprobe.go:99: return tunnelclient.FromTunnel(r.Context()) && r.Header.Get(tunnelclient.ReplicaProbeHeader) == "1"
+internal/edge/replicaforward_test.go:33: e.replicaProbes = newReplicaProber(hub, func(_ context.Context, channel, host string) (replicas.Copy, error) {
+internal/edge/replicaforward_test.go:40: t.Cleanup(e.stopReplicaProbes)
+internal/edge/replicaforward_test.go:42: rt.Status = "ready"
+internal/edge/replicaforward_test.go:101: t.Fatal("set used address health")
+internal/edge/replicaforward_test.go:109: platform := registry.Route{Host: "platform.example.com", Kind: "instance", Status: "ready", Platform: true, Account: source.Account, App: source.App, Socket: source.Socket}
+internal/edge/replicaforward_test.go:222: p := e.replicaProbes
+internal/edge/replicaforward_test.go:286: t.Fatal("old lifetime health survived")
+internal/edge/replicaforward_test.go:293: e.stopReplicaProbes()
+internal/edge/replicaforward_test.go:317: rt.Status = "ready"
+internal/edge/replicaforward_test.go:337: t.Fatalf("structural refusal misreported as health: %+v", verdict)
+internal/edge/replicaproxy.go:22: replicaUnavailable = "no healthy copy is available. try again shortly"
+internal/edge/replicaproxy.go:35: p *replicaProber
+internal/edge/replicaproxy.go:42:func replicaProxy(host, fleet string, p *replicaProber, hub *TunnelHub) *httputil.ReverseProxy {
+internal/edge/replicaproxy.go:189: // Headers already returned by RoundTrip win even if cancellation
+internal/edge/replicaconsole_test.go:32: rt := registry.Route{Host: "console.test", App: "console", Unit: "console.service", Kind: "service", Addr: console.Listener.Addr().String(), Status: "ready", Version: "v-test"}
+internal/edge/replicaconsole_test.go:33: for _, route := range []registry.Route{rt, {Host: "app.test", Kind: "service", Addr: app.Listener.Addr().String(), Status: "ready"}} {
+internal/edge/replicaprobe_test.go:26:type replicaProbeLeg struct{ ctx context.Context }
+internal/edge/replicaprobe_test.go:28:func (l replicaProbeLeg) Context() context.Context { return l.ctx }
+internal/edge/replicaprobe_test.go:29:func (l replicaProbeLeg) Done() {}
+internal/edge/replicaprobe_test.go:31:type replicaProbeAct struct {
+internal/edge/replicaprobe_test.go:35: onProbe func()
+internal/edge/replicaprobe_test.go:38:func (a *replicaProbeAct) ProbeCopy(context.Context, string) (replicas.Copy, error) {
+internal/edge/replicaprobe_test.go:40: if a.onProbe != nil {
+internal/edge/replicaprobe_test.go:41: a.onProbe()
+internal/edge/replicaprobe_test.go:45:func (a *replicaProbeAct) AdmitHeldLeg(ctx context.Context, _ registry.Route) (HeldLeg, error) {
+internal/edge/replicaprobe_test.go:46: return replicaProbeLeg{ctx}, nil
+internal/edge/replicaprobe_test.go:49:func replicaLanding(t *testing.T, h http.Handler) (*Edge, *replicaProbeAct) {
+internal/edge/replicaprobe_test.go:54: rt := registry.Route{Host: "shop.example.com", Kind: "instance", Status: "ready", Account: "bab", App: "shop", Region: "fleet/pi", Stateless: true, FleetBoxes: `["a","b"]`, Copies: 2, ReplicaRevision: 7, ReplicaIncarnation: "life", Socket: filepath.Join(dir, "wrong.sock")}
+internal/edge/replicaprobe_test.go:58: act := &replicaProbeAct{genActivator: &genActivator{fakeGens: newFakeGens(true)}, copy: replicas.Copy{Host: rt.Host, Account: rt.Account, App: rt.App, Fleet: "pi", Box: "a", BootID: "boot", Incarnation: "life", AssignmentRevision: 7, Generation: 12, Version: "v1", Digest: "digest", State: "running", Socket: app.sock}}
+internal/edge/replicaprobe_test.go:70: r := httptest.NewRequest(http.MethodGet, "http://shop.example.com"+replicaProbePath, nil)
+internal/edge/replicaprobe_test.go:71: r.Header.Set(tunnelclient.ReplicaProbeHeader, marker)
+internal/edge/replicaprobe_test.go:81:func TestReplicaProbeLandingRefusesPublic(t *testing.T) {
+internal/edge/replicaprobe_test.go:111: if r.Header.Get(tunnelclient.ReplicaProbeHeader) != "" {
+internal/edge/replicaprobe_test.go:120: ordinary.Header.Set(tunnelclient.ReplicaProbeHeader, "1")
+internal/edge/replicaprobe_test.go:137: r.Header.Set(tunnelclient.ReplicaProbeHeader, "1")
+internal/edge/replicaprobe_test.go:139: if r.Header.Get(tunnelclient.ReplicaProbeHeader) != "" {
+internal/edge/replicaprobe_test.go:142: r.Header.Set(tunnelclient.ReplicaProbeHeader, "1")
+internal/edge/replicaprobe_test.go:145: if pr.Out.Header.Get(tunnelclient.ReplicaProbeHeader) != "" {
+internal/edge/replicaprobe_test.go:150:func TestReplicaProbeStatusRange(t *testing.T) {
+internal/edge/replicaprobe_test.go:156: if r.URL.Path != "/" || r.Method != "GET" || r.Header.Get("Authorization") != "" || r.Header.Get(tunnelclient.ReplicaProbeHeader) != "" {
+internal/edge/replicaprobe_test.go:169: t.Fatalf("health=%v hits=%d", c.Healthy, hits.Load())
+internal/edge/replicaprobe_test.go:175:func TestReplicaProbeAssignedIdentity(t *testing.T) {
+internal/edge/replicaprobe_test.go:207:func TestReplicaProbeAdmissionAndTimeout(t *testing.T) {
+internal/edge/replicaprobe_test.go:225: w := s.do(t, "GET", doorOwnHost, "/__carlos/replica-probe", s.key, map[string]string{tunnelclient.ReplicaProbeHeader: "1"}, nil)
+internal/edge/replicaprobe_test.go:229: w = s.do(t, "GET", doorOwnHost, "/replica-health", s.key, nil, nil)
+internal/edge/replicaprobe_test.go:235:func TestReplicaProbeServingGenerationChanges(t *testing.T) {
+internal/edge/replicaprobe_test.go:237: a.onProbe = func() {
+internal/edge/replicaprobe_test.go:250:func TestReplicaProbeCheckedSocket(t *testing.T) {
+internal/edge/replicaprobe_test.go:286:func TestReplicaProbeMalformedHostRefused(t *testing.T) {
+internal/edge/replicaprobe_test.go:294: r := httptest.NewRequest("GET", "http://shop.example.com"+replicaProbePath, nil)
+internal/edge/replicaprobe_test.go:296: e.serveReplicaProbe(w, r, rt.Host, *rt, true)
+internal/edge/replicaprobe_test.go:302:func TestReplicaProbeLandingUnderBurstProtection(t *testing.T) {
+internal/edge/replicaprobe_test.go:314: r := httptest.NewRequest("GET", "http://"+a.copy.Host+replicaProbePath, nil)
+internal/edge/replicaprobe_test.go:315: r.Header.Set(tunnelclient.ReplicaProbeHeader, "1")
+internal/edge/replica_retry_test.go:183:func TestReplicaRetrySkipsNewlyUnhealthyCopy(t *testing.T) {
+internal/edge/replica_retry_test.go:184: var p *replicaProber
+internal/edge/replica_retry_test.go:207:// Q17: a slow healthy request must keep the legacy header-wait behavior
+internal/edge/replica_retry_test.go:306: // the dispatch hub, after the health set was captured. Both end ejected.
+internal/edge/replica_retry_test.go:346: // Headers have already returned successfully. Hold the proxy precisely
+282: memMax := b.tier(rt).MemoryMax
+562: inv, err := rc.StartRootfsWorker(ctx, rt.Host, name, g.Tier.MemoryMax, img)
+584: log.Printf("activator: %s: started %s (worker %s of build %s) memory.max=%d", rt.Host, unit, name, id.Version, g.Tier.MemoryMax)
+74: return id.Version == rt.GoodVersion && strings.EqualFold(id.Digest, rt.GoodDigest)
+102:// its unit is proven gone: a.releaseOps[host]. Whatever happens to the
+192: // errReleaseOpen: a record for the host exists, in any state (INV-R4).
+307:// releaseOpen reports whether a release command's record exists for host,
+310:func (a *Service) releaseOpen(host string) bool {
+313: return a.releaseOps[host] != nil
+320:// 0 with Result success. Any other code recorded no exit: noExit.
+330: return n == 0 && (st.Result == "" || st.Result == "success"), n, "", false
+359:// (a.releaseOps[rt.Host]) from admission until its unit is proven gone
+374: // INV-R4: one release per host, whatever state the last one is in.
+376: open := a.releaseOps[host] != nil
+426: op := &releaseOp{host: host, build: id, cancel: cancel, owner: e, state: releaseRunning, done: make(chan struct{})}
+450: if a.releaseOps[host] != nil {
+457: a.releaseOps[host] = op
+464: if err := a.recordBuild(ctx, host, id.Version); err != nil {
+472: emitEvent(a.Logs, rt, "info", fmt.Sprintf(rolloutwords.EventReleaseStarted, id.Version))
+494: startErr = fmt.Errorf("%s: the release command's start returned no unit", host)
+499: log.Printf("activator: %s: release command of build %s started", host, id.Version)
+512: log.Printf("activator: %s: polling the release command of build %s: %v; asking again", host, id.Version, perr)
+530: if a.releaseOps[host] == op {
+534: log.Printf("activator: %s: the release command of build %s is not proven stopped: %v; the sweep retries", host, id.Version, settleErr)
+547: emitEvent(a.Logs, rt, "warn", fmt.Sprintf(rolloutwords.EventReleaseLeaseLost, id.Version))
+556: rerr := &ReleaseError{Build: id.Version, TimedOut: true, Took: limit}
+567: emitEvent(a.Logs, rt, "info", fmt.Sprintf(rolloutwords.EventReleaseDone, id.Version, took.Round(time.Second).String()))
+570: log.Printf("activator: %s: the release command of build %s ended with code %q status %q result %q", host, id.Version, st.Code, st.Status, st.Result)
+573: rerr := &ReleaseError{Build: id.Version, Exit: exit, Signal: signal, Took: took}
+630: log.Printf("activator: %s: stopping the release command of build %s: the instance's lease is ending", op.host, op.build.Version)
+699: log.Printf("activator: %s: the release command of build %s is proven stopped", op.host, op.build.Version)
+701: ours := a.releaseOps[op.host] == op
+710: released = a.giveBack(ctx, op.host, owed)
+714: if a.releaseOps[op.host] == op {
+719: delete(a.releaseOps, op.host)
+732: if a.releaseOps[op.host] == op {
+733: delete(a.releaseOps, op.host)
+766:// the wake; an unproven release leaves its record holding the host, and
+785:// proven stopped, the record (a.releaseOps[host], owned by e) keeps the
+799: op := a.releaseOps[e.host]
+815: log.Printf("activator: %s: the wake failed with the release command of build %s not proven stopped; its record keeps the lease until the sweep proves it", op.host, op.build.Version)
+847:// attempt runs the release again (D3). It names the attempt (host,
+882:// and of its exec gate: no release record of the host is open (INV-R4),
+886: if a.releaseOps[at.Host] != nil {
+941: rt.GoodVersion, rt.GoodDigest, rt.GoodDemand = good.Version, good.Digest, good.Demand
+942: id := release.StagedIdentity{Version: at.Build, StagedPath: at.StagedPath, Digest: at.Digest, Demand: at.Demand}
+958: return &releasePass{host: at.Host, schedRev: at.SchedRev, build: id}, true, SwapResult{}, true
+960: return nil, true, releaseSwapResult(err, executed, a.releaseOpen(at.Host)), false
+
+ succeeded in 0ms:
+ 1 package activator
+ 2
+ 3 import (
+ 4 "maps"
+ 5 "os"
+ 6 "path/filepath"
+ 7 "slices"
+ 8 "testing"
+ 9
+ 10 "github.com/carlosframework/platform/internal/edge"
+ 11 "github.com/carlosframework/platform/internal/moves"
+ 12 "github.com/carlosframework/platform/internal/registry"
+ 13 )
+ 14
+ 15 // TestAgentOwnedVarsAreMovesBoxOwned pins moves.AgentOwnedVars against
+ 16 // agentOwnedVars (home part 2, Task 2b; fix round 2). A move's env pin and
+ 17 // T3 leave the agent-owned variables out, because each box composes them
+ 18 // for itself; a variable the agent starts to set, overwrite or remove
+ 19 // without joining that set would make every cross-region move's pin differ
+ 20 // on the target again, or let an instance-supplied value slip past it.
+ 21 //
+ 22 // Each feature configuration is asserted separately, against a tenant env
+ 23 // file that names every agent-owned variable: the exact value the agent
+ 24 // sets, or the variable's absence where the agent removes it. Removing any
+ 25 // one branch's set or deletion fails the test. The variables named here
+ 26 // are the ones the test knows: a new variable the agent only ever removes
+ 27 // (never sets) appears in no configuration's output, so it must be added
+ 28 // to moves.AgentOwnedVars and to the tenant file below by hand.
+ 29 func TestAgentOwnedVarsAreMovesBoxOwned(t *testing.T) {
+ 30 rt := registry.Route{Host: "shop.example.com", Socket: "/run/carlos/shop.example.com.sock"}
+ 31 control := rt.Socket + ".control"
+ 32 tenant := map[string]string{"APP_MODE": "tenant", "HOSTNAME": "tenant"}
+ 33 for k := range moves.AgentOwnedVars {
+ 34 tenant[k] = "tenant"
+ 35 }
+ 36 cache := edge.NewCache(16, 1<<20)
+ 37 absent := "<absent>"
+ 38 for _, c := range []struct {
+ 39 name string
+ 40 b *ExecBackend
+ 41 control bool
+ 42 want map[string]string
+ 43 }{
+ 44 {"everything on", &ExecBackend{ServedPools: eligibleSharedPools, Region: "uk", Cache: cache}, true,
+ 45 map[string]string{"CARLOS_CONTROL_SOCKET": control, "CARLOS_PURGE": "header", "CARLOS_REGION": "uk", "CARLOS_HOST": rt.Host}},
+ 46 {"everything off", &ExecBackend{ServedPools: eligibleSharedPools}, false,
+ 47 map[string]string{"CARLOS_CONTROL_SOCKET": absent, "CARLOS_PURGE": absent, "CARLOS_REGION": absent, "CARLOS_HOST": rt.Host}},
+ 48 {"no control channel", &ExecBackend{ServedPools: eligibleSharedPools, Region: "uk", Cache: cache}, false,
+ 49 map[string]string{"CARLOS_CONTROL_SOCKET": absent, "CARLOS_PURGE": "header", "CARLOS_REGION": "uk", "CARLOS_HOST": rt.Host}},
+ 50 {"no cache", &ExecBackend{ServedPools: eligibleSharedPools, Region: "uk"}, true,
+ 51 map[string]string{"CARLOS_CONTROL_SOCKET": control, "CARLOS_PURGE": absent, "CARLOS_REGION": "uk", "CARLOS_HOST": rt.Host}},
+ 52 {"a home box, no region", &ExecBackend{ServedPools: eligibleSharedPools, Cache: cache}, true,
+ 53 map[string]string{"CARLOS_CONTROL_SOCKET": control, "CARLOS_PURGE": "header", "CARLOS_REGION": absent, "CARLOS_HOST": rt.Host}},
+ 54 } {
+ 55 t.Run(c.name, func(t *testing.T) {
+ 56 for _, file := range []map[string]string{{}, tenant} {
+ 57 got := c.b.agentOwnedVars(rt, control, file, c.control)
+ 58 for k, want := range c.want {
+ 59 v, ok := got[k]
+ 60 if want == absent && ok {
+ 61 t.Errorf("file %v: %s = %q, want it removed", file, k, v)
+ 62 }
+ 63 if want != absent && (!ok || v != want) {
+ 64 t.Errorf("file %v: %s = %q (present %v), want %q", file, k, v, ok, want)
+ 65 }
+ 66 }
+ 67 // Nothing else is the agent's: the tenant's own variables,
+ 68 // a box variable among them, pass through untouched.
+ 69 for k, v := range got {
+ 70 if _, owned := c.want[k]; !owned && file[k] != v {
+ 71 t.Errorf("file %v: the agent set %s = %q", file, k, v)
+ 72 }
+ 73 }
+ 74 }
+ 75 })
+ 76 }
+ 77 // The configurations above cover exactly moves' set, and every member
+ 78 // is box-owned and never pinned.
+ 79 covered := slices.Sorted(maps.Keys(map[string]string{"CARLOS_CONTROL_SOCKET": "", "CARLOS_PURGE": "", "CARLOS_REGION": "", "CARLOS_HOST": ""}))
+ 80 if want := slices.Sorted(maps.Keys(moves.AgentOwnedVars)); !slices.Equal(covered, want) {
+ 81 t.Fatalf("the test covers %v, moves.AgentOwnedVars is %v", covered, want)
+ 82 }
+ 83 // LaunchLayers' list of the names the agent decides is the same set.
+ 84 if names := slices.Sorted(slices.Values(agentOwnedNames)); !slices.Equal(names, covered) {
+ 85 t.Fatalf("agentOwnedNames is %v, the agent decides %v", names, covered)
+ 86 }
+ 87 for _, k := range covered {
+ 88 if !moves.BoxOwned(k) || moves.Pinned(k, false) || moves.Class(k) == "equal" {
+ 89 t.Errorf("%s is agent-owned but pinned or compared when the box supplies it (class %q)", k, moves.Class(k))
+ 90 }
+ 91 }
+ 92 }
+ 93
+ 94 // TestLaunchLayersNamesTheInstanceLayers (fix round 2): LaunchLayers is
+ 95 // LaunchEnvironment with the names the instance's own layers supplied, the
+ 96 // rendered configuration file's and the own .env's. A box variable an
+ 97 // instance file sets is one of them; one inherited from the agent's
+ 98 // process is not, and neither is anything the agent adds.
+ 99 func TestLaunchLayersNamesTheInstanceLayers(t *testing.T) {
+ 100 b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir(), Region: "ie"}
+ 2730 }
+ 2731
+ 2732 // agentOwnedNames are the variables agentOwnedVars decides: it sets or
+ 2733 // removes each of them on every launch, whatever the instance's files say.
+ 2734 // moves.AgentOwnedVars is the same set (TestAgentOwnedVarsAreMovesBoxOwned
+ 2735 // pins both against agentOwnedVars itself).
+ 2736 var agentOwnedNames = []string{"CARLOS_CONTROL_SOCKET", "CARLOS_PURGE", "CARLOS_REGION", "CARLOS_HOST"}
+ 2737
+ 2738 // agentOwnedVars composes the child's agent-owned environment variables,
+ 2739 // namely the control socket, the purge channel, and the region, on top of
+ 2740 // fileEnv, exactly as startChild did inline before the unit spawn path
+ 2741 // needed the same composition. Extracted so the two paths cannot drift
+ 2742 // (design §7.2): haveControl is whether this call's control listener
+ 2743 // actually bound. childVars must follow the OUTCOME of the bind, not the
+ 2744 // intention, per the long comment this replaced, still true here.
+ 2745 func (b *ExecBackend) agentOwnedVars(rt registry.Route, control string, fileEnv map[string]string, haveControl bool) map[string]string {
+ 2746 childVars := fileEnv
+ 2747 if haveControl {
+ 2748 childVars = withVar(childVars, "CARLOS_CONTROL_SOCKET", control)
+ 2749 } else {
+ 2750 childVars = withoutVars(childVars, "CARLOS_CONTROL_SOCKET")
+ 2751 }
+ 2752 if b.Cache != nil {
+ 2753 childVars = withVar(childVars, "CARLOS_PURGE", "header")
+ 2754 } else {
+ 2755 childVars = withoutVars(childVars, "CARLOS_PURGE")
+ 2756 }
+ 2757 if b.Region != "" {
+ 2758 childVars = withVar(childVars, "CARLOS_REGION", b.Region)
+ 2759 } else {
+ 2760 childVars = withoutVars(childVars, "CARLOS_REGION")
+ 2761 }
+ 2762 // The hostname, always, from the row (discussion #256 item 2). An app
+ 2763 // used to learn it from its socket's file name, /run/carlos/<host>.sock,
+ 2764 // and the nested layout's app.sock names nothing; three instances
+ 2765 // crashed at start over that on the first roll. Agent-owned like the
+ 2766 // three above: a tenant's env file does not get to tell an app it is
+ 2767 // some other host.
+ 2768 return storageVars(rt, withVar(childVars, "CARLOS_HOST", rt.Host))
+ 2769 }
+ 2770
+ 2771 // seedVars is the seed's environment over fileEnv: the control-channel
+ 2772 // variables stripped (a seed has no listener for either; see seedChild's
+ 2773 // comment), and CARLOS_HOST set, since a seed initialising a host's
+ 2774 // database is as entitled to know which host as the instance is. One
+ 2775 // composer for both seed paths, as agentOwnedVars is for both run paths.
+ 2776 func seedVars(fileEnv map[string]string, host string) map[string]string {
+ 2777 return withVar(withoutVars(fileEnv, "CARLOS_CONTROL_SOCKET", "CARLOS_PURGE"), "CARLOS_HOST", host)
+ 2778 }
+ 2779
+ 2780 // normalizeSocketMode is the PLATFORM's 0660 on a spawned instance's socket
+ 2781 // (issue #103), not the app's. Extracted from startChild so the unit path
+ 2782 // (whose own bind is the trampoline's, not this process's exec) applies the
+ 2783 // identical rule rather than a second copy that can drift. So a deployment's
+ 2784 // enrolled cross-user consumers (the carlos-sockets group, group-inherited
+ 2785 // from the setgid /run/carlos, see host.tmpfilesConf) can dial, no matter
+ 3320
+ 3321 // LaunchLayers is LaunchEnvironment with the names whose running value the
+ 3322 // instance's own layers supplied: every name of the rendered configuration
+ 3323 // file and the instance's own <host>.env, as mergeEnv merged them, except
+ 3324 // the names agentOwnedVars decides (agentOwnedNames), whose running value
+ 3325 // is the agent's whatever the files say. A name in the composed env that is
+ 3326 // not in instance came from the agent: its own variables or its process
+ 3327 // environment (childEnv). The move's env pin needs the difference
+ 3328 // (moves.ReportLaunch): a box variable such as HOSTNAME is the box's when
+ 3329 // inherited and the instance's when its files set it.
+ 3330 func (b *ExecBackend) LaunchLayers(rt registry.Route) (env map[string]string, instance map[string]bool, shadowed []string, err error) {
+ 3331 cfgEnv, ownEnv, err := b.instanceEnvParts(rt)
+ 3332 if err != nil {
+ 3333 return nil, nil, nil, err
+ 3334 }
+ 3335 for k := range ownEnv {
+ 3336 if _, rendered := cfgEnv[k]; rendered {
+ 3337 if k == instancekey.Var && ownEnv[k] == "" {
+ 3338 continue // an empty own key shadows nothing (mergeEnv)
+ 3339 }
+ 3340 shadowed = append(shadowed, k)
+ 3341 }
+ 3342 }
+ 3343 sort.Strings(shadowed)
+ 3344 fileEnv := mergeEnv(cfgEnv, ownEnv)
+ 3345 instance = make(map[string]bool, len(fileEnv))
+ 3346 for k := range fileEnv {
+ 3347 instance[k] = true
+ 3348 }
+ 3349 for _, k := range agentOwnedNames {
+ 3350 delete(instance, k)
+ 3351 }
+ 3352 out := map[string]string{}
+ 3353 for _, kv := range childEnv(b.agentOwnedVars(rt, rt.Socket+".control", fileEnv, true)) {
+ 3354 if i := strings.IndexByte(kv, '='); i > 0 {
+ 3355 out[kv[:i]] = kv[i+1:]
+ 3356 }
+ 3357 }
+ 3358 return out, instance, shadowed, nil
+ 3359 }
+ 3360
+internal/activator/genbackend_test.go:258: t.Fatalf("size small, no build: GenTier = %+v, want 256 MiB", got)
+internal/activator/genbackend_test.go:267: t.Fatalf("split, size xlarge: GenTier = %+v, want 2 GiB", got)
+internal/activator/genbackend_test.go:271:// Each artifact's own tier (spec §7.3): a staged child gets g.Tier, not the
+internal/activator/genbackend_test.go:282: b.Tier = func(registry.Route) cgroup.Limit { return cgroup.TierDefault }
+internal/activator/genbackend.go:29: // through the live link, in its own child cgroup at g.Tier, on the
+internal/activator/genbackend.go:271: if g.Tier == (cgroup.Limit{}) {
+internal/activator/genbackend.go:272: g.Tier = b.GenTier(rt, g.Build)
+internal/activator/genbackend.go:281: proc, _, err := b.spawnChildFrom(ctx, rt, sock, g.N, g.StagedPath, g.Build, g.Tier)
+internal/activator/genbackend.go:293: proc, _, err := b.spawnChildFrom(ctx, rt, rt.Socket, g.N, g.StagedPath, g.Build, g.Tier)
+internal/activator/genbackend.go:307: proc, _, err := b.spawnUnitFrom(ctx, rt, sock, g.N, exe, g.Tier)
+internal/activator/genbackend.go:493: return b.startSidecarUnitFrom(ctx, rt, &exe, g.Tier)
+internal/activator/backend_rootfs.go:562: inv, err := rc.StartRootfsWorker(ctx, rt.Host, name, g.Tier.MemoryMax, img)
+internal/activator/backend_rootfs.go:584: log.Printf("activator: %s: started %s (worker %s of build %s) memory.max=%d", rt.Host, unit, name, id.Version, g.Tier.MemoryMax)
+internal/activator/swap_hold_exec_test.go:70: {"the lease is lost during the preparation", func(f *swapFixture, b *prepHookBackend) { b.onTier = lose(f) }, errSwapLeaseLost},
+internal/activator/swap_hold_exec_test.go:71: {"a fence lands during the preparation", func(f *swapFixture, b *prepHookBackend) { b.onTier = fence(f) }, errSwapFenced},
+internal/activator/size_live_test.go:109: e.gen.Tier = cgroup.Limit{MemoryMax: tier}
+internal/activator/size_live_test.go:138: return g.Tier.MemoryMax
+internal/activator/rootfs.go:47:var rootfsTier = cgroup.TierChildren
+internal/activator/rootfs.go:236: g.Build, g.StagedPath, g.Digest, g.Demand, g.Tier = ran.Version, ran.StagedPath, ran.Digest, ran.Demand, b.GenTier(rt, ran.Version)
+internal/activator/rootfs.go:261: if g.Tier == (cgroup.Limit{}) {
+internal/activator/rootfs.go:262: g.Tier = b.GenTier(rt, g.Build)
+internal/activator/rootfs.go:268: // g.Tier is the limit the caller chose (a swap keeps the incumbent's
+internal/activator/rootfs.go:271: up, ver, err := b.spawnRootfs(ctx, rt, sock, g.N, id, g.Tier)
+internal/activator/containment_test.go:335: b.Tier = func(registry.Route) cgroup.Limit { return cgroup.Limit{} }
+internal/activator/swaphold.go:537: if pin.Tier == (cgroup.Limit{}) {
+internal/activator/swaphold.go:538: pin.Tier = gb.GenTier(rt, pin.Build) // the pinned artifact's own tier (spec §7.3)
+internal/activator/size_identical_test.go:134: if g, _ := f.b.lastGen(); res.Gen.Tier != c.succ || g.Tier != c.succ || g.Tier.MemoryMax != c.succMain {
+internal/activator/size_identical_test.go:135: t.Fatalf("successor: result tier %+v, spawned at %+v; want TierOf's %+v (main: %d)", res.Gen.Tier, g.Tier, c.succ, c.succMain)
+internal/activator/size_identical_test.go:277: if g, _ := f.b.lastGen(); g.Tier.MemoryMax != 536870912 {
+internal/activator/size_identical_test.go:278: t.Fatalf("the successor spawned at %+v; main (953b9fda): 536870912", g.Tier)
+internal/activator/size_identical_test.go:302: if g.Tier.MemoryMax != 536870912 {
+internal/activator/size_identical_test.go:303: t.Fatalf("the successor spawned at %+v; main (953b9fda): 536870912", g.Tier)
+internal/activator/activator.go:3514: e.gen.Tier = tier
+internal/activator/activator.go:3702: g.Tier = gt.GenTier(rt, id.Version)
+internal/activator/swap.go:639: if incumbent.Tier == (cgroup.Limit{}) {
+internal/activator/swap.go:640: incumbent.Tier = gb.GenTier(wakeRt, incumbent.Build)
+internal/activator/swap.go:655: succTier = cgroup.MaxLimit(succTier, incumbent.Tier)
+internal/activator/swap.go:659: m.gen.Tier = succTier
+internal/activator/backend_exec_test.go:36: b.Tier = func(registry.Route) cgroup.Limit { return cgroup.TierChildren }
+internal/activator/backend_exec_test.go:702: b.Tier = func(registry.Route) cgroup.Limit { return cgroup.TierChildren }
+internal/activator/identity_test.go:755: b.Tier = func(rt registry.Route) cgroup.Limit {
+internal/activator/identity_test.go:808: if got := readMax(t, filepath.Join(parent, "memory.max")); got != childrenMax || g.Tier != cgroup.TierChildren {
+internal/activator/identity_test.go:809: t.Fatalf("host cgroup memory.max = %s, handle tier %v; want A's 1 GiB", got, g.Tier)
+internal/activator/identity_test.go:820: if got := readMax(t, filepath.Join(parent, "g9", "memory.max")); got != childrenMax || g.Tier != cgroup.TierChildren {
+internal/activator/identity_test.go:821: t.Fatalf("g9 memory.max = %s, handle tier %v; want A's 1 GiB", got, g.Tier)
+internal/activator/identity_test.go:871: if !strings.Contains(ctl.joined(), tc.want) || g.Tier != cgroup.TierChildren {
+internal/activator/identity_test.go:872: t.Fatalf("root was asked:\n%s\nwant %q; handle tier %v", ctl.joined(), tc.want, g.Tier)
+internal/activator/backend_exec.go:560: if b.Tier == nil {
+internal/activator/backend_exec.go:2265: g.Build, g.StagedPath, g.Digest, g.Demand, g.Tier = id.Version, id.StagedPath, id.Digest, id.Demand, tier
+internal/activator/rootfs_test.go:734: b.Tier = func(registry.Route) cgroup.Limit { return cgroup.TierDefault }
+internal/activator/rootfs_test.go:738: t.Fatalf("GenTier = %+v, want TierChildren", got)
+internal/activator/rootfs_test.go:744: t.Fatalf("a binary row's GenTier = %+v", got)
+internal/activator/rootfs_test.go:996: if g.Socket != sock || g.Build != "v2" || g.StagedPath != id.StagedPath || g.Digest != sum || g.Tier != cgroup.TierChildren {
+internal/activator/rootfsworkers_backend_test.go:223: want := fmt.Sprintf("start-rootfs-worker %s jobs memory_max=%d process=jobs version=%s", rt.Host, g.Tier.MemoryMax, g.Build)
+internal/activator/swap_overlap_test.go:85: if g, _ := f.b.lastGen(); g.Tier != cgroup.TierDefault {
+internal/activator/swap_overlap_test.go:86: t.Fatalf("the successor spawned at %v, want its own 512 MiB tier", g.Tier)
+internal/activator/swap_overlap_test.go:138: inc.Tier = cgroup.Limit{MemoryMax: tc.inc}
+internal/activator/swap_overlap_test.go:148: if g, _ := f.b.lastGen(); g.Tier.MemoryMax != tc.succ {
+internal/activator/swap_overlap_test.go:149: t.Fatalf("the successor spawned at %d, want %d", g.Tier.MemoryMax, tc.succ)
+internal/activator/rootfs_staged_test.go:378: if g.Tier != want || want.MemoryMax == 0 {
+internal/activator/rootfs_staged_test.go:379: t.Fatalf("the generation's tier is %+v, want GenTier's %+v", g.Tier, want)
+internal/activator/rootfs_staged_test.go:404: if g.Tier != chosen {
+internal/activator/rootfs_staged_test.go:405: t.Fatalf("the generation's tier is %+v, want the supplied %+v", g.Tier, chosen)
+internal/activator/rootfs_staged_test.go:530: if err != nil || got != want || g.Tier != eb.GenTier(rt, "v1") {
+
+exec
+/bin/bash -lc "rg --files internal/edge | rg replica; rg -n 'func|Healthy|healthy|State|state|Ready|ready' internal/edge/replicaprober.go internal/edge/replicaproxy.go; nl -ba internal/activator/activator.go | sed -n '3430,3525p'; rg -n 'Mem|memory|limit' internal/instancectl/rootfs*.go | head -60" in /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-stateless-replicas-scale
+ succeeded in 0ms:
+internal/edge/replica_retry_test.go
+internal/edge/replicashutdown_linux_test.go
+internal/edge/replicaprober_test.go
+internal/edge/replicaproxy_test.go
+internal/edge/replicaconsole_test.go
+internal/edge/replicaconsole.go
+internal/edge/replicaprober.go
+internal/edge/replicaforward_test.go
+internal/edge/replicaprobe.go
+internal/edge/replicaprobe_test.go
+internal/edge/replicaproxy.go
+internal/edge/replicaproxy.go:22: replicaUnavailable = "no healthy copy is available. try again shortly"
+internal/edge/replicaproxy.go:31:func (e *replicaUnrepeatedError) Unwrap() error { return e.error }
+internal/edge/replicaproxy.go:39: afterRoundTrip func(context.Context)
+internal/edge/replicaproxy.go:42:func replicaProxy(host, fleet string, p *replicaProber, hub *TunnelHub) *httputil.ReverseProxy {
+internal/edge/replicaproxy.go:46: ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
+internal/edge/replicaproxy.go:66:func (t *replicaTransport) RoundTrip(req *http.Request) (*http.Response, error) {
+internal/edge/replicaproxy.go:71: defer func() {
+internal/edge/replicaproxy.go:137: startTimer := func() {
+internal/edge/replicaproxy.go:141: timer = time.AfterFunc(replicaAttemptTimeout, func() {
+internal/edge/replicaproxy.go:150: stopTimer := func() {
+internal/edge/replicaproxy.go:163: Got1xxResponse: func(int, textproto.MIMEHeader) error {
+internal/edge/replicaproxy.go:168: WroteRequest: func(info httptrace.WroteRequestInfo) {
+internal/edge/replicaproxy.go:189: // Headers already returned by RoundTrip win even if cancellation
+internal/edge/replicaproxy.go:231:func (b *replicaRequestBody) Close() error {
+internal/edge/replicaproxy.go:232: b.once.Do(func() { b.err = b.ReadCloser.Close() })
+internal/edge/replicaproxy.go:235:func replicaBody(b io.ReadCloser) io.ReadCloser {
+internal/edge/replicaproxy.go:247:func (b *replicaResponseBody) Close() error { defer b.cancel(); return b.ReadCloser.Close() }
+internal/edge/replicaproxy.go:254:func (b *replicaResponseConn) Close() error { defer b.cancel(); return b.ReadWriteCloser.Close() }
+internal/edge/replicaproxy.go:255:func (b *replicaResponseConn) CloseWrite() error {
+internal/edge/replicaprober.go:45:func (replicaRealClock) Now() time.Time { return time.Now() }
+internal/edge/replicaprober.go:46:func (replicaRealClock) Ticker(d time.Duration) replicaProbeTicker {
+internal/edge/replicaprober.go:49:func (replicaRealClock) Timeout(ctx context.Context, d time.Duration) (context.Context, context.CancelFunc) {
+internal/edge/replicaprober.go:55:func (t replicaRealTicker) C() <-chan time.Time { return t.Ticker.C }
+internal/edge/replicaprober.go:57:type replicaProbeFunc func(context.Context, string, string) (replicas.Copy, error)
+internal/edge/replicaprober.go:71: count upstreamState
+internal/edge/replicaprober.go:86:func newReplicaProber(hub *TunnelHub, probe replicaProbeFunc, clock replicaProbeClock) *replicaProber {
+internal/edge/replicaprober.go:98:func (p *replicaProber) Sync(routes []registry.Route) {
+internal/edge/replicaprober.go:152:func sameReplicaJob(j *replicaJob, rt registry.Route) bool {
+internal/edge/replicaprober.go:156:func (p *replicaProber) reset(j *replicaJob, conn *tunnelConn, reason string) {
+internal/edge/replicaprober.go:158: j.count = upstreamState{}
+internal/edge/replicaprober.go:161: j.sample = replicas.Copy{Host: j.key.host, Account: j.route.Account, App: j.route.App, Fleet: fleet, Box: j.key.box, Incarnation: j.key.incarnation, AssignmentRevision: j.route.ReplicaRevision, State: "unknown", Reason: reason}
+internal/edge/replicaprober.go:163: j.sample.State = "down"
+internal/edge/replicaprober.go:166:func (p *replicaProber) connection(j *replicaJob) *tunnelConn {
+internal/edge/replicaprober.go:175: j.sample.State, j.sample.Reason = "down", replicaDisconnected
+internal/edge/replicaprober.go:179:func (p *replicaProber) run(j *replicaJob) {
+internal/edge/replicaprober.go:196: go func() {
+internal/edge/replicaprober.go:218: // its successor; readers already exclude the closed connection.
+internal/edge/replicaprober.go:227:func (p *replicaProber) record(j *replicaJob, conn *tunnelConn, c replicas.Copy, err, cause error) {
+internal/edge/replicaprober.go:247: current.count = upstreamState{}
+internal/edge/replicaprober.go:248: current.sample.Healthy = false
+internal/edge/replicaprober.go:249: current.sample.State, current.sample.Reason = "unknown", replicaStale
+internal/edge/replicaprober.go:255: current.count = upstreamState{}
+internal/edge/replicaprober.go:263: if !c.Healthy {
+internal/edge/replicaprober.go:272: current.sample.Healthy = current.count.up
+internal/edge/replicaprober.go:275: current.sample.State, current.sample.Reason = "running", reason
+internal/edge/replicaprober.go:277: current.sample.State = "unknown"
+internal/edge/replicaprober.go:280: current.sample.State, current.sample.Reason = "failed", replicaFailed
+internal/edge/replicaprober.go:284:func replicaIdentityMatches(j *replicaJob, c replicas.Copy) bool {
+internal/edge/replicaprober.go:290:func replicaEvidenceMatches(j *replicaJob, c replicas.Copy) bool {
+internal/edge/replicaprober.go:293: if c.Generation == 0 || c.Version == "" || err != nil || len(digest) != 32 || c.State != "running" || c.WorkersRunning < 0 || c.WorkersDeclared < c.WorkersRunning {
+internal/edge/replicaprober.go:304:func (p *replicaProber) snapshotLocked(rt registry.Route) replicas.Snapshot {
+internal/edge/replicaprober.go:308: // FleetBoxes is already canonical and sorted. A single-host read visits
+internal/edge/replicaprober.go:318:func (p *replicaProber) snapshots() map[string]replicas.Snapshot {
+internal/edge/replicaprober.go:327:func (p *replicaProber) Snapshot(host string) replicas.Snapshot {
+internal/edge/replicaprober.go:336:func (p *replicaProber) Live(host string) []replicas.Copy {
+internal/edge/replicaprober.go:339: if c.Healthy && !c.ObservedAt.IsZero() && p.clock.Now().Sub(c.ObservedAt) <= replicaProbeFail*replicaProbeInterval+replicaProbeTimeout {
+internal/edge/replicaprober.go:348:func (p *replicaProber) Eject(host, box string) {
+internal/edge/replicaprober.go:352: j.count = upstreamState{}
+internal/edge/replicaprober.go:353: j.sample.Healthy = false
+internal/edge/replicaprober.go:354: j.sample.State, j.sample.Reason = "down", replicaDisconnected
+internal/edge/replicaprober.go:357:func (p *replicaProber) Stop() {
+internal/edge/replicaprober.go:371:func (h *TunnelHub) probeReplica(ctx context.Context, channel, host string) (replicas.Copy, error) {
+internal/edge/replicaprober.go:399:func (e *Edge) replicaProberForRouting() *replicaProber {
+internal/edge/replicaprober.go:407:func (e *Edge) syncReplicaProbes(routes []registry.Route) {
+internal/edge/replicaprober.go:418:func (e *Edge) ReplicaSnapshots() map[string]replicas.Snapshot {
+internal/edge/replicaprober.go:427:func (e *Edge) stopReplicaProbes() {
+ 3430 // member (run spec §5.3).
+ 3431 func (a *Service) beginStopLocked(e *actEntry, why string) {
+ 3432 // Held legs end with the stop, in this critical section, before the
+ 3433 // stop goroutine starts (edge-held streams spec §3.2): a leg is either
+ 3434 // registered now and cancelled here, or admitted later and refused.
+ 3435 a.cancelHeldLegsLocked(e, 0)
+ 3436 if why == StopLeaseLost || (e.state == actAwake && servingError(e) != nil) {
+ 3437 a.latchHALossLocked(e)
+ 3438 }
+ 3439
+ 3440 // A hold canary's settle ends with an intentional stop, before anything
+ 3441 // is stopped (zero-downtime spec §6.4). A process that already exited
+ 3442 // died of its build, and its stop must not hide that.
+ 3443 if e.settleCancel != nil && (e.proc == nil || !e.proc.Exited()) {
+ 3444 e.settleCancel()
+ 3445 }
+ 3446 // The same for a planned first wake's observation (spec §6.4): an
+ 3447 // intentional stop ends it and records nothing. A stop that began
+ 3448 // because the child died on its own (unexpectedExit), or of a process
+ 3449 // that has already exited, leaves it to read the exit as the build's.
+ 3450 if e.firstWatch != nil && !e.unexpectedExit && (e.proc == nil || !e.proc.Exited()) {
+ 3451 e.firstWatch()
+ 3452 }
+ 3453 e.state = actStopping
+ 3454 e.stopWhy = why
+ 3455 for _, h := range []*cmdHold{e.cmd, e.tty} {
+ 3456 if h != nil && h.cancelPrepare != nil {
+ 3457 h.cancelPrepare() // a stop interrupts a run's or a session's download
+ 3458 }
+ 3459 }
+ 3460 // A release command this entry owns is cancelled, so runRelease stops
+ 3461 // and settles its unit at once (Group R, INV-R1). The stop keeps the
+ 3462 // lease until the record is proven gone (releasable, finishStop).
+ 3463 if op := a.releaseOps[e.host]; op != nil && op.owner == e {
+ 3464 op.cancel(fmt.Errorf("%w (%s)", errSwapStopped, why))
+ 3465 }
+ 3466 e.stopped = make(chan struct{})
+ 3467 go a.stop(e)
+ 3468 }
+ 3469
+ 3470 // installProcLocked is the one place a process is installed on an entry:
+ 3471 // its process, its generation and, when rep is non-nil, the lease's
+ 3472 // replica (nil keeps the entry's own: a swap's successor and a worker's
+ 3473 // respawn run under the lease the wake took). Every install path comes
+ 3474 // through here: a wake (wake), a hold's pinned wake and a resident's
+ 3475 // restart (both wakes), a swap's successor (swapOverlap) and a worker's
+ 3476 // respawn and a recovery probe's install. For a rootfs row the lease
+ 3477 // watch is installed here too, before the function returns, so no fence,
+ 3478 // shutdown or queued-restart transition the caller runs after it can leave
+ 3479 // a rootfs process unwatched (Plan 3 Task 8, C7: one invariant in one
+ 3480 // place). Every rootfs row, resident or hibernating, is watched (Plan 6
+ 3481 // Task 7a, Call A1), so a run or session on either is reached at the
+ 3482 // lease's loss; the watch's resident actions stay a resident's. The watch
+ 3483 // is held until finishStop, after the stop's termination proof, closes it.
+ 3484 // TestResidentProcessInstallsGoThroughOnePlace refuses any other write of
+ 3485 // these fields. The caller holds a.mu.
+ 3486 func (a *Service) installProcLocked(e *actEntry, rep Rep, proc Proc, g Gen) {
+ 3487 if rep != nil {
+ 3488 e.rep = rep
+ 3489 }
+ 3490 if e.gen.N != g.N {
+ 3491 // The generation that stops being current takes its held legs with
+ 3492 // it, before the switch returns: a swap's successor installs here,
+ 3493 // ahead of genRetired and the retiring generation's drain
+ 3494 // (edge-held streams spec §3.2).
+ 3495 a.cancelHeldLegsLocked(e, e.gen.N)
+ 3496 }
+ 3497 e.proc = proc
+ 3498 e.gen = g
+ 3499 if e.lifecycleDone == nil {
+ 3500 e.lifecycleDone = make(chan struct{})
+ 3501 }
+ 3502 if e.route.Rootfs() {
+ 3503 a.watchResidentLeaseLocked(e)
+ 3504 }
+ 3505 }
+ 3506
+ 3507 // recordCurrentTierLocked records the tier the entry's current generation
+ 3508 // runs at, when it is still generation n (a swap's captured tier). It is
+ 3509 // the one write of an entry's generation besides installProcLocked, and
+ 3510 // it installs nothing: it changes only Gen.Tier (the install guard holds it
+ 3511 // to that). The caller holds a.mu.
+ 3512 func recordCurrentTierLocked(e *actEntry, n uint64, tier cgroup.Limit) {
+ 3513 if e.gen.N == n {
+ 3514 e.gen.Tier = tier
+ 3515 }
+ 3516 }
+ 3517
+ 3518 // Owns reports whether host has a live entry in ANY state — waking,
+ 3519 // awake, or stopping. This is the external-socket advisory's predicate
+ 3520 // (issue #17): while an entry exists, whatever is serving the host's
+ 3521 // socket is this activator's own child — possibly still binding its
+ 3522 // listener, or draining SIGTERM — so any-state presence, not awake-only,
+ 3523 // is what keeps the advisory from calling the activator's own children
+ 3524 // strays.
+ 3525 func (a *Service) Owns(host string) bool {
+internal/instancectl/rootfs_stop_test.go:24: if _, err := c.StartRootfs(ctx, f.host, 5, cgroup.TierChildren.MemoryMax, f.img(release.ProcessWeb)); err != nil {
+internal/instancectl/rootfs_stop_test.go:27: if _, err := c.StartRootfsWorker(ctx, f.host, "jobs", cgroup.TierChildren.MemoryMax, f.img("jobs")); err != nil {
+internal/instancectl/rootfs_test.go:59: // daemon-reload; loadedModel makes MemoryDenyWriteExecute follow it
+internal/instancectl/rootfs_test.go:221: return "InvocationID=" + sh.invocations[unit] + "\nSlice=" + SliceName(f.host) + "\nControlGroup=/carlos.slice/carlos-instances.slice/" + SliceName(f.host) + "/" + unit + "\nMemoryDenyWriteExecute=" + f.mdweLocked(unit) + "\n", true
+internal/instancectl/rootfs_test.go:229:// mdweLocked is the model's effective MemoryDenyWriteExecute for unit: with
+internal/instancectl/rootfs_test.go:260: max := strconv.FormatInt(cgroup.TierChildren.MemoryMax, 10)
+internal/instancectl/rootfs_test.go:261: high := strconv.FormatInt(cgroup.HighOf(cgroup.TierChildren.MemoryMax), 10)
+internal/instancectl/rootfs_test.go:262: tier := "MemoryMax=" + max + "\nMemoryHigh=" + high + "\nMemorySwapMax=" + max + "\n"
+internal/instancectl/rootfs_test.go:267: return block + "\nSlice=carlos-instances.slice\nNeedDaemonReload=no\nMemoryMax=infinity\nMemoryHigh=infinity\nMemorySwapMax=infinity\nCPUWeight=100\nCPUQuotaPerSecUSec=infinity\nIOWeight=100\n"
+internal/instancectl/rootfs_test.go:350: q := url.Values{"host": {f.host}, "role": {string(role)}, "memory_max": {strconv.FormatInt(cgroup.TierChildren.MemoryMax, 10)},
+internal/instancectl/rootfs_test.go:359: q := url.Values{"host": {f.host}, "memory_max": {strconv.FormatInt(cgroup.TierChildren.MemoryMax, 10)},
+internal/instancectl/rootfs_test.go:483:// MemoryDenyWriteExecute=no when jit.
+internal/instancectl/rootfs_test.go:493: f.ctl.set(rootfsPostStartShow+" "+unit, "InvocationID="+strings.Repeat("ab", 16)+"\nSlice="+SliceName(f.host)+"\nControlGroup=/carlos.slice/carlos-instances.slice/"+SliceName(f.host)+"/"+unit+"\nMemoryDenyWriteExecute="+mdwe+"\n")
+internal/instancectl/rootfs_test.go:874: if strings.Contains(string(got), "MemoryMax=") {
+internal/instancectl/rootfs_test.go:875: t.Error("a worker drop-in caps memory; workers share the host slice's tier")
+internal/instancectl/rootfs_test.go:923: q := url.Values{"host": {f.host}, "role": {"worker"}, "worker": {"jobs"}, "memory_max": {strconv.FormatInt(cgroup.TierChildren.MemoryMax, 10)}, "invocation": {"x"}}
+internal/instancectl/rootfs_test.go:1076: f.ctl.set(rootfsPostStartShow, "InvocationID="+strings.Repeat("ab", 16)+"\nSlice=system.slice\nControlGroup=/system.slice/"+unit+"\nMemoryDenyWriteExecute=yes\n")
+internal/instancectl/rootfs_test.go:1087: f.ctl.set(rootfsPostStartShow+" "+worker, "InvocationID="+strings.Repeat("ab", 16)+"\nSlice=system.slice\nControlGroup=/system.slice/"+worker+"\nMemoryDenyWriteExecute=yes\n")
+internal/instancectl/rootfs_test.go:1102: f.ctl.set(rootfsPostStartShow+" "+worker, "InvocationID="+strings.Repeat("ab", 16)+"\nSlice="+SliceName(f.host)+"\nControlGroup=/carlos.slice/carlos-instances.slice/"+SliceName(f.host)+"/../"+worker+"\nMemoryDenyWriteExecute=yes\n")
+internal/instancectl/rootfs_test.go:1417: f.ctl.set(rootfsPostStartShow+" "+worker(f), "InvocationID="+strings.Repeat("ab", 16)+"\nSlice=system.slice\nControlGroup=/system.slice/"+worker(f)+"\nMemoryDenyWriteExecute=yes\n")
+internal/instancectl/rootfs_test.go:1725: if strings.HasPrefix(c, "set-property") && strings.Contains(c, "MemoryMax=") {
+internal/instancectl/rootfs_test.go:1731: // Populated: the generation start leaves the limit alone.
+internal/instancectl/rootfs_test.go:1738: t.Error("a generation start lowered a populated slice's limit (the swap's raised parent)")
+internal/instancectl/rootfs_test.go:1755: max := strconv.FormatInt(cgroup.TierChildren.MemoryMax, 10)
+internal/instancectl/rootfs_test.go:1756: withTier := strings.SplitN(rootfsViewAnswer(f.host, unit, true), "\n\n", 2)[0] + "\n\nSlice=carlos-instances.slice\nNeedDaemonReload=no\nMemoryMax=" + max + "\nMemoryHigh=" + strconv.FormatInt(cgroup.HighOf(cgroup.TierChildren.MemoryMax), 10) + "\nMemorySwapMax=" + max + "\nCPUWeight=" + strconv.Itoa(sh.CPUWeight) + "\nCPUQuotaPerSecUSec=" + cpuQuotaShown(sh.CPUQuotaPercent) + "\nIOWeight=" + strconv.Itoa(sh.IOWeight) + "\n"
+internal/instancectl/rootfs_test.go:1783:// MemoryDenyWriteExecute through root's per-start drop-in, in every role;
+internal/instancectl/rootfs_test.go:1796:// R11: a session of a jit release runs without MemoryDenyWriteExecute, like
+internal/instancectl/rootfs_test.go:1861: // MemoryDenyWriteExecute disagrees with the release is stopped, 502.
+internal/instancectl/rootfs_test.go:1867: if status, body := f.startRole(t, role); status != 502 || !strings.Contains(body, "MemoryDenyWriteExecute") {
+internal/instancectl/rootfs_test.go:1874:// MemoryDenyWriteExecute does not match the release's jit is stopped and
+internal/instancectl/rootfs_test.go:1884: f.ctl.set(rootfsPostStartShow, "InvocationID="+strings.Repeat("ab", 16)+"\nSlice="+SliceName(f.host)+"\nControlGroup=/carlos.slice/carlos-instances.slice/"+SliceName(f.host)+"/"+unit+"\nMemoryDenyWriteExecute="+c.effective+"\n")
+internal/instancectl/rootfs_test.go:1886: if status != 502 || !strings.Contains(body, "MemoryDenyWriteExecute") {
+internal/instancectl/rootfs_test.go:1921:// systemd keeps the unit loaded with MemoryDenyWriteExecute=no until a
+internal/instancectl/rootfs_test.go:1941:// starts, and pass the post-start check with MemoryDenyWriteExecute=yes.
+internal/instancectl/rootfs_test.go:1966: t.Errorf("the non-jit start runs with MemoryDenyWriteExecute=%s", got)
+internal/instancectl/rootfs_test.go:1970:// mdwe is the model's effective MemoryDenyWriteExecute for unit now.
+internal/instancectl/rootfs_test.go:2093: inv, err := c.StartRootfs(ctx, f.host, 0, cgroup.TierChildren.MemoryMax, f.img(release.ProcessWeb))
+internal/instancectl/rootfs_test.go:2098: if inv, err := c.StartRootfs(ctx, f.host, 3, cgroup.TierChildren.MemoryMax, f.img(release.ProcessWeb)); err != nil || len(inv.InvocationID) != 32 {
+internal/instancectl/rootfs_test.go:2102: if inv, err := c.StartRootfsWorker(ctx, f.host, "jobs", cgroup.TierChildren.MemoryMax, f.img("jobs")); err != nil || len(inv.InvocationID) != 32 {
+internal/instancectl/rootfs_test.go:2117: inv, err = c.CmdRootfs(ctx, f.host, cgroup.TierChildren.MemoryMax, StagedImage{Path: f.imagePath, Version: rootfsVer, Digest: f.digest, Argv: []string{"bin/rails", "db:migrate:status"}})
+internal/instancectl/rootfs_test.go:2130: if _, err := c.StartRootfs(ctx, f.host, 0, cgroup.TierChildren.MemoryMax, bad); !errors.Is(err, ErrStagedImage) {
+internal/instancectl/rootfs_test.go:2134: if _, err := c.StartRootfsWorker(ctx, f.host, "jobs", cgroup.TierChildren.MemoryMax, bad); !errors.Is(err, ErrStagedImage) {
+internal/instancectl/rootfs_test.go:2141: if _, err := c.CmdRootfs(ctx, f.host, cgroup.TierChildren.MemoryMax, bad); !errors.Is(err, ErrStagedImage) {
+internal/instancectl/rootfs_test.go:2145: if _, err := c.StartRootfs(ctx, f.host, 0, cgroup.TierChildren.MemoryMax, StagedImage{Path: f.imagePath, Version: "../v1", Digest: f.digest, Process: release.ProcessWeb}); err == nil || errors.Is(err, ErrStagedImage) {
+internal/instancectl/rootfs_test.go:2177:MemoryMax=1073741824
+internal/instancectl/rootfs_test.go:2178:MemoryHigh=966367638
+internal/instancectl/rootfs_test.go:2179:MemorySwapMax=1073741824
+internal/instancectl/rootfs_test.go:2202: if JITDropIn != "# Written by carlos instance-control for one start of a release that declares jit (rootfs apps design §5.11); removed when the unit stops.\n[Service]\nMemoryDenyWriteExecute=no\n" {
+internal/instancectl/rootfs_test.go:2243: return "InvocationID=" + strings.Repeat("ab", 16) + "\nSlice=system.slice\nControlGroup=/system.slice/" + unit + "\nMemoryDenyWriteExecute=no\n"
+internal/instancectl/rootfs_test.go:2266: t.Error("no reload owed after a stale MemoryDenyWriteExecute")
+internal/instancectl/rootfs_test.go:2307: _, err := f.client(t).StartRootfs(context.Background(), f.host, 2, cgroup.TierChildren.MemoryMax, f.img(release.ProcessWeb))
+internal/instancectl/rootfs_test.go:2311: _, err := f.client(t).StartRootfsWorker(context.Background(), f.host, "jobs", cgroup.TierChildren.MemoryMax, f.img("jobs"))
+internal/instancectl/rootfs_test.go:2392: if err := os.WriteFile(path, []byte(WorkerDropIn(f.host, "jobs", cgroup.TierChildren)+"MemoryMax=1\n"), 0o644); err != nil {
+internal/instancectl/rootfs_test.go:3108: if status, body := f.post(t, "/tty", url.Values{"host": {f.host}, "memory_max": {strconv.FormatInt(cgroup.TierChildren.MemoryMax, 10)}, "process": {release.ProcessConsole}}); status != 400 {
+internal/instancectl/rootfs_test.go:3277: inv, err := c.TTYRootfs(ctx, f.host, cgroup.TierChildren.MemoryMax, img)
+internal/instancectl/rootfs_test.go:3286: if inv, err := c.TTYRootfs(ctx, f.host, cgroup.TierChildren.MemoryMax, StagedImage{Path: f.imagePath, Version: rootfsVer, Digest: f.digest, Argv: []string{"bin/rails", "console"}}); err != nil || len(inv.InvocationID) != 32 {
+internal/instancectl/rootfs_test.go:3294: if _, err := c.TTYRootfs(ctx, f.host, cgroup.TierChildren.MemoryMax, bad); !errors.Is(err, ErrStagedImage) {
+internal/instancectl/rootfs_test.go:3299: if _, err := c.TTYRootfs(ctx, f.host, cgroup.TierChildren.MemoryMax, web); !errors.Is(err, ErrStagedImage) {
+internal/instancectl/rootfs_test.go:3304: if _, err := c.TTYRootfs(ctx, f.host, cgroup.TierChildren.MemoryMax, both); !errors.Is(err, ErrStartRefused) {
+internal/instancectl/rootfs.go:37:// host's slice (C5) and gave it the MemoryDenyWriteExecute the release's
+
+exec
+/bin/bash -lc "nl -ba internal/edge/replicaprober.go | sed -n '20,36p;227,303p;336,347p'; nl -ba internal/edge/replicaprobe.go | sed -n '1,240p'; nl -ba internal/edge/replicaproxy.go | sed -n '75,122p'" in /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-stateless-replicas-scale
+ succeeded in 0ms:
+ 20 replicaProbeFail = 2
+ 21 replicaProbeRise = 2
+ 22 // copy SR-3-C03 (provisional)
+ 23 replicaFailed = "this copy did not pass its health check"
+ 24 // copy SR-3-C04 (provisional)
+ 25 replicaDisconnected = "this box's tunnel is disconnected"
+ 26 // copy SR-3-C05 (provisional)
+ 27 replicaWaiting = "waiting for this copy to pass its health check"
+ 28 // copy SR-3-C06 (provisional)
+ 29 replicaStale = "this health answer belongs to an earlier instance or assignment"
+ 30 )
+ 31
+ 32 // replicaProbeClock controls cadence and deadlines together. Tests advance both
+ 33 // without sleeping through 64 independent timeout windows.
+ 34 type replicaProbeClock interface {
+ 35 Now() time.Time
+ 36 Ticker(time.Duration) replicaProbeTicker
+ 227 func (p *replicaProber) record(j *replicaJob, conn *tunnelConn, c replicas.Copy, err, cause error) {
+ 228 p.mu.Lock()
+ 229 defer p.mu.Unlock()
+ 230 current := p.jobs[replicaSlot{j.key.host, j.key.box}]
+ 231 if current != j || j.ctx.Err() != nil {
+ 232 return
+ 233 }
+ 234 if p.hub.probeConnection(j.channel) != conn || conn.generation != j.conn.generation {
+ 235 p.connection(j)
+ 236 return
+ 237 }
+ 238 if errors.Is(cause, context.Canceled) || (cause == nil && errors.Is(err, context.Canceled)) {
+ 239 return
+ 240 }
+ 241 reason := ""
+ 242 if err != nil || cause != nil {
+ 243 reason = replicaFailed
+ 244 } else {
+ 245 identityOK := replicaIdentityMatches(j, c) && p.hub.matchReplicaBoot(conn, c.BootID, false)
+ 246 if !identityOK || !replicaEvidenceMatches(j, c) {
+ 247 current.count = upstreamState{}
+ 248 current.sample.Healthy = false
+ 249 current.sample.State, current.sample.Reason = "unknown", replicaStale
+ 250 return
+ 251 }
+ 252 p.hub.matchReplicaBoot(conn, c.BootID, true)
+ 253 old := current.evidence
+ 254 if old.Generation != c.Generation {
+ 255 current.count = upstreamState{}
+ 256 }
+ 257 current.evidence = c
+ 258 // Assignment propagation can lag in either direction. Sync owns
+ 259 // membership; this observation describes the same copy's health.
+ 260 c.AssignmentRevision = j.route.ReplicaRevision
+ 261 c.Socket = ""
+ 262 current.sample = c
+ 263 if !c.Healthy {
+ 264 reason = replicaFailed
+ 265 }
+ 266 }
+ 267 var failure error
+ 268 if reason != "" {
+ 269 failure = errors.New(reason)
+ 270 }
+ 271 current.count.recordProbe(failure, replicaProbeFail, replicaProbeRise, p.clock.Now())
+ 272 current.sample.Healthy = current.count.up
+ 273 current.sample.ObservedAt = p.clock.Now()
+ 274 if current.count.up {
+ 275 current.sample.State, current.sample.Reason = "running", reason
+ 276 } else {
+ 277 current.sample.State = "unknown"
+ 278 current.sample.Reason = replicaWaiting
+ 279 if current.count.fails >= replicaProbeFail {
+ 280 current.sample.State, current.sample.Reason = "failed", replicaFailed
+ 281 }
+ 282 }
+ 283 }
+ 284 func replicaIdentityMatches(j *replicaJob, c replicas.Copy) bool {
+ 285 r := j.route
+ 286 fleet, _ := registry.FleetPlacement(r.Region)
+ 287 return c.Host == r.Host && c.Account == r.Account && c.App == r.App && c.Fleet == fleet && c.Box == j.key.box && c.Incarnation == j.key.incarnation && c.BootID != ""
+ 288 }
+ 289
+ 290 func replicaEvidenceMatches(j *replicaJob, c replicas.Copy) bool {
+ 291 old := j.evidence
+ 292 digest, err := hex.DecodeString(c.Digest)
+ 293 if c.Generation == 0 || c.Version == "" || err != nil || len(digest) != 32 || c.State != "running" || c.WorkersRunning < 0 || c.WorkersDeclared < c.WorkersRunning {
+ 294 return false
+ 295 }
+ 296 // Each box reports its own serving build; per-host deployment stamps
+ 297 // cannot describe the mixed builds in a rolling deployment.
+ 298 if old.BootID != "" && (old.BootID != c.BootID || c.Generation < old.Generation || (c.Generation == old.Generation && (c.Version != old.Version || c.Digest != old.Digest))) {
+ 299 return false
+ 300 }
+ 301 return true
+ 302 }
+ 303
+ 336 func (p *replicaProber) Live(host string) []replicas.Copy {
+ 337 var live []replicas.Copy
+ 338 for _, c := range p.Snapshot(host).Copies {
+ 339 if c.Healthy && !c.ObservedAt.IsZero() && p.clock.Now().Sub(c.ObservedAt) <= replicaProbeFail*replicaProbeInterval+replicaProbeTimeout {
+ 340 live = append(live, c)
+ 341 }
+ 342 }
+ 343 return live
+ 344 }
+ 345
+ 346 // Eject is for a pre-dispatch missing channel or a closed tunnel only. An
+ 347 // ordinary dispatched request error must be left to the health probes.
+ 1 package edge
+ 2
+ 3 import (
+ 4 "context"
+ 5 "encoding/json"
+ 6 "io"
+ 7 "net"
+ 8 "net/http"
+ 9 "time"
+ 10
+ 11 "github.com/carlosframework/platform/internal/registry"
+ 12 "github.com/carlosframework/platform/internal/replicas"
+ 13 "github.com/carlosframework/platform/internal/tunnelclient"
+ 14 "github.com/carlosframework/platform/internal/unixdial"
+ 15 )
+ 16
+ 17 const replicaProbePath = "/__carlos/replica-probe"
+ 18 const replicaProbeTimeout = time.Second
+ 19
+ 20 // ReplicaHealth is the hub's current assignment-scoped health view.
+ 21 type ReplicaHealth interface {
+ 22 Snapshot(host string) replicas.Snapshot
+ 23 }
+ 24
+ 25 type copyProbeSource interface {
+ 26 ProbeCopy(context.Context, string) (replicas.Copy, error)
+ 27 }
+ 28
+ 29 func (e *Edge) serveReplicaProbe(w http.ResponseWriter, r *http.Request, host string, rt registry.Route, authenticated bool) {
+ 30 w.Header().Set("Cache-Control", "no-store")
+ 31 if !authenticated || r.Method != http.MethodGet || r.URL.RawQuery != "" {
+ 32 w.WriteHeader(http.StatusNotFound)
+ 33 return
+ 34 }
+ 35 source, ok := e.act.(copyProbeSource)
+ 36 if !ok || rt.Host != host || rt.Kind != "instance" || rt.FleetBoxes == "" || !rt.ReplicaContains(e.box) || rt.Hibernate || rt.HA {
+ 37 UnavailableHeader(w, "replica-probe-route", 2)
+ 38 return
+ 39 }
+ 40 ctx, cancel := context.WithTimeout(r.Context(), replicaProbeTimeout)
+ 41 defer cancel()
+ 42 initial, err := source.ProbeCopy(ctx, host)
+ 43 if err != nil || !e.replicaCopyMatches(initial, rt) {
+ 44 UnavailableHeader(w, "replica-probe-copy", 2)
+ 45 return
+ 46 }
+ 47 // A held leg is cancelled on stop or generation switch, without keeping
+ 48 // the instance awake or entering request accounting. Check awake first
+ 49 // so a sleeping or waking copy never enters the held-leg wait loop.
+ 50 leg, err := e.act.AdmitHeldLeg(ctx, rt)
+ 51 if err != nil {
+ 52 UnavailableHeader(w, "replica-probe-leg", 2)
+ 53 return
+ 54 }
+ 55 defer leg.Done()
+ 56 c, err := source.ProbeCopy(leg.Context(), host)
+ 57 if err != nil || !e.replicaCopyMatches(c, rt) || c.Generation != initial.Generation || c.Socket != initial.Socket {
+ 58 UnavailableHeader(w, "replica-probe-changed", 2)
+ 59 return
+ 60 }
+ 61 transport := &http.Transport{DisableKeepAlives: true, DisableCompression: true,
+ 62 DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ 63 return unixdial.Checked(ctx, &net.Dialer{}, c.Socket)
+ 64 }}
+ 65 defer transport.CloseIdleConnections()
+ 66 probe, err := http.NewRequestWithContext(leg.Context(), http.MethodGet, "http://"+host+"/", nil)
+ 67 if err != nil {
+ 68 UnavailableHeader(w, "replica-probe-request", 2)
+ 69 return
+ 70 }
+ 71 // RoundTrip never follows redirects. A fresh request carries no visitor
+ 72 // credentials or probe marker, and bypasses every edge gate and cache.
+ 73 resp, probeErr := transport.RoundTrip(probe)
+ 74 if resp != nil {
+ 75 _, _ = io.CopyN(io.Discard, resp.Body, 4<<10)
+ 76 _ = resp.Body.Close()
+ 77 c.Healthy = probeErr == nil && replicas.HealthyStatus(resp.StatusCode)
+ 78 }
+ 79 after, err := source.ProbeCopy(leg.Context(), host)
+ 80 if err != nil || leg.Context().Err() != nil || !e.replicaCopyMatches(after, rt) || after.Generation != c.Generation || after.Socket != c.Socket || after.BootID != c.BootID || after.Version != c.Version || after.Digest != c.Digest {
+ 81 UnavailableHeader(w, "replica-probe-after", 2)
+ 82 return
+ 83 }
+ 84 if !c.Healthy {
+ 85 c.Reason = replicaFailed
+ 86 }
+ 87 c.ObservedAt = time.Now()
+ 88 w.Header().Set("Content-Type", "application/json")
+ 89 _ = json.NewEncoder(w).Encode(c)
+ 90 }
+ 91
+ 92 func (e *Edge) replicaCopyMatches(c replicas.Copy, rt registry.Route) bool {
+ 93 fleet, ok := registry.FleetPlacement(rt.Region)
+ 94 return ok && c.Fleet == fleet && c.Host == rt.Host && c.Account != "" && c.Account == rt.Account && c.App != "" && c.App == rt.App && c.Box == e.box && rt.ReplicaContains(c.Box) && c.Incarnation == rt.ReplicaIncarnation && c.AssignmentRevision == rt.ReplicaRevision && c.State == "running" && c.BootID != "" && c.Generation != 0 && c.Version != "" && c.Digest != "" && c.Socket != ""
+ 95 }
+ 96
+ 97 // The context mark alone also accompanies ordinary visitor traffic.
+ 98 func replicaProbeAuthenticated(r *http.Request) bool {
+ 99 return tunnelclient.FromTunnel(r.Context()) && r.Header.Get(tunnelclient.ReplicaProbeHeader) == "1"
+ 100 }
+ 75 }()
+ 76 if len(live) == 0 {
+ 77 return nil, errReplicaUnavailable
+ 78 }
+ 79 start := (t.cursor.Add(1) - 1) % uint64(len(live))
+ 80 last := errReplicaUnavailable
+ 81 attempts := 0
+ 82 var dispatched, anyDispatched bool
+ 83 var started atomic.Bool
+ 84 for i := 0; i < len(live); i++ {
+ 85 if err := req.Context().Err(); err != nil {
+ 86 return nil, err
+ 87 }
+ 88 candidate := live[(int(start)+i)%len(live)]
+ 89 if i > 0 {
+ 90 stillLive := false
+ 91 for _, c := range t.p.Live(t.host) {
+ 92 if c.Box == candidate.Box && c.Incarnation == candidate.Incarnation {
+ 93 stillLive = true
+ 94 break
+ 95 }
+ 96 }
+ 97 if !stillLive {
+ 98 continue
+ 99 }
+ 100 }
+ 101 if i > 0 && dispatched && body != nil {
+ 102 if req.GetBody == nil {
+ 103 return nil, &replicaUnrepeatedError{last}
+ 104 }
+ 105 next, err := req.GetBody()
+ 106 if err != nil {
+ 107 return nil, err
+ 108 }
+ 109 body = replicaBody(next)
+ 110 owned = false
+ 111 }
+ 112 box := candidate.Box
+ 113 attempts++
+ 114 if o := outcomeFrom(req); o != nil {
+ 115 o.replicaBox = box
+ 116 o.replicaAttempts = attempts
+ 117 }
+ 118 // Only a replayable read with another live candidate gets a header
+ 119 // timer. Slow writes and the last attempt retain legacy behavior.
+ 120 canTimeOut := false
+ 121 if replicas.RetryAllowed(req.Method, true, started.Load()) && (body == nil || req.GetBody != nil) {
+ 122 current := t.p.Live(t.host)
+
+exec
+/bin/bash -lc "rg -n 'MemoryMax|Limit|limit|tier' internal/instancectl/rootfs.go; rg -n 'cmdLimit|CmdLimit|MemoryMax|512|256' internal/instancectl/*go | rg -v '_test' | head -90; nl -ba internal/activator/size.go | head -240; nl -ba internal/activator/rootfsrelease.go | sed -n '170,205p;300,350p'" in /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-stateless-replicas-scale
+ succeeded in 0ms:
+74: rootfsViewShow = "show -p Slice,RootImage,NeedDaemonReload,MemoryMax,MemoryHigh,MemorySwapMax,CPUWeight,CPUQuotaPerSecUSec,IOWeight"
+448:// and live binds (rootfs apps plan 2). The tier is this start's, every
+450:func RootfsGenDropIn(host string, n uint64, tier cgroup.Limit) string {
+452: "StandardOutput=file:" + GenLogSocket(host, n) + "\n" + tierLines(tier)
+458:// lines: a worker shares the host slice's tier (spec §5.4), which is why
+459:// the tier it is handed is not written.
+460:func WorkerDropIn(host, name string, _ cgroup.Limit) string {
+484:// gen (withTier) the tier's memory lines. tierSet reports whether the
+487:func (s *Server) rootfsView(ctx context.Context, host, unit, image string, tier cgroup.Limit, withTier bool) (slice string, applied, tierSet bool) {
+496: max := strconv.FormatInt(tier.MemoryMax, 10)
+497: applied = applied && m["MemoryMax"] == max && m["MemorySwapMax"] == max && m["MemoryHigh"] == strconv.FormatInt(cgroup.HighOf(tier.MemoryMax), 10)
+500: tierSet = sliceAtTier(parseShow(blocks[1]), tier)
+502: return m["Slice"], applied, tierSet
+626:// never on an ordinary start, wake latency 1 and 2c), the tier, the start,
+728: if _, err := s.writeDropInIfChanged(unit, DropInName, WorkerDropIn(req.host, req.worker, req.tier)); err != nil {
+734: if err := s.writeDropIn(unit, DropInName, RootfsGenDropIn(req.host, req.gen, req.tier)); err != nil {
+746: applied, tierSet := true, false
+748: slice, applied, tierSet = s.rootfsView(ctx, req.host, unit, image, req.tier, withTier)
+758: if slice, applied, tierSet = s.rootfsView(ctx, req.host, unit, image, req.tier, withTier); !applied {
+765: // The tier (Astra R1 finding 5): a gen-0 run start sets the host
+766: // slice's tier, as a cold instance's start does. A generation or a
+768: // the swap's raised limit for two generations.
+769: if req.role == RoleRun && req.gen == 0 || !s.slicePopulated(req.host) && !tierSet {
+770: if err := s.setTier(ctx, req.host, req.tier); err != nil {
+794: s.logf("instance-control: %s: started %s from %s memory.max=%d (prepared in %s, reload %s, start %s)", req.host, unit, launch.Version, req.tier.MemoryMax,
+1021:// drop-in and its reload, the tier rule of a populated slice, start
+1110: // leaves it, so a session is inside the instance's slice and tier.
+1112: s.logf("instance-control: %s: slice populated, leaving its limit to the instance's owner", req.host)
+1113: } else if err := s.setTier(ctx, req.host, req.tier); err != nil {
+1129: s.logf("instance-control: %s: started %s (%s) from %s memory.max=%d", req.host, unit, launch.Process, launch.Version, req.tier.MemoryMax)
+internal/instancectl/demo_build.go:55: out.SHA256 = ""
+internal/instancectl/demo_build.go:59: if err != nil || v.SHA256 != out.SHA256 {
+internal/instancectl/demo_build.go:171: out.SHA256 = ""
+internal/instancectl/demo_snapshot_disk.go:124: "MemoryMax": "268435456", "MemorySwapMax": "0", "TasksMax": "32", "CPUQuotaPerSecUSec": "500ms",
+internal/instancectl/demo_snapshot_client.go:6: "crypto/sha256"
+internal/instancectl/demo_snapshot_client.go:74: digest := res.Header.Get(democlaim.SnapshotSHA256Header)
+internal/instancectl/demo_snapshot_client.go:79: return &demoSnapshotBody{body: res.Body, c: c, in: in, cancel: cancel, ctx: ctx, meta: democlaim.Snapshot{SHA256: digest, Bytes: n}, hash: sha256.New()}, nil
+internal/instancectl/demo_snapshot_client.go:161: if err == io.EOF && (b.read != b.meta.Bytes || hex.EncodeToString(b.hash.Sum(nil)) != b.meta.SHA256) {
+internal/instancectl/sandbox.go:198: state.RunscSHA256 = lock.Platforms["linux-"+runtime.GOARCH].SHA256
+internal/instancectl/stagedexe.go:4: "crypto/sha256"
+internal/instancectl/stagedexe.go:22:// staged build of the attempt, its version and the sha256 the attempt
+internal/instancectl/stagedexe.go:42:// - Its sha256 must be the attempt's digest.
+internal/instancectl/stagedexe.go:50: if !release.ValidVersion(x.Version) || len(x.Digest) != 2*sha256.Size {
+internal/instancectl/stagedexe.go:71: h := sha256.New()
+internal/instancectl/demo_snapshot.go:5: "crypto/sha256"
+internal/instancectl/demo_snapshot.go:264: w.Header().Set(democlaim.SnapshotSHA256Header, meta.SHA256)
+internal/instancectl/demo_snapshot.go:442: SHA256 string `json:"sha256"`
+internal/instancectl/demo_snapshot.go:452: hash := sha256.New()
+internal/instancectl/demo_snapshot.go:457: if err != nil || ctx.Err() != nil || n != meta.Bytes || hex.EncodeToString(hash.Sum(nil)) != meta.SHA256 {
+internal/instancectl/demo_snapshot.go:465: return source, democlaim.Snapshot{SHA256: meta.SHA256, Bytes: meta.Bytes}, nil
+internal/instancectl/gen.go:77: max := strconv.FormatInt(tier.MemoryMax, 10)
+internal/instancectl/gen.go:78: return "MemoryMax=" + max + "\n" +
+internal/instancectl/gen.go:79: "MemoryHigh=" + strconv.FormatInt(cgroup.HighOf(tier.MemoryMax), 10) + "\n" +
+internal/instancectl/gen.go:323: out, err := s.Systemctl(ctx, "show", "-p", "Slice,NeedDaemonReload,MemoryMax,MemoryHigh,MemorySwapMax,CPUWeight,CPUQuotaPerSecUSec,IOWeight", unit, SliceName(host))
+internal/instancectl/gen.go:329: max := strconv.FormatInt(tier.MemoryMax, 10)
+internal/instancectl/gen.go:330: high := strconv.FormatInt(cgroup.HighOf(tier.MemoryMax), 10)
+internal/instancectl/gen.go:332: m["MemoryMax"] == max && m["MemorySwapMax"] == max && m["MemoryHigh"] == high
+internal/instancectl/gen.go:342: max := strconv.FormatInt(tier.MemoryMax, 10)
+internal/instancectl/gen.go:343: high := strconv.FormatInt(cgroup.HighOf(tier.MemoryMax), 10)
+internal/instancectl/gen.go:345: return sl["MemoryMax"] == max && sl["MemorySwapMax"] == max && sl["MemoryHigh"] == high &&
+internal/instancectl/gen.go:472: s.logf("instance-control: %s: started %s memory.max=%d (prepared in %s: staged exe %s, layout %s, drop-in %s, check and tier %s; reload %s, start %s)", req.host, unit, req.tier.MemoryMax,
+internal/instancectl/gen.go:771: if err != nil || !cgroup.ValidParentLimit(cgroup.Limit{MemoryMax: n}) {
+internal/instancectl/gen.go:777: n = small.Limit.MemoryMax
+internal/instancectl/gen.go:784: n = execsandbox.Physical(cgroup.Limit{MemoryMax: n}).MemoryMax
+internal/instancectl/gen.go:789: "MemoryMax="+max, "MemoryHigh="+strconv.FormatInt(cgroup.HighOf(n), 10), "MemorySwapMax="+max); err != nil {
+internal/instancectl/names.go:658:// answer (#256). The agent compares it with its own: both are meant to be
+internal/instancectl/cmd.go:128: s.logf("instance-control: %s: started %s memory.max=%d", req.host, unit, req.tier.MemoryMax)
+internal/instancectl/demo_policy.go:51: out, err := s.Systemctl(ctx, "show", unit, "-p", "PrivateNetwork,NetworkNamespacePath,JoinsNamespaceOf,TemporaryFileSystem,RestrictAddressFamilies,IPAddressDeny,IPAddressAllow,MemoryMax,CPUWeight,CPUQuotaPerSecUSec,IOWeight,Slice")
+internal/instancectl/demo_policy.go:95: out, err = s.Systemctl(ctx, "show", SliceName(host), "-p", "MemoryMax,CPUWeight,CPUQuotaPerSecUSec,IOWeight")
+internal/instancectl/demo_policy.go:108: for k, w := range map[string]string{"MemoryHigh": strconv.FormatInt(cgroup.HighOf(physical.MemoryMax), 10), "MemorySwapMax": strconv.FormatInt(physical.MemoryMax, 10), "TasksMax": "320"} {
+internal/instancectl/demo_policy.go:115: if rb.SliceMemoryMax != physical.MemoryMax || rb.CPUWeight != small.Shares.CPUWeight || rb.CPUQuotaPercent != small.Shares.CPUQuotaPercent || rb.IOWeight != small.Shares.IOWeight {
+internal/instancectl/demo_policy.go:141: limits := map[string]string{"memory.max": strconv.FormatInt(small.Limit.MemoryMax, 10), "cpu.weight": strconv.Itoa(small.Shares.CPUWeight), "io.weight": "default " + strconv.Itoa(small.Shares.IOWeight)}
+internal/instancectl/demo_policy.go:144: limits["memory.max"] = strconv.FormatInt(physical.MemoryMax, 10)
+internal/instancectl/demo_policy.go:145: limits["memory.high"] = strconv.FormatInt(execsandbox.KernelMemoryHigh(cgroup.HighOf(physical.MemoryMax)), 10)
+internal/instancectl/client.go:48: // BuildHeader does not name it (#256); empty skips the comparison,
+internal/instancectl/client.go:69:// serves this release's units with the previous release's code (#256).
+internal/instancectl/size.go:20:// the slice back; it never writes MemoryMax, MemoryHigh or MemorySwapMax
+internal/instancectl/size.go:32:// read, is 0. SliceMemoryMax is for information: /size never writes it.
+internal/instancectl/size.go:34: SliceMemoryMax int64 `json:"slice_memory_max"`
+internal/instancectl/size.go:106: slice, err := s.Systemctl(ctx, "show", "-p", "MemoryMax", "-p", "CPUQuotaPerSecUSec", "-p", "CPUWeight", "-p", "IOWeight", SliceName(host))
+internal/instancectl/size.go:117:// value, infinity included, is 0. MemoryMax=infinity is 0.
+internal/instancectl/size.go:121: SliceMemoryMax: showBytes(sl["MemoryMax"]),
+internal/instancectl/size.go:134:// showBytes is a MemoryMax= value in bytes; infinity, or anything that is
+internal/instancectl/gvisorunit.go:73: p["MemoryMax"] = strconv.FormatInt(physical.MemoryMax, 10)
+internal/instancectl/gvisorunit.go:74: p["MemoryHigh"] = strconv.FormatInt(cgroup.HighOf(physical.MemoryMax), 10)
+internal/instancectl/gvisorunit.go:75: p["MemorySwapMax"] = p["MemoryMax"]
+internal/instancectl/gvisorunit.go:76: p["TasksMax"] = strconv.FormatInt(execsandbox.PhysicalTasks(256), 10)
+internal/instancectl/gvisorunit.go:105: fmt.Fprintf(&b, "TasksMax=%d\nCPUWeight=50\nCPUQuota=50%%\nIOWeight=50\n", execsandbox.PhysicalTasks(256))
+internal/instancectl/gvisorunit.go:270: out, err = s.Systemctl(ctx, "show", SliceName(host), "-p", "MemoryMax,MemoryHigh,MemorySwapMax,TasksMax,CPUWeight,CPUQuotaPerSecUSec,IOWeight")
+internal/instancectl/server.go:178: // its own release (#256). Empty sends no header, which a client of
+internal/instancectl/server.go:186: // ran: that is exactly the stale-service case of #256.
+internal/instancectl/server.go:763: if _, ok := cgroup.SizeOf(cgroup.Limit{MemoryMax: n}); !ok {
+internal/instancectl/server.go:766: req.tier = cgroup.Limit{MemoryMax: n}
+internal/instancectl/server.go:852: max := strconv.FormatInt(tier.MemoryMax, 10)
+internal/instancectl/server.go:854: args := []string{"set-property", "--runtime", SliceName(host), "MemoryMax=" + max, "MemoryHigh=" + strconv.FormatInt(cgroup.HighOf(tier.MemoryMax), 10), "MemorySwapMax=" + max, "CPUWeight=" + strconv.Itoa(sh.CPUWeight), "CPUQuota=" + strconv.Itoa(sh.CPUQuotaPercent) + "%", "IOWeight=" + strconv.Itoa(sh.IOWeight)}
+internal/instancectl/server.go:1018: s.logf("instance-control: %s: started %s memory.max=%d", req.host, unit, req.tier.MemoryMax)
+internal/instancectl/server.go:1486:// is restarted (#256).
+internal/instancectl/rootfs.go:5: "crypto/sha256"
+internal/instancectl/rootfs.go:74: rootfsViewShow = "show -p Slice,RootImage,NeedDaemonReload,MemoryMax,MemoryHigh,MemorySwapMax,CPUWeight,CPUQuotaPerSecUSec,IOWeight"
+internal/instancectl/rootfs.go:112:// digest answers the sha256 of f, opened at path, from the cache when the
+internal/instancectl/rootfs.go:125: h := sha256.New()
+internal/instancectl/rootfs.go:155:// component (instancefs.OpenBeneath), and its sha256 is img.Digest
+internal/instancectl/rootfs.go:179: if raw, err := hex.DecodeString(img.Digest); err != nil || len(raw) != sha256.Size {
+internal/instancectl/rootfs.go:180: return RootfsLaunch{}, fmt.Errorf("%w: digest %q is not a sha256", ErrStagedImage, img.Digest)
+internal/instancectl/rootfs.go:236: if !strings.EqualFold(art.SHA256, img.Digest) {
+internal/instancectl/rootfs.go:237: return RootfsLaunch{}, fmt.Errorf("%w: the staged manifest names digest %s, the image is %s", ErrStagedImage, art.SHA256, img.Digest)
+internal/instancectl/rootfs.go:496: max := strconv.FormatInt(tier.MemoryMax, 10)
+internal/instancectl/rootfs.go:497: applied = applied && m["MemoryMax"] == max && m["MemorySwapMax"] == max && m["MemoryHigh"] == strconv.FormatInt(cgroup.HighOf(tier.MemoryMax), 10)
+internal/instancectl/rootfs.go:794: s.logf("instance-control: %s: started %s from %s memory.max=%d (prepared in %s, reload %s, start %s)", req.host, unit, launch.Version, req.tier.MemoryMax,
+internal/instancectl/rootfs.go:1129: s.logf("instance-control: %s: started %s (%s) from %s memory.max=%d", req.host, unit, launch.Process, launch.Version, req.tier.MemoryMax)
+internal/instancectl/rootfs.go:1271: digest, err := fileSHA256(img)
+internal/instancectl/rootfs.go:1326:// fileSHA256 is the hex sha256 of the file at path.
+internal/instancectl/rootfs.go:1327:func fileSHA256(path string) (string, error) {
+internal/instancectl/rootfs.go:1333: h := sha256.New()
+internal/instancectl/claimunit.go:48: MemoryMax int64
+internal/instancectl/claimunit.go:71: if _, ok := cgroup.SizeOf(cgroup.Limit{MemoryMax: n}); !ok {
+internal/instancectl/claimunit.go:74: return cgroup.Limit{MemoryMax: n}, true
+internal/instancectl/claimunit.go:142: tier, ok := claimTier(in.MemoryMax)
+ 1 package activator
+ 2
+ 3 import (
+ 4 "context"
+ 5 "errors"
+ 6 "log"
+ 7 "sync"
+ 8 "time"
+ 9
+ 10 "github.com/carlosframework/platform/internal/cgroup"
+ 11 "github.com/carlosframework/platform/internal/execsandbox"
+ 12 "github.com/carlosframework/platform/internal/instancectl"
+ 13 "github.com/carlosframework/platform/internal/registry"
+ 14 )
+ 15
+ 16 // unknownSizes holds each host and size value SizedLimit has already
+ 17 // logged, so a name this box does not know is said once, not on every
+ 18 // spawn.
+ 19 var unknownSizes sync.Map
+ 20
+ 21 // SizedLimit is the limit rt runs at (#329, spec §5): the size column's row
+ 22 // when rt.Size names one, else fallback, the build's tier. An empty column
+ 23 // is fallback exactly, so a box with no policy runs as it did before. A
+ 24 // non-empty name this box does not know (a newer console's size) logs once
+ 25 // per host and value and falls back too.
+ 26 func SizedLimit(rt registry.Route, fallback cgroup.Limit) cgroup.Limit {
+ 27 if rt.IsDemo() {
+ 28 small, _ := cgroup.SizeByName("small")
+ 29 return small.Limit
+ 30 }
+ 31 if rt.Size == "" {
+ 32 return fallback
+ 33 }
+ 34 if s, ok := cgroup.SizeByName(rt.Size); ok {
+ 35 return s.Limit
+ 36 }
+ 37 if _, seen := unknownSizes.LoadOrStore(rt.Host+"\x00"+rt.Size, struct{}{}); !seen {
+ 38 log.Printf("activator: %s: size %q is not one this box knows; using the build's tier", rt.Host, rt.Size)
+ 39 }
+ 40 return fallback
+ 41 }
+ 42
+ 43 // EffectiveSize is the size row rt's build runs at on this box:
+ 44 // SizeOf(gb.GenTier(rt, build)), standard when the tier is no row. gb is
+ 45 // the backend the activator already spawns through: production's
+ 46 // *SplitBackend (which answers TierDefault for a unit-backed row) or an
+ 47 // *ExecBackend.
+ 48 func EffectiveSize(gb interface {
+ 49 GenTier(registry.Route, string) cgroup.Limit
+ 50 }, rt registry.Route, build string) cgroup.Size {
+ 51 if s, ok := cgroup.SizeOf(gb.GenTier(rt, build)); ok {
+ 52 return s
+ 53 }
+ 54 s, _ := cgroup.SizeByName("standard")
+ 55 return s
+ 56 }
+ 57
+ 58 // SizeBackend is the optional Backend capability behind a live size change
+ 59 // (#329, spec §5.4 rev 10): root's /size verb for a nested host.
+ 60 // ResizeLive sets rt's slice to size's CPU and IO shares and answers the
+ 61 // slice's read-back; memory never changes while the instance runs. A host
+ 62 // with no live change (another layout, a channel without the verb, a
+ 63 // unit-backed row) answers errSizeNotLive.
+ 64 type SizeBackend interface {
+ 65 ResizeLive(ctx context.Context, rt registry.Route, size cgroup.Size) (instancectl.SizeReadBack, error)
+ 66 }
+ 67
+ 68 var (
+ 69 _ SizeBackend = (*ExecBackend)(nil)
+ 70 _ SizeBackend = (*SplitBackend)(nil)
+ 71 )
+ 72
+ 73 // sizeBackstop is how often an awake entry compares its size column with
+ 74 // what it last acted on when no NoteSize has said it moved: the backstop
+ 75 // for a missed note. It reads only the local registry, never the store
+ 76 // (spec §3a). Each entry's clock starts at its wake, so entries do not
+ 77 // compare together.
+ 78 const sizeBackstop = 5 * time.Minute
+ 79
+ 80 // genTierer is the tier source EffectiveSize reads.
+ 81 type genTierer interface {
+ 82 GenTier(registry.Route, string) cgroup.Limit
+ 83 }
+ 84
+ 85 // sizedDefault is the tier source of a backend with no GenTier: the size
+ 86 // column over the default tier.
+ 87 type sizedDefault struct{}
+ 88
+ 89 func (sizedDefault) GenTier(rt registry.Route, _ string) cgroup.Limit {
+ 90 return SizedLimit(rt, cgroup.TierDefault)
+ 91 }
+ 92
+ 93 // tierSource is the Service's backend as EffectiveSize's tier source:
+ 94 // production's *SplitBackend (Ruling C1), which answers TierDefault for a
+ 95 // unit-backed row.
+ 96 func (a *Service) tierSource() genTierer {
+ 97 if gt, ok := a.backend.(genTierer); ok {
+ 98 return gt
+ 99 }
+ 100 return sizedDefault{}
+ 101 }
+ 102
+ 103 // genUnitOf is the generation unit g serves from: g.N when the entry runs
+ 104 // in a generation unit of its own (not a worker, and the generation bound
+ 105 // a socket of its own, so startRole started it through GenControl), else 0,
+ 106 // the run template's slice alone. A canonical handle is numbered with
+ 107 // generations off too, but no unit has that number (Astra plan R1-8). The
+ 108 // size controller uses this generation number for live resizing.
+ 109 func genUnitOf(rt registry.Route, g Gen) uint64 {
+ 110 if !g.Worker && linksCanonical(rt, g) {
+ 111 return g.N
+ 112 }
+ 113 return 0
+ 114 }
+ 115
+ 116 // SizeState is an awake instance's size (#329): Unit is the observed unit,
+ 117 // Sandbox its family, and Gen is the generation unit
+ 118 // it serves from (0: the slice alone), Raised that a swap holds the parent,
+ 119 // and Want the size its route and build run at now. Memory reaches Want at
+ 120 // the next start or swap (spec §5.4 rev 10); until then the status shows
+ 121 // the change pending.
+ 122 type SizeState struct {
+ 123 // Unit and Sandbox come from the retained handle, never from box policy.
+ 124 Unit string
+ 125 Sandbox execsandbox.Family
+ 126 Gen uint64
+ 127 Raised bool
+ 128 Want cgroup.Size
+ 129 }
+ 130
+ 131 // SizeState answers for an awake instance that is not a worker.
+ 132 func (a *Service) SizeState(host string) (SizeState, bool) {
+ 133 a.mu.Lock()
+ 134 e := a.entries[host]
+ 135 if e == nil || e.state != actAwake || e.worker {
+ 136 a.mu.Unlock()
+ 137 return SizeState{}, false
+ 138 }
+ 139 st := SizeState{Gen: genUnitOf(e.route, e.gen), Raised: e.ops.raised}
+ 140 if p, ok := e.proc.(interface {
+ 141 UnitIdentity() (string, execsandbox.Family)
+ 142 }); ok {
+ 143 st.Unit, st.Sandbox = p.UnitIdentity()
+ 144 }
+ 145 rt, build := a.sizedRouteLocked(e), e.gen.Build
+ 146 a.mu.Unlock()
+ 147 st.Want = EffectiveSize(a.tierSource(), rt, build)
+ 148 return st, true
+ 149 }
+ 150
+ 151 // sizedRouteLocked is e's route with the size column the size pass last
+ 152 // read (pendingSize), or e.route as it woke when no pass has read one: the
+ 153 // route a swap's successor starts from and SizeState's Want. It is a copy;
+ 154 // e.route is not changed. The caller holds a.mu.
+ 155 func (a *Service) sizedRouteLocked(e *actEntry) registry.Route {
+ 156 rt := e.route
+ 157 if e.pendingSizeSet {
+ 158 rt.Size = e.pendingSize
+ 159 }
+ 160 return rt
+ 161 }
+ 162
+ 163 // NoteSize says host's size column may have moved (the agent's
+ 164 // PolicyChanged): the next sweep compares it at once rather than at the
+ 165 // backstop. It never blocks on anything but a.mu.
+ 166 func (a *Service) NoteSize(host string) {
+ 167 a.mu.Lock()
+ 168 defer a.mu.Unlock()
+ 169 if e := a.entries[host]; e != nil {
+ 170 e.sizeDirty = true
+ 171 }
+ 172 }
+ 173
+ 174 // sizeEligibleLocked reports whether e may start a live size change now: it
+ 175 // is the host's awake instance entry, not a worker, and nothing else holds
+ 176 // its parent (no member, no raised parent, no restore or resize in
+ 177 // flight). The caller holds a.mu.
+ 178 func (a *Service) sizeEligibleLocked(e *actEntry) bool {
+ 179 return !a.shuttingDown && a.entries[e.host] == e && e.state == actAwake && !e.worker &&
+ 180 e.route.Kind == "instance" && len(e.ops.members) == 0 &&
+ 181 !e.ops.raised && !e.ops.restoring && !e.ops.resizing
+ 182 }
+ 183
+ 184 // sizeSnap is what a size pass took from its entry under a.mu.
+ 185 type sizeSnap struct {
+ 186 sb SizeBackend
+ 187 gt genTierer
+ 188 rt registry.Route
+ 189 g Gen
+ 190 seen string
+ 191 dirty bool
+ 192 owed bool
+ 193 }
+ 194
+ 195 // retrySizeLocked starts a live size pass for e when one is due (#329,
+ 196 // spec §5.4): NoteSize marked the column moved, a previous CPU and IO write
+ 197 // is owed, or the slow backstop compare is due. Otherwise it does nothing
+ 198 // at all. The pass first compares the column off a.mu, holding nothing
+ 199 // back (preflight C6), and only a change takes the resizing mark, after
+ 200 // the eligibility checks again. The caller holds a.mu; called from the
+ 201 // sweep (finishPendingStops), patterned on retryParentRestoreLocked.
+ 202 func (a *Service) retrySizeLocked(e *actEntry) {
+ 203 if e.sizeChecking || !a.sizeEligibleLocked(e) {
+ 204 return
+ 205 }
+ 206 sb, ok := a.backend.(SizeBackend)
+ 207 if !ok {
+ 208 return
+ 209 }
+ 210 now := a.now()
+ 211 if !e.sizeSeenSet {
+ 212 // The wake's fresh row: the size the entry was started at.
+ 213 e.sizeSeen, e.sizeSeenSet, e.sizeCheckedAt = e.route.Size, true, now
+ 214 }
+ 215 dirty, owed := e.sizeDirty, e.sizeOwed
+ 216 if !dirty && !owed && now.Sub(e.sizeCheckedAt) < sizeBackstop {
+ 217 return
+ 218 }
+ 219 e.sizeChecking, e.sizeDirty, e.sizeCheckedAt = true, false, now
+ 220 go a.sizePass(e, sizeSnap{sb: sb, gt: a.tierSource(), rt: e.route, g: e.gen,
+ 221 seen: e.sizeSeen, dirty: dirty, owed: owed})
+ 222 }
+ 223
+ 224 // endSizeCheck ends a pass that wrote nothing. redo keeps the change marked
+ 225 // for the next sweep.
+ 226 func (a *Service) endSizeCheck(e *actEntry, redo bool) {
+ 227 a.mu.Lock()
+ 228 defer a.mu.Unlock()
+ 229 e.sizeChecking = false
+ 230 if redo {
+ 231 e.sizeDirty = true
+ 232 }
+ 233 }
+ 234
+ 235 // sizePass is one live size pass, off a.mu. It reads only snapshots of the
+ 236 // entry; every entry field is read and written under a.mu.
+ 237 //
+ 238 // With no operator change (the column is what the entry last acted on) and
+ 239 // no write owed it ends after the registry read, with no root call.
+ 240 // Otherwise it sends the effective size once: root sets the slice's CPU
+ 170 // ended it, TimedOut when it ran past its timeout and was stopped. Took is
+ 171 // how long it ran; for a timeout, the timeout it ran into. Its text is the
+ 172 // approved event's (RFS-3-C05 to C07), the reason a failed wake or swap
+ 173 // carries.
+ 174 type ReleaseError struct {
+ 175 Build, Signal string
+ 176 Exit int
+ 177 TimedOut bool
+ 178 Took time.Duration
+ 179 }
+ 180
+ 181 func (e *ReleaseError) Error() string {
+ 182 switch {
+ 183 case e.TimedOut:
+ 184 return fmt.Sprintf(rolloutwords.EventReleaseTimedOut, e.Build, e.Took.Round(time.Second).String())
+ 185 case e.Signal != "":
+ 186 return fmt.Sprintf(rolloutwords.EventReleaseSignal, e.Build, e.Signal)
+ 187 }
+ 188 return fmt.Sprintf(rolloutwords.EventReleaseFailed, e.Build, e.Exit)
+ 189 }
+ 190
+ 191 var (
+ 192 // errReleaseOpen: a record for the host exists, in any state (INV-R4).
+ 193 // It is errSwapBusy, so an admission reads it as another operation in
+ 194 // flight.
+ 195 errReleaseOpen = fmt.Errorf("%w: a release command of this instance is still running or not proven stopped", errSwapBusy)
+ 196 // errReleaseUnproven: the release's unit was not proven gone; its
+ 197 // record stays and the sweep's pass retries the proof.
+ 198 errReleaseUnproven = errors.New("activator: a release command's unit is not proven stopped")
+ 199 // errReleaseNoLease: the caller has no lease whose safety deadline the
+ 200 // release can be stopped ahead of. Marked refuseRootfs where returned.
+ 201 errReleaseNoLease = errors.New("activator: the lease a release would run under cannot report its safety deadline")
+ 202 // errReleaseLeaseLost: the lease ended, or came within releaseStopLead
+ 203 // of its safety deadline, while the release ran. Returned as
+ 204 // fmt.Errorf("%w: %w", errSwapLeaseLost, errReleaseLeaseLost): an
+ 205 // ownership end, never the build's failure.
+ 300 if errors.Is(err, s) {
+ 301 return true
+ 302 }
+ 303 }
+ 304 return false
+ 305 }
+ 306
+ 307 // releaseOpen reports whether a release command's record exists for host,
+ 308 // running or not proven stopped (INV-R1): the one question every consumer
+ 309 // asks. Never call it with a.mu held.
+ 310 func (a *Service) releaseOpen(host string) bool {
+ 311 a.mu.Lock()
+ 312 defer a.mu.Unlock()
+ 313 return a.releaseOps[host] != nil
+ 314 }
+ 315
+ 316 // releaseExit reads a done unit's status as `carlos run` does
+ 317 // (host/runexec.go exitOf) [pf R1.15]: ExecMainCode 2, 3, killed or
+ 318 // dumped is a signal, numbered by ExecMainStatus; ExecMainCode 1 or exited
+ 319 // is an exit with ExecMainStatus as its status, and a pass only at status
+ 320 // 0 with Result success. Any other code recorded no exit: noExit.
+ 321 func releaseExit(st instancectl.CmdStatus) (passed bool, exit int, signal string, noExit bool) {
+ 322 n, perr := strconv.Atoi(st.Status)
+ 323 switch st.Code {
+ 324 case "2", "3", "killed", "dumped":
+ 325 return false, 0, strconv.Itoa(n), false
+ 326 case "1", "exited":
+ 327 if perr != nil {
+ 328 return false, 0, "", true
+ 329 }
+ 330 return n == 0 && (st.Result == "" || st.Result == "success"), n, "", false
+ 331 }
+ 332 return false, 0, "", true
+ 333 }
+ 334
+ 335 // releaseLeaseGone reports whether held has ended: its loss closed, its
+ 336 // liveness errs, or it can no longer read its safety deadline.
+ 337 func releaseLeaseGone(held leaseWatch) bool {
+ 338 select {
+ 339 case <-held.Lost():
+ 340 return true
+ 341 default:
+ 342 }
+ 343 if held.Err() != nil {
+ 344 return true
+ 345 }
+ 346 _, err := held.SafeUntil()
+ 347 return err != nil
+ 348 }
+ 349
+ 350 // releaseAppLog is the writer a release's output goes through to the app
+
+codex
+The 29.8 GiB total and the 27.3 GiB budget both check out. S1 needs a more precise limit contract: web can retain a larger limit during a shrink, while commands and sessions have their own launch handling. For S3, I’m checking how a drain waits for hub removal and what happens if the remaining copy fails during that wait.
+exec
+/bin/bash -lc "nl -ba internal/instancectl/rootfs.go | sed -n '1030,1120p'; rg -n 'MemoryMax|MemoryHigh|CPUQuota' internal/host/units/*rootfs*; rg -n 'CmdDropIn|TTYDropIn|cmdDropIn|ttyDropIn' internal/instancectl; nl -ba internal/activator/rootfsrelease.go | sed -n '400,455p'; rg -n 'ProbeCopy|Healthy' internal/activator/replica*.go; nl -ba internal/cgroup/size.go | head -120; rg -n 'MaxWorkers' internal/release/processes.go" in /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-stateless-replicas-scale
+ exited 2 in 0ms:
+ 1030 if !OneShot(role) {
+ 1031 http.Error(w, "role "+string(role)+" is not a one-shot role", http.StatusInternalServerError)
+ 1032 return
+ 1033 }
+ 1034 lock := s.oneShotLock(role, req.host)
+ 1035 lock.Lock()
+ 1036 defer lock.Unlock()
+ 1037 ctx := r.Context()
+ 1038 unit := RootfsUnitName(role, req.host)
+ 1039 if s.DropInDir == "" || s.ExeRoot == "" {
+ 1040 http.Error(w, "not starting "+unit+": rootfs units are not configured on this service", http.StatusNotImplemented)
+ 1041 return
+ 1042 }
+ 1043 switch state := s.showValue(ctx, "ActiveState", unit); state {
+ 1044 case "active", "activating", "deactivating", "reloading", "refreshing":
+ 1045 http.Error(w, string(role)+": "+unit+" is "+state, http.StatusConflict)
+ 1046 return
+ 1047 case "failed":
+ 1048 if out, err := s.Systemctl(ctx, "reset-failed", unit); err != nil {
+ 1049 http.Error(w, "reset-failed: "+strings.TrimSpace(out+" "+err.Error()), http.StatusBadGateway)
+ 1050 return
+ 1051 }
+ 1052 }
+ 1053 launch, answered := s.rootfsPreflight(w, req.host, role, unit, req.image)
+ 1054 if answered {
+ 1055 return
+ 1056 }
+ 1057 key := provision.InstanceID(req.host)
+ 1058 files := func() {
+ 1059 s.removeJITDropIn(unit)
+ 1060 s.removeRootfsExe(key, role)
+ 1061 }
+ 1062 // The unit's lock (task 11 fix E6), as startRootfs holds it; the
+ 1063 // role's per-host lock above already keeps two starts of the role
+ 1064 // apart, and cleanCmdExe takes both in the same order.
+ 1065 hold, err := s.holdRootfsUnit(ctx, unit)
+ 1066 if err != nil {
+ 1067 http.Error(w, string(role)+": "+err.Error(), http.StatusConflict)
+ 1068 return
+ 1069 }
+ 1070 defer hold.release()
+ 1071 // As startRootfs (task 11 fix W1): before systemctl start one look
+ 1072 // (fail), after it the full proof (failAfter); remove is the proof call
+ 1073 // the post-start check ends a misplaced unit with.
+ 1074 remove := func(extra ...string) error {
+ 1075 return s.removeRootfsUnitFiles(ctx, hold, req.host, unit, files, extra...)
+ 1076 }
+ 1077 removeOnce := func() { _ = s.removeRootfsUnitFilesOnce(ctx, hold, req.host, unit, files) }
+ 1078 if s.refuseStart(w, req.host, unit, func() error {
+ 1079 err := s.ensureRootfsExe(key, role, req.image.Path, launch)
+ 1080 if err != nil {
+ 1081 removeOnce()
+ 1082 }
+ 1083 return err
+ 1084 }) {
+ 1085 return
+ 1086 }
+ 1087 fail := func(status int, msg string) {
+ 1088 removeOnce()
+ 1089 http.Error(w, msg, status)
+ 1090 }
+ 1091 failAfter := func(status int, msg string) {
+ 1092 if err := remove(); err != nil {
+ 1093 msg += "; termination unproven, files kept: " + err.Error()
+ 1094 }
+ 1095 http.Error(w, msg, status)
+ 1096 }
+ 1097 changed, err := s.writeJITDropIn(unit, launch.JIT)
+ 1098 if err != nil {
+ 1099 fail(http.StatusBadGateway, "jit drop-in: "+err.Error())
+ 1100 return
+ 1101 }
+ 1102 if changed || s.jitReloadOwed() {
+ 1103 if err := s.jitDaemonReload(ctx); err != nil {
+ 1104 fail(http.StatusBadGateway, err.Error())
+ 1105 return
+ 1106 }
+ 1107 }
+ 1108 // A command or session runs beside an awake instance, whose start set
+ 1109 // the slice; a populated slice is left alone, as the binary branch
+ 1110 // leaves it, so a session is inside the instance's slice and tier.
+ 1111 if s.slicePopulated(req.host) {
+ 1112 s.logf("instance-control: %s: slice populated, leaving its limit to the instance's owner", req.host)
+ 1113 } else if err := s.setTier(ctx, req.host, req.tier); err != nil {
+ 1114 fail(http.StatusBadGateway, "set-property: "+err.Error())
+ 1115 return
+ 1116 }
+ 1117 // #328: s.Egress.Assert(ctx, host) here (egress checked before the unit starts)
+ 1118 before := s.showValue(ctx, "InvocationID", unit)
+ 1119 if out, err := s.Systemctl(ctx, "start", "--no-block", unit); err != nil {
+ 1120 failAfter(http.StatusBadGateway, rootfsStartFailure(unit, out, err))
+internal/host/units/carlos-instance-rootfs-probe.service:248:MemoryMax=64M
+internal/host/units/carlos-instance-rootfs-probe.service:252:CPUQuota=50%
+ 400 rb, ok := a.backend.(ReleaseBackend)
+ 401 if !ok {
+ 402 return false, refuseRootfs(fmt.Errorf("%s: %w", host, errNoRootfsControl))
+ 403 }
+ 404 // The bounds are read once, so the supervisor never reads them after
+ 405 // this call returns.
+ 406 lead, recheck := releaseStopLead, releaseLeaseRecheck
+ 407 own := func() error {
+ 408 if err := gate(); err != nil {
+ 409 return err
+ 410 }
+ 411 if err := held.Err(); err != nil {
+ 412 return fmt.Errorf("%w: %v", errSwapLeaseLost, err)
+ 413 }
+ 414 until, err := held.SafeUntil()
+ 415 if err != nil || time.Until(until) <= lead {
+ 416 return fmt.Errorf("%w: %w", errSwapLeaseLost, errReleaseLeaseLost)
+ 417 }
+ 418 return nil
+ 419 }
+ 420 if err := own(); err != nil {
+ 421 return false, err
+ 422 }
+ 423
+ 424 rctx, cancel := context.WithCancelCause(ctx)
+ 425 defer cancel(nil)
+ 426 op := &releaseOp{host: host, build: id, cancel: cancel, owner: e, state: releaseRunning, done: make(chan struct{})}
+ 427 op.hold = newCmdHold("release", instancectl.RoleCmd, func() { cancel(context.Canceled) }, a.now)
+ 428 op.hold.starting = true
+ 429 op.hold.onProven = func() { a.releaseProven(op) }
+ 430 startedClosed := false
+ 431 closeStarted := func(u CmdUnit) {
+ 432 if !startedClosed {
+ 433 op.hold.unit = u
+ 434 close(op.hold.started)
+ 435 startedClosed = true
+ 436 }
+ 437 }
+ 438 // A refusal before a unit exists: the record goes, nothing runs.
+ 439 refuse := func(err error, published bool) (bool, error) {
+ 440 closeStarted(nil)
+ 441 a.dropReleaseOp(op, published)
+ 442 return false, err
+ 443 }
+ 444
+ 445 a.mu.Lock()
+ 446 if err := a.releaseAdmitLocked(e); err != nil {
+ 447 a.mu.Unlock()
+ 448 return false, err
+ 449 }
+ 450 if a.releaseOps[host] != nil {
+ 451 a.mu.Unlock()
+ 452 return false, errReleaseOpen
+ 453 }
+ 454 if a.releaseOps == nil {
+ 455 a.releaseOps = make(map[string]*releaseOp)
+internal/activator/replicaprobe_test.go:76: c, err := a.ProbeCopy(ctx, rt.Host)
+internal/activator/replicaprobe_test.go:83: if state == "running" && (c.Host != rt.Host || c.Box != "a" || c.BootID != "boot" || c.Incarnation != "life" || c.AssignmentRevision != 7 || c.Generation != 12 || c.Version != "v1" || c.Digest != "digest" || c.State != "running" || c.Healthy || c.Socket != e.gen.Socket) {
+internal/activator/replicaprobe.go:11:// ProbeCopy reads the already-serving copy. It cannot join a wake, start a
+internal/activator/replicaprobe.go:13:func (a *Service) ProbeCopy(ctx context.Context, host string) (replicas.Copy, error) {
+nl: internal/cgroup/size.go: No such file or directory
+rg: internal/release/processes.go: IO error for operation on internal/release/processes.go: No such file or directory (os error 2)
+
+exec
+/bin/bash -lc "rg -n 'MemoryMax|CPUQuota' internal/host/units | rg '(cmd|tty|rootfs)'; rg -n 'MemoryMax|CPUQuota|256M|512M' internal/host/*rootfs*; rg -n 'MaxWorkers' internal/release | head; nl -ba internal/activator/replicaprobe.go | head -95; rg -n 'memory|Memory|cmd|tty' internal/host/rootfs_units.go" in /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-stateless-replicas-scale
+ exited 2 in 0ms:
+internal/host/units/carlos-instance-rootfs-probe.service:248:MemoryMax=64M
+internal/host/units/carlos-instance-rootfs-probe.service:252:CPUQuota=50%
+internal/host/units_rootfs_test.go:249: "BindPaths=/data/instances/_probe /run/carlos/instances/_probe", "ReadWritePaths=/data/instances/_probe /run/carlos/instances/_probe", "StandardOutput=truncate:/run/carlos-control/rootfs-probe.out", "Slice=carlos-instances.slice", "TasksMax=64", "MemoryMax=64M", "CPUQuota=50%", "CPUWeight=50", "IOWeight=50", "User=carlos", "Group=carlos",
+internal/release/rootfs.go:32: MaxWorkers = 4
+internal/release/rootfs.go:117: if workers > MaxWorkers {
+ 1 package activator
+ 2
+ 3 import (
+ 4 "context"
+ 5 "time"
+ 6
+ 7 "github.com/carlosframework/platform/internal/registry"
+ 8 "github.com/carlosframework/platform/internal/replicas"
+ 9 )
+ 10
+ 11 // ProbeCopy reads the already-serving copy. It cannot join a wake, start a
+ 12 // process, acquire authority, read a bucket, or record activity.
+ 13 func (a *Service) ProbeCopy(ctx context.Context, host string) (replicas.Copy, error) {
+ 14 if err := ctx.Err(); err != nil {
+ 15 return replicas.Copy{}, err
+ 16 }
+ 17 a.mu.Lock()
+ 18 defer a.mu.Unlock()
+ 19 e := a.entries[host]
+ 20 if !a.heldAdmissibleLocked(e) {
+ 21 return replicas.Copy{}, ErrHeldAsleep
+ 22 }
+ 23 rt := e.route
+ 24 if rt.FleetBoxes == "" || !rt.ValidReplicaProjection() || rt.Kind != "instance" || rt.Hibernate || rt.HA || !e.gen.Stateless || a.Routes == nil {
+ 25 return replicas.Copy{}, ErrFenced
+ 26 }
+ 27 // The registry is the reconciler's local assignment projection. Never
+ 28 // call currentWakeRoute here: its fresh record check reads the bucket.
+ 29 now, err := a.Routes.Get(host)
+ 30 if err != nil || now == nil || wakeRouteChanged(rt, *now, false) != nil || now.ReplicaIncarnation != rt.ReplicaIncarnation || now.Region != rt.Region || now.Incarnation != rt.Incarnation || !now.Stateless || now.Hibernate || now.HA {
+ 31 return replicas.Copy{}, ErrFenced
+ 32 }
+ 33 // Membership may change while this generation stays assigned. Report
+ 34 // the current revision, but never relabel a process across lifetimes.
+ 35 rt = *now
+ 36 fleet, placed := registry.FleetPlacement(rt.Region)
+ 37 coord, ok := a.Coordinator.(*CoordinationClient)
+ 38 if !placed || a.Fleet.Mode != FleetWakeCheck || a.Fleet.Fleet != fleet || !rt.ReplicaContains(a.Fleet.Label) || !ok || coord.box != a.Fleet.Label || coord.boot == "" {
+ 39 return replicas.Copy{}, ErrFenced
+ 40 }
+ 41 g := e.gen
+ 42 if g.Socket == "" || g.N == 0 || g.Build == "" || g.Digest == "" {
+ 43 return replicas.Copy{}, ErrFenced
+ 44 }
+ 45 c := replicas.Copy{Host: host, Account: rt.Account, App: rt.App, Fleet: fleet,
+ 46 Box: a.Fleet.Label, BootID: coord.boot, Incarnation: rt.ReplicaIncarnation,
+ 47 AssignmentRevision: rt.ReplicaRevision, Generation: g.N,
+ 48 Version: g.Build, Digest: g.Digest, Socket: g.Socket, State: "running", ObservedAt: time.Now()}
+ 49 for _, wk := range e.rootfsWorkers {
+ 50 if wk.gen == g.N {
+ 51 c.WorkersDeclared++
+ 52 if !wk.starting && wk.proc != nil && !wk.startFailed && !workerEnded(wk.proc) {
+ 53 c.WorkersRunning++
+ 54 }
+ 55 }
+ 56 }
+ 57 if e.sidecarWanted {
+ 58 c.WorkersDeclared++
+ 59 if e.sidecarGen == g.N && e.sidecar != nil && !e.sidecar.Exited() {
+ 60 c.WorkersRunning++
+ 61 }
+ 62 }
+ 63 return c, nil
+ 64 }
+rg: internal/host/rootfs_units.go: IO error for operation on internal/host/rootfs_units.go: No such file or directory (os error 2)
+
+exec
+/bin/bash -lc "rg -n 'MemoryMax|CPUQuota|rootfs.*cmd|rootfs.*tty' internal/host/units.go | head -60; rg --files internal/host/units | rg 'rootfs|cmd|tty'; nl -ba internal/host/units/carlos-instance-rootfs-cmd@.service | tail -50; rg -n 'memory|Memory|tier' internal/instancectl/names.go | head -30; rg -n 'runRt|cmdRt|rt :=|sizedRoute|genEnv' internal/activator/cmd*.go | head -55; nl -ba internal/edge/replicaprober.go | head -22" in /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-stateless-replicas-scale
+ succeeded in 0ms:
+rg: internal/host/units.go: IO error for operation on internal/host/units.go: No such file or directory (os error 2)
+internal/host/units/carlos-instance-rootfs-gen@.service
+internal/host/units/carlos-instance-cmd@.service
+internal/host/units/carlos-instance-rootfs-probe.service
+internal/host/units/carlos-instance-rootfs@.service
+internal/host/units/carlos-instance-rootfs-worker@.service
+internal/host/units/carlos-instance-tty@.service
+internal/host/units/carlos-instance-rootfs-tty@.service
+internal/host/units/carlos-instance-rootfs-cmd@.service
+ 230 # Kept, unchanged; unit-file pins.
+ 231 ProtectKernelTunables=yes
+ 232 ProtectKernelModules=yes
+ 233 ProtectKernelLogs=yes
+ 234 ProtectClock=yes
+ 235 ProtectHostname=yes
+ 236 RemoveIPC=yes
+ 237 LockPersonality=yes
+ 238 RestrictRealtime=yes
+ 239 # No RestrictSUIDSGID=: systemd cannot read the mode inside openat2's
+ 240 # open_how, so it refuses openat2 outright (ENOSYS), and every instancefs
+ 241 # open in here is an openat2 (#126, first roll; systemd 257). What it
+ 242 # guarded is covered: with no capabilities an instance can only make a
+ 243 # set-id file owned by carlos, which gains nothing for another carlos
+ 244 # process, NoNewPrivileges= voids it in here, and no other uid can reach
+ 245 # one (the image is nosuid by RootImageOptions=, the tenant trees are
+ 246 # nosuid, and /tmp is a nosuid tmpfs of this unit's own).
+ 247 #
+ 248 # Kept in the block for every template, the probe included (R11, rootfs
+ 249 # apps design §5.11). A release whose root-staged manifest declares jit
+ 250 # runs without it through a per-start drop-in that root writes and checks
+ 251 # the effective property of (C10), never through a unit file. The probe's
+ 252 # mdwe check: an mmap(PROT_WRITE|PROT_EXEC) is refused inside the probe,
+ 253 # which never gets the drop-in (EACCES from the kernel's PR_SET_MDWE,
+ 254 # which systemd 257 uses where the kernel has it, or EPERM from its
+ 255 # seccomp fallback).
+ 256 MemoryDenyWriteExecute=yes
+ 257 SystemCallArchitectures=native
+ 258 # The tenant's syscall surface (#527 Q5): systemd's baseline for an
+ 259 # ordinary service, less io_uring, the kernel keyring and userfaultfd,
+ 260 # which no supported runtime needs and which carry most of the recent
+ 261 # local privilege escalations. A refused call answers ENOSYS, as a kernel
+ 262 # without it would, so runtimes take the fallback they already have
+ 263 # (libuv's thread pool for io_uring) rather than being killed. openat2 is
+ 264 # in @system-service and an allow-list never reads arguments, so instancefs
+ 265 # is untouched (unlike RestrictSUIDSGID=, above). The probes' syscall-filter
+ 266 # line checks it from inside.
+ 267 SystemCallFilter=@system-service
+ 268 SystemCallFilter=~@keyring io_uring_setup io_uring_enter io_uring_register userfaultfd
+ 269 SystemCallErrorNumber=ENOSYS
+ 270
+ 271 # --- per-service resources; the tier lives on the host slice (§4.3) ---
+ 272 TasksMax=256
+ 273 # The kernel picks a tenant before it picks anything else in carlos.slice.
+ 274 OOMScoreAdjust=500
+ 275 # One OOM kill takes every process of THIS service (systemd sets
+ 276 # memory.oom.group on the service cgroup for OOMPolicy=kill). A worker is
+ 277 # a sibling service with its own family rule (isolated-exec design §4.3;
+ 278 # rootfs apps design §5.4).
+ 279 OOMPolicy=kill
+526: // lacks MemoryDenyWriteExecute.
+internal/activator/cmdunit_test.go:36: rt := registry.Route{Host: "h.example.com"}
+internal/activator/cmdunit_test.go:65: b, rt := nestedBackend(t, ctl, unit)
+internal/activator/cmdunit_test.go:70: genEnv: map[string]string{"CARLOS_ADMIN_TOKEN": "tok"}})
+internal/activator/cmdunit_test.go:118: b, rt := nestedBackend(t, ctl, &fakeUnit{})
+internal/activator/cmdunit_test.go:135: b, rt := nestedBackend(t, ctl, &fakeUnit{})
+internal/activator/cmdunit_test.go:230: start := time.Now()
+internal/activator/cmdunit_test.go:243: genEnv: map[string]string{"CARLOS_ADMIN_TOKEN": "tok", "CARLOS_CONTROL_SOCKET": "/x", "CARLOS_RUN_DIR": "/planted", "SHOP_MODE": "live"}}
+internal/activator/cmdunit_test.go:264: b, rt := nestedBackend(t, ctl, &fakeUnit{})
+internal/activator/cmdunit_test.go:273: rrt := rootfsRoute(rb)
+internal/activator/cmdunit_test.go:276: serving: &instancectl.StagedExe{Path: "/x", Version: "v1", Digest: "d"}, genEnv: map[string]string{}}
+internal/activator/cmdunit.go:105: // genEnv is the file environment the run's generation launched with,
+internal/activator/cmdunit.go:111: genEnv map[string]string
+internal/activator/cmdunit.go:112: // genKeyLayer is the layer genEnv's CARLOS_INSTANCE_KEY came from, from
+internal/activator/cmdunit.go:374:// with (spec.genEnv, merge ruling M3), the two stream listeners or the
+internal/activator/cmdunit.go:437: if spec.genEnv == nil {
+internal/activator/cmdunit.go:448: if err := b.replicaKeyGate(rt, spec.genEnv, spec.genKeyLayer, false); err != nil {
+internal/activator/cmdunit.go:464: vars := b.cmdVars(rt, spec.genEnv, p.dbPath, spec.RunID, spec.RunDir)
+internal/activator/cmdunit.go:466: vars = b.ttyVars(rt, spec.genEnv, p.dbPath, spec.RunID, spec.TTY.Term)
+internal/activator/cmdunit.go:579: rt := u.rt
+internal/activator/cmd_env_test.go:29: b, rt := nestedBackend(t, ctl, unit)
+internal/activator/cmd_env_test.go:61: spec := CmdSpec{RunID: "run_a", RunDir: dir, Stdout: &syncBuffer{}, Stderr: &syncBuffer{}, genEnv: lp.LaunchEnv()}
+internal/activator/cmd_env_test.go:115: rt := testRoute("c.example.com")
+internal/activator/cmd_env_test.go:118: got = append(got, spec.genEnv)
+internal/activator/cmd_env_test.go:119: if spec.genEnv == nil {
+internal/activator/cmd_env_test.go:168: b, rt := nestedBackend(t, ctl, &fakeUnit{})
+internal/activator/cmd_env_test.go:173: spec := CmdSpec{RunID: "run_a", RunDir: dir, Stdout: &syncBuffer{}, Stderr: &syncBuffer{}, genEnv: c.env, genKeyLayer: c.layer}
+internal/activator/cmd_swap_test.go:31: gate, entered, onStart := b.gate, b.entered, b.onStart
+internal/activator/cmd.go:912: spec.genEnv, spec.genKeyLayer = nil, instancekey.LayerNone
+internal/activator/cmd.go:914: spec.genEnv = lp.LaunchEnv()
+internal/activator/cmd_test.go:30: rt := testRoute("why.example.com")
+internal/activator/cmd_test.go:209: rt := testRoute("c.example.com")
+internal/activator/cmd_test.go:223: rt := testRoute("c.example.com")
+internal/activator/cmd_test.go:284: rt := testRoute("c.example.com")
+internal/activator/cmd_test.go:313: rt := testRoute("c.example.com")
+internal/activator/cmd_test.go:333: rt := testRoute("c.example.com")
+internal/activator/cmd_test.go:352: rt := testRoute("c.example.com")
+internal/activator/cmd_test.go:394: rt := testRoute("c.example.com")
+internal/activator/cmd_test.go:457: rt := testRoute("c.example.com")
+internal/activator/cmd_test.go:500: rt := testRoute("c.example.com")
+internal/activator/cmd_test.go:516: rt := testRoute("c.example.com")
+internal/activator/cmd_test.go:561: rt := testRoute("c.example.com")
+internal/activator/cmd_test.go:608: b, rt := nestedBackend(t, ctl, unit)
+internal/activator/cmd_test.go:671: rt := testRoute("c.example.com")
+internal/activator/cmd_test.go:724: b, rt := nestedBackend(t, &fakeControl{cmdInv: "inv1"}, &fakeUnit{})
+internal/activator/cmd_test.go:728: spec := CmdSpec{RunID: "run_a", RunDir: dir, Stdout: &syncBuffer{}, Stderr: &syncBuffer{}, serving: &x, genEnv: map[string]string{}}
+internal/activator/cmd_test.go:959: rt := testRoute("c.example.com")
+internal/activator/cmd_test.go:989: rt := testRoute("c.example.com")
+internal/activator/cmd_test.go:1014: rt := testRoute("c.example.com")
+internal/activator/cmd_test.go:1096: rt := testRoute("c.example.com")
+internal/activator/cmd_test.go:1156: rt := testRoute("c.example.com")
+internal/activator/cmd_test.go:1207: rt := testRoute("c.example.com")
+internal/activator/cmd_test.go:1331: rt := testRoute("c.example.com")
+internal/activator/cmd_test.go:1369: rt := testRoute("c.example.com")
+internal/activator/cmd_test.go:1401: rt := testRoute("c.example.com")
+internal/activator/cmd_test.go:1512: rt := testRoute("c.example.com")
+ 1 package edge
+ 2
+ 3 import (
+ 4 "context"
+ 5 "encoding/hex"
+ 6 "encoding/json"
+ 7 "errors"
+ 8 "io"
+ 9 "net/http"
+ 10 "sync"
+ 11 "time"
+ 12
+ 13 "github.com/carlosframework/platform/internal/registry"
+ 14 "github.com/carlosframework/platform/internal/replicas"
+ 15 "github.com/carlosframework/platform/internal/tunnelclient"
+ 16 )
+ 17
+ 18 const (
+ 19 replicaProbeInterval = time.Second
+ 20 replicaProbeFail = 2
+ 21 replicaProbeRise = 2
+ 22 // copy SR-3-C03 (provisional)
+
+exec
+/bin/bash -lc "nl -ba internal/activator/cmd.go | sed -n '850,940p'; nl -ba internal/activator/swap.go | sed -n '630,665p'; nl -ba internal/activator/backend_rootfs.go | sed -n '130,180p;190,217p'; nl -ba internal/activator/rootfsenv_test.go | sed -n '180,207p'; nl -ba internal/activator/rootfs_test.go | sed -n '242,266p'; nl -ba internal/moves/envreport.go | sed -n '55,80p'; rg -n 'StartCmd\\(' internal/activator/cmd.go; rg -n 'rt =|rt :=' internal/activator/cmd.go | head -30" in /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-stateless-replicas-scale
+ succeeded in 0ms:
+ 850 // An overlap successor is on its way: the current generation may
+ 851 // retire before the unit is even up, so nothing starts against it.
+ 852 // The run waits for the switch (and then runs the successor's
+ 853 // build) or for the successor's end (merge ruling M2). A stop
+ 854 // cancels pctx, as do the run's own cancel and deadline, and the
+ 855 // checks above then abandon the run.
+ 856 if m := switchPendingLocked(e); m != nil {
+ 857 a.mu.Unlock()
+ 858 select {
+ 859 case <-m.done:
+ 860 case <-time.After(cmdSwitchPoll):
+ 861 case <-pctx.Done():
+ 862 }
+ 863 waited = true
+ 864 a.mu.Lock()
+ 865 continue
+ 866 }
+ 867 if !waited || spec.Recheck == nil {
+ 868 break
+ 869 }
+ 870 // The run's own eligibility, which Prepare checked before the
+ 871 // wait, read again off a.mu (the record), then every check above
+ 872 // once more, since the entry may have moved meanwhile.
+ 873 a.mu.Unlock()
+ 874 prepErr = spec.Recheck(pctx)
+ 875 waited = false
+ 876 a.mu.Lock()
+ 877 }
+ 878 // Admitted against the current generation, under the lock a swap's
+ 879 // admission and switch take (merge ruling M2): no successor is live,
+ 880 // and a swap admitted from here on is refused until StartCmd returns
+ 881 // (cmdStartInFlightLocked).
+ 882 h.starting = true
+ 883 h.gen = e.gen
+ 884 rt.Stateless = h.gen.Stateless
+ 885 h.onProven = func() {
+ 886 // The pin for h.gen is this run's alone once that generation is
+ 887 // no longer the entry's current one.
+ 888 a.mu.Lock()
+ 889 stale := a.entries[e.host] != e || e.gen.N != h.gen.N
+ 890 a.mu.Unlock()
+ 891 if stale {
+ 892 _ = a.persistGenerations()
+ 893 }
+ 894 }
+ 895 // What the command runs is what the instance serves now: the current
+ 896 // generation's recorded file, by path, never the live link, which a
+ 897 // repoint, a fallback or a held update can move off it (zero-downtime
+ 898 // spec §7.5). That holds whatever CARLOS_SWAP says, as it does for the
+ 899 // legacy sidecar (settings ruling R-EXEC-SIDECAR): since settings Task
+ 900 // 5c a flag-off wake runs its recorded file by path too, so a flag-off
+ 901 // command on the live link could run a different build than its
+ 902 // instance. Only a generation that names no file (a backend that cannot
+ 903 // pin one) leaves the run the live link.
+ 904 spec.serving = nil
+ 905 if h.gen.StagedPath != "" {
+ 906 spec.serving = &instancectl.StagedExe{Path: h.gen.StagedPath, Version: h.gen.Build, Digest: h.gen.Digest}
+ 907 }
+ 908 // And with the environment that generation launched with, from its
+ 909 // handle: never the delivered files, which may hold a config revision
+ 910 // it has not activated, a config swap queued or failed (merge ruling
+ 911 // M3). A handle that kept none gets none, and StartCmd refuses.
+ 912 spec.genEnv, spec.genKeyLayer = nil, instancekey.LayerNone
+ 913 if lp, ok := e.proc.(launchEnvProc); ok {
+ 914 spec.genEnv = lp.LaunchEnv()
+ 915 }
+ 916 if lp, ok := e.proc.(launchKeyLayerProc); ok {
+ 917 spec.genKeyLayer = lp.LaunchKeyLayer()
+ 918 }
+ 919 a.mu.Unlock()
+ 920 // One bound covers the build-state write and the start, so a stop
+ 921 // waiting on the start still has the settle's budget after it
+ 922 // (cmdStartBound).
+ 923 sctx, scancel := context.WithTimeout(ctx, cmdStartBound)
+ 924 defer scancel()
+ 925 // The build about to touch the instance's database is recorded first
+ 926 // (settings spec §4.2), as the sidecar's is (startSidecar): a command
+ 927 // runs its serving generation's build against the data, and the build
+ 928 // state must name that build before it does. A failed successor may
+ 929 // have left the record naming its own build; without this write a
+ 930 // command on the incumbent would run under a record that names
+ 931 // another, and a held recovery could pick the wrong one. A write that
+ 932 // fails refuses the launch (errBuildStateUnwritten): nothing starts.
+ 933 //
+ 934 // The starting hold is kept throughout. A stop that begins meanwhile
+ 935 // waits for this start to return, and no overlap swap is admitted
+ 936 // (cmdStartInFlightLocked), so the generation recorded is still the
+ 937 // one serving when the unit starts. The write takes time, so
+ 938 // ownership and the run's own cancel and deadline are checked again
+ 939 // after it, before anything starts.
+ 940 if err := a.recordBuild(sctx, rt.Host, h.gen.Build); err != nil {
+ 630 }
+ 631 return abandon(err)
+ 632 }
+ 633
+ 634 // Each artifact's own tier, captured now (spec §7.3): the incumbent's
+ 635 // from the build it runs, the successor's from the attempt's build.
+ 636 // Neither is read from the live link, which root may repoint. They size
+ 637 // the overlap parent, the successor's child, and the restore (leaveSet
+ 638 // restores to the current generation's Tier).
+ 639 if incumbent.Tier == (cgroup.Limit{}) {
+ 640 incumbent.Tier = gb.GenTier(wakeRt, incumbent.Build)
+ 641 }
+ 642 succTier := gb.GenTier(rt, at.Build)
+ 643 // With an operator size the successor starts at the larger of its own
+ 644 // effective size and the incumbent's captured tier (spec §5.4 rev 8,
+ 645 // R1-3). That applies when the route has a size now, or when the
+ 646 // incumbent runs at a tier other than its build's own (a size was in
+ 647 // force at its start and has since been cleared). Memory never changes
+ 648 // live (spec §5.4 rev 10), so the captured tier is what the incumbent
+ 649 // runs at, and a swap is how a growth lands.
+ 650 // The raise and the restore then never lower memory: a shrink waits for
+ 651 // a cold start. It is conditional so that a host with no operator size
+ 652 // keeps each artifact's own tier, byte-identical to main: a release that
+ 653 // drops children still restores to 512 MiB at the swap.
+ 654 if rt.Size != "" || incumbent.Tier != gb.GenTier(rt, incumbent.Build) {
+ 655 succTier = cgroup.MaxLimit(succTier, incumbent.Tier)
+ 656 }
+ 657 a.mu.Lock()
+ 658 recordCurrentTierLocked(e, incumbent.N, incumbent.Tier)
+ 659 m.gen.Tier = succTier
+ 660 a.mu.Unlock()
+ 661
+ 662 // Step 2: the parent raise, before the successor spawns (spec §7.3).
+ 663 // The parent is marked potentially changed BEFORE the raise is asked: a
+ 664 // raise that wrote memory.max and then failed a later write has changed
+ 665 // it, and the member's cleanup (leaveSet) must restore it (final review
+ 130
+ 131 // ReleaseEnv implements ReleaseBackend [pf R1.3]. It takes the three
+ 132 // steps a web start's prepare takes for the run role (prepare.go), so a
+ 133 // first boot's release has the admin token and the instance key, and the
+ 134 // web start after it finds the same ones; then the replica gate a cmd
+ 135 // start asks; then the release's composition over the file environment.
+ 136 // The environment is never logged.
+ 137 func (b *ExecBackend) ReleaseEnv(ctx context.Context, rt registry.Route) (map[string]string, error) {
+ 138 if !rt.Rootfs() {
+ 139 return nil, refuseRootfs(fmt.Errorf("%s: a release command runs only on a rootfs instance", rt.Host))
+ 140 }
+ 141 // Nothing is minted on a row that is not nested: a fenced or
+ 142 // conflicting row's paths name the box's flat directory, which may be
+ 143 // a host mid-migration (ensureInstanceKeyAt).
+ 144 p := b.pathsFor(rt)
+ 145 switch p.layout {
+ 146 case LayoutNested:
+ 147 case LayoutFenced, LayoutConflict:
+ 148 return nil, refuseRootfs(fmt.Errorf("%s: refusing a release command: %s", rt.Host, p.reason))
+ 149 default:
+ 150 return nil, refuseRootfs(fmt.Errorf("%s: %s", rt.Host, rootfsNotNestedText))
+ 151 }
+ 152 if err := os.MkdirAll(p.dataDir, 0o700); err != nil {
+ 153 return nil, err
+ 154 }
+ 155 hctx, cancel := context.WithTimeout(ctx, haSecretsBudget)
+ 156 defer cancel()
+ 157 if err := b.ensureAdminTokenFor(hctx, rt, p); err != nil {
+ 158 return nil, fmt.Errorf("admin token for %s: %w", rt.Host, err)
+ 159 }
+ 160 if _, err := b.ensureInstanceKeyFor(hctx, rt, p); err != nil {
+ 161 return nil, fmt.Errorf("instance key for %s: %w", rt.Host, err)
+ 162 }
+ 163 env, layer, err := b.launchEnvLayer(hctx, rt)
+ 164 if err != nil {
+ 165 return nil, err
+ 166 }
+ 167 if err := b.replicaKeyGate(rt, env, layer, false); err != nil {
+ 168 return nil, err
+ 169 }
+ 170 return b.rootfsReleaseVars(rt, env, p.dbPath), nil
+ 171 }
+ 172
+ 173 // StartRelease implements ReleaseBackend: startRootfsCmd naming id's
+ 174 // release process in the cmd unit, both streams written into out through
+ 175 // one capped line writer (releaseOutput) [pf R1.5].
+ 176 func (b *ExecBackend) StartRelease(ctx context.Context, rt registry.Route, id release.StagedIdentity, env map[string]string, out io.Writer) (CmdUnit, error) {
+ 177 ctx = b.admissionContext(ctx, rt)
+ 178 o := newReleaseOutput(rt.Host, out, runs.MaxOutputBytes)
+ 179 return b.startRootfsCmd(ctx, rt, instancectl.RoleCmd, id, rootfsCmdLaunch{Process: release.ProcessRelease}, env, oneShotSinks{Stdout: o.stream(), Stderr: o.stream()})
+ 180 }
+ 190 // process.
+ 191 Argv []string
+ 192 }
+ 193
+ 194 // processName is the launch file's name for what l runs: its process, or
+ 195 // "cmd" for an operator's command, in either role.
+ 196 func (l rootfsCmdLaunch) processName() string {
+ 197 if l.Process != "" {
+ 198 return l.Process
+ 199 }
+ 200 return string(instancectl.RoleCmd)
+ 201 }
+ 202
+ 203 // oneShotSinks is where a rootfs one-shot's I/O goes: a run's or a
+ 204 // release's two streams (the cmd role), or a session's terminal (the tty
+ 205 // role, TTY set).
+ 206 type oneShotSinks struct {
+ 207 Stdout, Stderr io.Writer
+ 208 TTY *TTYSpec
+ 209 }
+ 210
+ 211 // startRootfsCmd starts l, a declared process of id or an operator's
+ 212 // command, in rt's rootfs one-shot unit of role, cmd or tty [pf R0.1,
+ 213 // R1.4; Plan 6 Task 8, PF-1], in this order: every rootfs gate; a whole
+ 214 // identity, exactly one of l's two fields, a role that is a one-shot's
+ 215 // whose I/O matches sinks (a terminal for tty alone), and a control
+ 216 // channel with a rootfs half, and with the session verbs for tty
+ 217 // (ErrNoTTY); the instance's directories; the two stream listeners the
+ 180 b, ctl := newRootfsBackend(t)
+ 181 rt := nestedRoute(b, "blog.example.com")
+ 182 stageLive(t, b, rt.Host, "v1")
+ 183 writeInstanceEnv(t, b, rt, "SHOP_MODE=live\n")
+ 184 ctl.onStart = serveHealthy(t, rt.Socket)
+ 185 p, _, err := b.Start(context.Background(), rt)
+ 186 if err != nil {
+ 187 t.Fatal(err)
+ 188 }
+ 189 defer p.Stop(context.Background()) //nolint:errcheck
+ 190 l := readLaunchFile(t, b, rt, instancectl.RoleRun)
+ 191 if want := []string{b.liveLink(rt.Host), "--socket", rt.Socket, "--db", rt.DBPath}; !slices.Equal(l.Argv, want) {
+ 192 t.Errorf("binary argv %q, want %q", l.Argv, want)
+ 193 }
+ 194 if l.Schema != instancectl.LaunchSchema || l.Runtime != "" {
+ 195 t.Errorf("binary launch schema %d runtime %q", l.Schema, l.Runtime)
+ 196 }
+ 197 env := envMap(t, l.Env)
+ 198 for _, k := range rootfsOwnedNames {
+ 199 if v, ok := env[k]; ok {
+ 200 t.Errorf("a binary launch carries %s=%q", k, v)
+ 201 }
+ 202 }
+ 203 if env["SHOP_MODE"] != "live" {
+ 204 t.Errorf("the tenant's variable is missing from the binary launch: %v", env)
+ 205 }
+ 206 }
+ 242 // The names rootfsVars owns are rootfsOwnedNames, and a tenant's PATH (its
+ 243 // own choice) is kept.
+ 244 func TestRootfsVarsOwnsExactlyItsNames(t *testing.T) {
+ 245 t.Parallel()
+ 246 got := rootfsVars(map[string]string{"PATH": "/app/bin", "CARLOS_DB": "x"}, "/s", "/d")
+ 247 var owned []string
+ 248 for k := range got {
+ 249 if k != "PATH" {
+ 250 owned = append(owned, k)
+ 251 }
+ 252 }
+ 253 sort.Strings(owned)
+ 254 want := slices.Clone(rootfsOwnedNames)
+ 255 sort.Strings(want)
+ 256 if !slices.Equal(owned, want) || got["CARLOS_SOCKET"] != "/s" || got["CARLOS_DB"] != "/d" || got["PATH"] != "/app/bin" {
+ 257 t.Errorf("rootfsVars = %v, owned %v", got, owned)
+ 258 }
+ 259 if env := rootfsLaunchEnv(got); !slices.Contains(env, "PATH=/app/bin") {
+ 260 t.Errorf("the tenant's own PATH was dropped: %v", env)
+ 261 }
+ 262 }
+ 263
+ 264 // C1 from the agent: every gate refuses before root is asked, before any
+ 265 // listener is bound, before a launch file is written, and before the live
+ 266 // link is materialized (preflight 2.28: the Materialize hook relays a stage
+ 55 // AgentOwnedVars are the variables the agent sets, overwrites or
+ 56 // removes on every launch (activator ExecBackend.agentOwnedVars): the
+ 57 // control socket, the purge channel, the box's region and the host
+ 58 // row's name. A tenant's env file never decides them, and each box sets
+ 59 // its own, so they are box-owned (BoxOwned).
+ 60 // TestAgentOwnedVarsAreMovesBoxOwned (internal/activator) pins this set
+ 61 // against agentOwnedVars.
+ 62 AgentOwnedVars = map[string]bool{RegionVar: true, "CARLOS_CONTROL_SOCKET": true, "CARLOS_PURGE": true, "CARLOS_HOST": true}
+ 63 )
+ 64
+ 65 // BoxOwned reports a variable whose value can be the box's rather than the
+ 66 // instance's: an agent-owned variable, always the box's, or a box variable
+ 67 // of the box's own process, the box's unless the instance's own layers
+ 68 // supply it (Pinned). It is the one set every comparison of a move's
+ 69 // environment across two boxes may leave out (home part 2, Task 2b): T3
+ 70 // tolerates these (Class is not "equal") unless an instance supplied
+ 71 // them, and the env pin covers every variable Pinned keeps.
+ 72 func BoxOwned(name string) bool { return AgentOwnedVars[name] || BoxVars[name] }
+ 73
+ 74 // Pinned reports whether a variable is part of the move-portable env, the
+ 75 // env the move's pin covers on the source and the target's checks hash
+ 76 // (fix round 4, platform-1e's exclusion rule): a variable is left out only
+ 77 // when it is box-owned (BoxOwned) and the instance's own layers did not
+ 78 // supply the value that runs (instanceSupplied false). Everything else is
+ 79 // pinned. The composer reports as instance-supplied only the names whose
+ 80 // running value is the instance's (activator ExecBackend.LaunchLayers): an
+988: u, err := cb.StartCmd(sctx, rt, spec)
+
+codex
+No P1 findings. Two P2 findings.
+
+1. **P2 — §4 S1: “the same number” needs a definition for size transitions.**
+
+ **Problem:** The design conflates the configured size, a generation’s launch limit, and the shared slice’s current limit. They can differ.
+
+ **Verified evidence:** [internal/activator/rootfs.go:268](internal/activator/rootfs.go:268) preserves the caller’s generation tier during a pending shrink. [internal/activator/backend_rootfs.go:562](internal/activator/backend_rootfs.go:562) starts workers with `g.Tier.MemoryMax`, whereas commands, release and TTY use `b.tier(rt).MemoryMax` at line 282. Root leaves a populated slice’s existing limit unchanged: [internal/instancectl/rootfs.go:1108](internal/instancectl/rootfs.go:1108). Web’s retained `LaunchEnv` is the file environment, before agent-owned additions: [internal/activator/rootfs.go:434](internal/activator/rootfs.go:434).
+
+ **Failure scenario:** During a size increase, release runs beside the old web under its existing slice limit; the successor web subsequently starts at the larger limit. They cannot truthfully receive the same number. During a pending shrink, deriving the variable from the configured size understates the retained generation limit. Merely adding it to web’s final environment does not make workers inherit it.
+
+ **Concrete fix:** Define the variable as a launch-time budget, with explicit rules for each role: web uses the resolved `spawnRootfs` tier; workers use their generation’s tier; commands, sessions and release use the applicable retained slice budget, or the cold-start budget when no instance is running. Pass retained limits through existing in-memory launch context, without new reads. Qualify the same-number promise across size transitions. Update the ownership lists and their pin tests consistently; `agentOwnedNames` and `moves.AgentOwnedVars` are equality-pinned by [internal/activator/agentowned_moves_test.go:79](internal/activator/agentowned_moves_test.go:79).
+
+ **Fault family:** Launch environment must describe the memory budget actually applicable to that launch.
+
+2. **P2 — §4 S3: the drain sequence needs explicit admission, timeout and cancellation rules.**
+
+ **Problem:** “Stops counting it as up” is not an immediate routing exclusion on main. The design also leaves unspecified what happens when hub removal cannot be confirmed, requests outlast the bound, or the remaining copy fails during the wait.
+
+ **Verified evidence:** [internal/edge/replicaprobe.go:77](internal/edge/replicaprobe.go:77) derives `Healthy` from the web response, so changing only the activator’s `Healthy` value would be overwritten. [internal/edge/replicaprober.go:263](internal/edge/replicaprober.go:263) applies failure hysteresis and replaces the reported health with the accumulated result; two failures are required. [internal/edge/replicaprober.go:336](internal/edge/replicaprober.go:336) routes from cached healthy observations. The merged design requires a serving copy throughout a rolling deploy: [2026-11-01 design:50](docs/superpowers/specs/2026-11-01-stateless-replicas-design.md:50).
+
+ **Failure scenario:** A draining box can remain eligible while probe failures accumulate. If the bounded wait expires and execution proceeds to stopping web, requests can still arrive or remain unfinished. If the only other serving copy disappears during that wait, an admission-time health check alone does not prevent stopping the last copy.
+
+ **Concrete fix:** Require a drain state honored by the edge probe and hub selection, confirmation of routing exclusion before stopping, and a fresh remaining-copy check before withdrawal and stop. Specify that missing confirmation or loss of the survivor aborts the drain and restores the old copy’s eligibility. Define the deadline policy for unfinished requests, distinguishing accepted websocket disconnection from ordinary HTTP requests.
+
+ **Fault family:** A planned drain must preserve serving availability and exclude new traffic before termination.
+
+The other checks passed: §2’s per-instance release scope matches merged §6.6 and the host-keyed release machinery; the estate totals approximately **29.8 GiB per box**; and **31.2 − 31.2/8 = 27.3 GiB**. No additional contradictions found within the five checks. No files changed, subagents spawned, or full suites run.
+
+**READY AFTER FIXES**
diff --git a/docs/superpowers/specs/2026-11-11-stateless-replicas-production-scale-design.md b/docs/superpowers/specs/2026-11-11-stateless-replicas-production-scale-design.md
index e87d8ee7c..bb814d225 100644
--- a/docs/superpowers/specs/2026-11-11-stateless-replicas-production-scale-design.md
+++ b/docs/superpowers/specs/2026-11-11-stateless-replicas-production-scale-design.md
@@ -1,6 +1,6 @@
# Stateless replicas at production scale: big copies, not many
-Rev 1, 2026-11-11. Discussion #892, a follow-up to #511. Builds on the
+Rev 2, 2026-11-11 (rev 1 plus Astra round 1's two P2 fixes: S1 per role, S3's drain steps). Discussion #892, a follow-up to #511. Builds on the
stateless replicas design (`docs/superpowers/specs/2026-11-01-stateless-replicas-design.md`,
"the 11-01 design" below) and changes none of its decisions. Brainstorm:
Paul asked for #892 to be taken to done on 2026-11-11 without a live
@@ -110,20 +110,36 @@ Four slices, each its own plan. S1 is independent of #511 Plan 4 and
starts now. S2 to S4 touch Plan 4's code (sizes, swaps, the floor), so
their plans are written after Plan 4 merges (stopping rule 4).
-### S1. Every process learns its size (now)
-
-Each rootfs process gets `CARLOS_MEMORY_MIB`: the memory limit, in MiB,
-that the instance runs at on this start. Web, workers and release see the
-same number, because they share it (rootfs spec: "All of an instance's
-processes share one memory and CPU limit"), and so do a `carlos run` and
-an interactive session. It is agent-owned like
-`CARLOS_HOST`: set on every launch, whatever the instance's files say.
+### S1. Web and workers learn their size (now)
+
+Web and every worker of a rootfs instance get `CARLOS_MEMORY_MIB`: the
+memory limit root is asked to start that process's unit at, in MiB,
+rounded down. It is a launch-time figure, one rule per role (Astra R1-1):
+
+- **web**: the limit `spawnRootfs` passes root for that generation. That
+ is the generation's tier, which a swap may keep at the incumbent's
+ larger tier while a shrink waits for a cold start.
+- **a worker**: its web generation's tier (`Gen.Tier`), the figure
+ `LaunchRootfsWorker` already passes root. The worker's variable is set
+ when its own launch file is written, not inherited from web's.
+- **release, `carlos run` and interactive sessions**: no variable. They
+ are one-shot processes that run beside, or before, a generation whose
+ limit their unit does not set (a populated slice keeps its owner's
+ limit), so no single figure is true for them. The name is removed from
+ their environment, so a tenant's files cannot supply a false one.
+
+It is agent-owned, like `CARLOS_SOCKET` and `CARLOS_DB`: set by the agent
+on every web and worker launch, after the instance's files, so they cannot
+change it. It is computed from the number the agent already passes root;
+nothing new is read. A size change takes effect at the next start, as
+sizes do today, and the variable follows it. It is not a binary
+instance's variable, and moves (`moves.AgentOwnedVars`) are unaffected,
+because it is never written to an environment file.
With it, one `processes.json` and one Puma config serve every size: for
example `workers ENV.fetch("WEB_CONCURRENCY") { [ENV["CARLOS_MEMORY_MIB"].to_i / 1024, 1].max }`.
A Sidekiq swarm's count and its per-process memory restart limit derive
-the same way. A size change takes effect at the next start, as sizes do
-today, and the variable follows it.
+the same way.
CPU is not added: Puma and concurrent-ruby already count the CPUs the
process can use.
@@ -163,15 +179,32 @@ and 11-01 §6.4 does the same per copy, one box at a time. A copy sized to
most of its box cannot have a second copy beside it, so with S2 alone
every deploy of a big copy would stop at the memory check.
-The drain swap replaces the overlap for those copies:
-
-1. The box takes its copy out of the hub's set (its health answer stops
- counting it as up) and waits, for a bounded time the plan sets, until
- the hub has stopped sending and its requests in flight have finished.
-2. It stops the old copy: web, then the workers, proven gone as today.
-3. It starts the new build and, once web is healthy, puts the copy back in
- the hub's set. Its workers start after web, as today.
-4. The next box's permit (Plan 4) follows only then.
+The drain swap replaces the overlap for those copies (Astra R1-2):
+
+1. **Check.** The box confirms, from the hub's current view, that at
+ least one other copy of the instance is healthy on the current build.
+ If none is, it does not drain (see below).
+2. **Withdraw.** It marks its copy *draining* in what the hub reads for
+ the copy. The hub honours the mark at once in its choice of copy: it is
+ a state of its own, not a health failure, so the prober's failure count
+ and hysteresis do not delay it. The box waits until the hub's view
+ shows the mark taken (no new requests chosen for the copy).
+3. **Settle.** It waits for the copy's requests in flight to finish,
+ up to a deadline the plan sets. Websockets and other upgraded
+ connections do not hold the drain; they are cut at the stop and
+ reconnect (11-01 §5.6). An ordinary request still running at the
+ deadline is cut and counted, as a stream cut is in the 11-01 drill.
+4. **Stop and start.** It stops the old copy (web, then its workers,
+ proven gone as today) and starts the new build. Once web is healthy
+ it clears the mark, and the copy rejoins. Its workers start after web,
+ as today.
+5. **Next box.** The next box's permit (Plan 4) follows only then.
+
+Aborts. If the hub's view does not show the mark taken within its bound,
+or no other copy is healthy at any point before the stop, the box clears
+the mark, keeps the old copy serving, and the deploy halts on that box
+with a reason, as a failed step does today. Nothing is stopped while it
+is the only serving copy.
Release still runs once, before any box swaps (11-01 §5.3). While one box
swaps, the other copies carry the traffic, so the docs say to size an app