edge: websockets get their own backhaul pool, so sockets can't shed requests
Open websockets held a backhaul in-flight slot for their whole life, so about 64 parked sockets toward one home box made every ordinary request to it answer 503 (#1535). A hop is now admitted on a request slot and moves to a separate per-home-box stream pool only when the home answers 101 (CARLOS_BACKHAUL_MAX_STREAMS, default 128, per-client share scaled to the cap); a socket to a full stream pool is refused before dialling. Request/response stays at 64 (CARLOS_BACKHAUL_MAX_INFLIGHT). Refusals at a limit raise the backhaul_shed warning (console alert engine) through the existing metrics sample, with no new polling or bucket reads. Scope cut by 8a3d302 after review round 2: the receiving-side aggregate budget is #1660. Reviews: Astra and Fable rounds 1-2, Astra census and fix check; census approved on #280; copy by Luna (three passes). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from backhaul-streams-1535 into main.
40 files changed,
+2,282
−56
.amadan/code-health.tsv+2 −2README.md+49 −0docs/superpowers/notes/census-proposal-backhaul-streams-1535.md+23 −0docs/superpowers/reviews/backhaul-streams-1535/ASTRA-CENSUS-AND-FIX-CHECK.md+25 −0docs/superpowers/reviews/backhaul-streams-1535/ASTRA-FINDINGS-R1.md+49 −0docs/superpowers/reviews/backhaul-streams-1535/ASTRA-FINDINGS-R2.md+53 −0docs/superpowers/reviews/backhaul-streams-1535/CENSUS-AND-FIX-CHECK.md+11 −0docs/superpowers/reviews/backhaul-streams-1535/FABLE-FINDINGS-R1.md+47 −0docs/superpowers/reviews/backhaul-streams-1535/FABLE-FINDINGS-R2.md+60 −0docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-BRIEF-1.md+15 −0docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-BRIEF-2.md+3 −0docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-BRIEF-3.md+3 −0docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-RESULT-1.md+32 −0docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-RESULT-2.md+17 −0docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-RESULT-3.md+13 −0docs/superpowers/reviews/backhaul-streams-1535/REVIEW-BRIEF-R1.md+31 −0docs/superpowers/reviews/backhaul-streams-1535/REVIEW-BRIEF-R2.md+35 −0internal/alerting/ruletext.go+29 −0internal/console/alertengine_pass.go+3 −1internal/console/alertnotify.go+7 −0internal/console/alertpages.go+7 −1internal/console/alertpages_test.go+42 −0internal/console/alertsignals.go+1 −0internal/edge/asset_far_test.go+2 −0internal/edge/backhaul_share_test.go+3 −0internal/edge/backhaul_streams_test.go+897 −0internal/edge/edge.go+288 −35internal/edge/handover_test.go+5 −3internal/host/agent.go+3 −0internal/host/backhaulshed.go+33 −0internal/host/metrics_backhaul_test.go+221 −0internal/host/metrics_loop.go+74 −9internal/hostenv/hostenv.go+1 −0internal/hostenv/hostenv_test.go+9 −0internal/metrics/alert.go+37 −1internal/metrics/backhaul.go+37 −0internal/metrics/backhaul_test.go+94 −0internal/metrics/sample.go+8 −4internal/provision/testdata/plan14-root-reads-backhaul-streams-1535.tsv+12 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0
CI cancelled — superseded by a newer push — run details
CI log
=== gate === go: downloading go1.26.10 (linux/arm64) go version go1.26.10 linux/arm64 opentofu: arm64, tofu 1.13.9, aws 6.73.0, archive 2.8.1 tofu: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/tofu_1.13.9_linux_arm64.tar.gz tofu: downloaded, digest verified aws: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/terraform-provider-aws_6.73.0_linux_arm64.zip aws: downloaded, digest verified archive: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/terraform-provider-archive_2.8.1_linux_arm64.zip archive: downloaded, digest verified installed in /tmp/carlos-opentofu-uVBlos .amadan/test-gate.sh go: downloading modernc.org/sqlite v1.55.0 go: downloading github.com/aws/aws-sdk-go-v2/service/acm v1.45.0 go: downloading github.com/aws/aws-sdk-go-v2/service/cloudwatch v1.68.0 go: downloading github.com/aws/aws-sdk-go-v2/service/ec2 v1.324.0 go: downloading github.com/aws/aws-sdk-go-v2/service/costexplorer v1.67.5 go: downloading github.com/aws/aws-sdk-go-v2/service/s3 v1.105.0 go: downloading github.com/aws/aws-sdk-go-v2/service/iam v1.58.2 go: downloading golang.org/x/net v0.62.0 go: downloading golang.org/x/crypto/x509roots/fallback v0.0.0-20260209214922-2f26647a795e go: downloading github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi v1.37.0 go: downloading github.com/aws/aws-sdk-go-v2/service/route53 v1.64.1 go: downloading github.com/aws/aws-sdk-go-v2/service/sts v1.45.6 go: downloading github.com/aws/aws-sdk-go-v2/service/sns v1.43.0 go: downloading golang.org/x/sys v0.49.0 go: downloading golang.org/x/crypto v0.58.0 go: downloading github.com/aws/aws-sdk-go-v2/service/sesv2 v1.66.6 go: downloading github.com/pierrec/lz4/v4 v4.1.22 go: downloading github.com/aws/aws-sdk-go-v2/service/ssm v1.74.0 go: downloading google.golang.org/protobuf v1.36.10 go: downloading github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.38 go: downloading github.com/klauspost/compress v1.20.2 go: downloading github.com/wlynxg/anet v0.0.5 go: downloading golang.org/x/text v0.43.0 go: downloading github.com/klauspost/compress v1.20.2 go: downloading modernc.org/sqlite v1.55.0 go: downloading github.com/aws/aws-sdk-go-v2/service/ecs v1.91.0 go: downloading github.com/pierrec/lz4/v4 v4.1.22 go: downloading modernc.org/libc v1.74.1 go: downloading modernc.org/libc v1.74.1 go: downloading modernc.org/memory v1.11.0 go: downloading github.com/dustin/go-humanize v1.0.1 go: downloading modernc.org/mathutil v1.7.1 go: downloading github.com/google/uuid v1.6.0 go: downloading github.com/dustin/go-humanize v1.0.1 go: downloading github.com/google/uuid v1.6.0 go: downloading modernc.org/mathutil v1.7.1 go: downloading github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec amadan: job cancelled — a newer push superseded it
diff --git a/.amadan/code-health.tsv b/.amadan/code-health.tsv| index 95729aa29..ec6509e54 100644 |
| --- a/.amadan/code-health.tsv |
| +++ b/.amadan/code-health.tsv |
| @@ -2198,7 +2198,7 @@ func-lines internal/host plan14RequiredArtifactsRootRunner - 374 |
| func-lines internal/host plan14TimerIntention - 315 |
| func-lines internal/host plan14TimerIntention.func1 - 311 |
| func-lines internal/host rootFilesSeedIsolatedWitness - 308 |
| -func-lines internal/host runAgent - 683 # raised: sets the activator's ConfigBeforeWake beside BeforeExec, where every wake hook is set before Start (body in configbeforewake.go); before it, #1290's continuity directory |
| +func-lines internal/host runAgent - 684 # raised: publishes the edge's backhaul refusal counters (#1535) beside the other in-process edge sources set once the edge is ready (body in backhaulshed.go) |
| func-lines internal/host runFilesSeedPreparationWithLive - 390 |
| func-lines internal/host runServingParkPeerNamespace - 538 |
| func-lines internal/host testRootMigrationBootstrap - 364 |
| @@ -2216,7 +2216,7 @@ file-lines . apimode_test.go - 3530 # raised: fdc912b (batch 2, #1123) landed be |
| file-lines internal/activator activator.go - 3785 # raised: the Service.ConfigBeforeWake field and doWakeOnce's one call to it (the body lives in configbeforewake.go); before it, #1290 step 2c |
| file-lines internal/activator activator_test.go - 5471 |
| file-lines internal/console server.go - 4051 # raised: public shares, Config.Shares (one field; the settings type and every share function live in shares.go) |
| -file-lines internal/host agent.go - 3117 |
| +file-lines internal/host agent.go - 3118 # raised: runAgent's one-line publication of the edge's backhaul refusal counters (#1535); their helpers live in backhaulshed.go |
| file-lines internal/provision reconcile_test.go - 3094 |
| file-lines internal/registry registry_test.go - 3261 |
| release-importers internal/release - - 66 # raised: scripts/pathmapcheck reads claims and edges files from the store (#186 pre-roll check) |
diff --git a/README.md b/README.md| index 6398b418c..160f5041f 100644 |
| --- a/README.md |
| +++ b/README.md |
| @@ -1093,6 +1093,54 @@ A fully-private deployment (`STATUS_PUBLIC` unset) whose console is down has |
| no page at all — the `aws s3 cp` fallback above is the entire story there; |
| nothing papers over it. |
| +## Forwarding between boxes |
| + |
| +When a request reaches a box that does not host its app, that box's edge |
| +forwards it to the box that does. This is the backhaul. Every forwarded |
| +request crosses the network twice, so each sending box limits how many it has |
| +open toward any one destination box at a time. It keeps two separate limits: |
| + |
| +- `CARLOS_BACKHAUL_MAX_INFLIGHT`: ordinary requests, 64 per destination box |
| + by default. |
| +- `CARLOS_BACKHAUL_MAX_STREAMS`: WebSockets and other upgraded connections, |
| + 128 per destination box by default. Once the destination box accepts the |
| + upgrade, the socket keeps its place until it closes, using the socket pool |
| + rather than ordinary-request capacity. The request to open it counts |
| + against ordinary-request capacity until acceptance. If the socket pool is |
| + full when the destination accepts it, the request gets `503` with |
| + `Retry-After: 2`. |
| + |
| +Set either one in the sending box's `/etc/carlos/host.env`, or as a |
| +`/carlos/<deployment>/<region>/` or `/shared/` parameter on a box launched by |
| +its region's group. Restart `carlos-edge` after changing `host.env`. A value |
| +that is not a positive whole number is logged and the default is used. |
| +Neither limit can be turned off. |
| + |
| +Keeping sockets in their own limit is what stops them crowding out ordinary |
| +requests, so the defaults stay small. Raise either limit on a sending box if |
| +its real traffic needs more. Each open socket costs about 100 KB of memory on |
| +both the sending box and the destination box. A destination box carries the |
| +sockets of every box that forwards to it, so its worst case is the sum of |
| +their limits. A single limit on the destination box, across all senders, is |
| +planned. |
| + |
| +When either limit is reached, the sending box returns `503` with |
| +`Retry-After: 2`, and its journal has a line that starts `backhaul to <box>` |
| +and names the destination box. While `CARLOS_RATE_LIMIT` is `enforce`, once |
| +the relevant backhaul pool is at least half full, one visitor address may |
| +hold at most 8 ordinary requests in the request pool or 64 sockets in the |
| +stream pool. If one quarter of that pool's limit is lower, the lower value |
| +applies. At the default stream limit of 128, the effective socket share is |
| +32. Requests over the share get `429`. The `backhaul_shed` rule is a |
| +warning in the console's alert engine. The box does not page for it. It |
| +fires when a box refuses more than 10 forwarded requests in a minute because |
| +a limit was reached, and clears after three minutes with none (see |
| +[Fleet alerts](#fleet-alerts)). Requests refused because a visitor exceeded |
| +its share do not count toward it. |
| + |
| +Server-sent events and long polls are ordinary requests here: they hold a |
| +place under `CARLOS_BACKHAUL_MAX_INFLIGHT` for as long as they stay open. |
| + |
| ## Host & process monitoring |
| Operator-grade monitoring layered on top of fleet status: real CPU, memory, |
| @@ -1222,6 +1270,7 @@ with no usable connector appear as notes on that job, not as failures. |
| | `lag`, mail relay lag | box | warning | 900 seconds, fixed | |
| | `geoip`, location database | box | warning | fixed | |
| | `engine_silent` | the console box's agent | incident | no beat for 10 minutes, fixed (`CARLOS_ALERT_ENGINE_BEAT`) | |
| +| `backhaul_shed`, forwarded requests refused | box | warning (console only) | more than 10 refused at a limit in a minute, clears after three minutes with none, fixed (see [Forwarding between boxes](#forwarding-between-boxes)) | |
| | `box_silent` | console | incident | no heartbeat for 15 minutes, editable from 5 to 1440 | |
| | `service_down` | console | incident | a platform service the fleet summary reports down | |
| | `cert_expiring` | console | warning | a served host's certificate expires within 14 days, editable from 1 to 60 | |
diff --git a/docs/superpowers/notes/census-proposal-backhaul-streams-1535.md b/docs/superpowers/notes/census-proposal-backhaul-streams-1535.md| new file mode 100644 |
| index 000000000..2675c82a3 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-backhaul-streams-1535.md |
| @@ -0,0 +1,23 @@ |
| +# Census approval: backhaul-streams-1535 |
| + |
| +Ruling `census-ruling-backhaul-streams-1535`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/edge/edge.go` `RunWithActivatorReady` | body | unchanged (5) | #1535: the edge process (carlos-edge.service, user carlos), not root: also reads CARLOS_BACKHAUL_MAX_STREAMS from the edge's own environment (root-owned host.env) through backhaulCapFromEnv (unset, unparseable or <= 0 means the default 128) into backhaulMaxStreams beside the existing CARLOS_BACKHAUL_MAX_INFLIGHT read (default unchanged, 64). Numbers only; no file, path or bucket read added; the existing 5 read sites unchanged. | |
| +| `internal/host/agent.go` `runAgent` | body | unchanged (8) | #1535: the agent: in the existing edge-ready callback (beside geoIPAlertSource and staticTreeSource) also stores the edge's in-memory backhaul shed counters getter into backhaulShedSource; an in-process function value, no read, no new authority; same 8 read sites. | |
| +| `internal/host/metrics_loop.go` `sampler.tick` | body | unchanged (1) | #1535: the agent's metrics sampler adds the in-memory backhaul shed counters (sampleBackhaulSheds, from backhaulShedSource; nil before the edge is ready and while every counter is zero) to each sample as backhaul_sheds; the samples go to the existing raw-chunk flush; no read added, same 1 read site. | |
| + |
| +Envelopes re-pinned: `internal/alerting`, `internal/edge`, `internal/host`, `internal/hostenv`, `internal/metrics`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `internal/edge/edge.go` `RunWithActivatorReady`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-certwarm-wake;basis=registers the cert warm's nudge on OnReload and on the home map's new served-hosts wake (#386); nudge only sends on a buffered channel; no read added, same 5 sites;rev3=census-ruling-edge-roll-blip;basis=the :80/:443 (and dev) listeners are bound on the calling goroutine with net.Listen via listen()/listenAddr (same empty-address defaults as ListenAndServe) before the serve goroutines, which now call Serve/ServeTLS on them, and one log line names the bound addresses; no read added, same 5 sites;rev3=census-ruling-edge-held-streams;basis=the edge in the agent (carlos-edge.service, user carlos): the inline home-map arming (newHomeMap, one boot Refresh, Store, run) moves unchanged into the new Edge.ArmHomeMap and is called here as e.ArmHomeMap(); same refresh, same timeout, same order. The reads are moved, none added.;rev3=census-ruling-agent-start-demo-1;basis=Logs the combined explicit wildcard parents through demoWildcardDomains; no new watcher or read loop.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: invoke the local admission Close before HTTP/HTTPS draining and door shutdown in both dev and normal listeners. Preserve merged main's startup behavior and its census basis; the same five read sites, no new reads.;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: defer stopping and joining the edge's replica jobs at shutdown. Existing five direct read sites unchanged; no new reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Wrap dev, HTTP and HTTPS listeners through ConfigureGroupHairpin before serving. Indirectly read protected root boot identity and group-ingress.json; kernel local/peer addresses mark local ingress, never HTTP headers. Agent edge uses verified public source for accounting; direct read sites unchanged and absent marker keeps original listeners. CI fix removes interface enumeration: local peer must match snapshot primary IPv4, an ingress IPv4 installed locally by root, or loopback; kernel destination must still be an ingress EIP on port 80/443. Merge 45cebde4 retains deferred stopReplicaProbes alongside group listener wrapping and shutdown admission closure.;rev3=census-ruling-demo-api-site-route;basis=Change the startup failure context from load routes to initialize because origin validation now runs during construction. Existing five read sites unchanged; no new read or runtime authority.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Invoke the agent shutdown timestamp hook synchronously at SIGTERM/SIGINT receipt before closing admission in dev and TLS paths. No read added.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 5: registers the https and http servers with the connection drain (conns.serve) so a drain can close idle keep-alive connections; no read added;rev3=census-ruling-warm-set-published-724;basis=#724: the inline cert warm construction (newCertWarm over warmSet and dnsGate, then OnReload and setServedWake registering warm.nudge) moves unchanged into the new Edge.newIssuerWarm in certwarm.go and is called here with the same apps domain, parents, perHostCert, warmResolver, edgeIPs and store; the loop still starts here. The warm set it wires now reads the published edges files through the home map (OwnServedHosts and ServedHosts, both already polled) instead of the local route table, regional names aside. It is a different source, not a subset: an attached name not yet published as pointing is no longer listed, while a name the route table has already dropped stays listed until this box's next edges file write and the home map's next poll catch up (HostPolicy still refuses an order for a name the registry no longer holds). A name published not pointing is not a warm candidate at all, whether or not its certificate is cached: the warm neither looks it up, orders it nor re-arms its renewal until its home box publishes it pointing again (a cached certificate keeps serving and re-arms on a handshake at the issuer). The warm reads the set only after the issuer gate, and the read is in memory (route table and the home map's last snapshot); it also drops a DNS-miss entry for a name that has left the set before probing it. It keeps a failure record while any box publishes the exact name (the home map DeployedHosts: every box's file, own included, pointing or not, the same in-memory snapshot) or the name is a regional route-table name, and prunes it only once no box publishes it. That retention set has no apps-domain or wildcard filter (those stay on candidacy only), so a name published not pointing, or one a wildcard parent starts covering, keeps the record that explains its backoff; the set is never a source of candidates. No read site added in this unit, same 5 sites.;rev3=census-ruling-w6-ingress-drain;basis=the two public servers are built by e.publicServers (internal/edge/ingressdrain.go): :443 as before (same handler, TLS config and ReadHeaderTimeout 10 s), :80 now wrapped by plainTracked so the ingress drain can count and close its requests (its barrier is never §25's); Serve's error test is listenerFailed(err) = err != nil && !errors.Is(err, http.ErrServerClosed) (was err != ErrServerClosed), so a graceful Shutdown by the drain is not fatal. New Edge.plain connDrain field. Same flags, addresses and listeners; read sites unchanged (5); no read added.;rev3=census-ruling-edge-ppv2;basis=Edge process (uid carlos), not root. Edge gains the proxy atomic.Pointer. Outside dev mode, before either public listener binds and before the ready hook hands the Edge to the agent, calls e.loadProxyIngress(os.Getenv, dataDir): CARLOS_INGRESS_PROXY_SOURCES from the edge's own environment (carlos-edge.service loads the root-owned 0600 host.env) through hostenv.ParseProxySources; blank leaves the edge unarmed with nothing read; a non-empty list arms it and Lstats <dataDir>/edge/trust-barrier (armProxyIngress); a value that does not parse is log.Fatal. After the hairpin configuration, wrapProxyIngress wraps both public listeners outermost (returns them untouched when unarmed); when armed it logs the armed line and starts runProxyJournal (counters to the journal, no reads). The existing 5 read sites are unchanged.;rev3=census-ruling-audit-request-path;basis=the dev-mode http.Server gains IdleTimeout: publicIdleTimeout (120 s) beside its ReadHeaderTimeout; comment updated. Same 5 read sites, no read added.;rev3=census-ruling-precert-dns01-1293;basis=the edge process (carlos-edge.service, user carlos), not root: after the cert warm starts, calls e.newPreIssuerFromEnv(certCache, mirror, wm) and, when it returns non-nil, starts its loop and logs one line. newPreIssuerFromEnv (precert.go) reads CARLOS_DNS01_ZONES and CARLOS_DNS01_ACCOUNTS from the edge environment (the root-owned host.env); either unset or invalid = nil, nothing else read. Only claims of the named accounts qualify. Armed, the loop runs only while this box holds the issuer gate: it lists domains/ claims in the deployment bucket through a ClaimCache, and for proven claims under the listed zones orders a certificate over DNS-01 through the existing DNS provider seam (dnsProviderFromEnv, same IAM-scoped _acme-challenge TXT writes the wildcard manager already makes), writing the result through the existing publishing cache (local acme dir + control/certs/<host>). No root read; the existing 5 read sites are unchanged.;rev3=census-ruling-alias-publish-precert-1293;basis=the edge process (carlos-edge.service, user carlos), not root: the pre-issuer start log now reads its zones from p.scope.Zones (the zones and accounts moved into the shared edge.DNS01Scope); no behaviour change, no read added, the existing 5 read sites unchanged.;rev3=census-ruling-cert-import-1429;basis=#1429: the edge process (carlos-edge.service, user carlos), not root: inserts mirror.wrapImported between perHostCert's capture and the wildcard wrap (a handshake for a name with a usable imported certificate in the mirror's memory, for a deployment host, returns chooseCert's answer over the wildcard covering the name, the <host> and <host>+rsa entries and the import: a supported CARLOS certificate first, else the import; every other name unchanged); the wildcard wrap becomes wrapGetCertificateImports, which passes exactly those imported names down instead of answering with the wildcard (in-memory predicates only: deploymentHost and the mirror snapshot); and starts the issuer-only import reconcile beside the pre-issuer (a ClaimCache.ListWithUnread prefilter rotated by a cursor across passes, then domains.ReconcileImport per host: entry revision, then claim, then DeleteIfMatch on control/certs/<host>+import only, at most 5 a pass, nothing on a failed listing). No root read; the existing 5 read sites unchanged.;rev3=census-ruling-sec-h5-edge-availability;basis=hunt H5-M5: the dev-mode server gains IdleTimeout publicIdleTimeout (120 s) beside its ReadHeaderTimeout (main since added the same value; merged, comments only); same listener, handler and addresses. No read added, same 5 sites. |
| +- `internal/host/agent.go` `runAgent`: authority, task B,C,D,F. Basis: rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 7: the startup Sweep literal hands its answer to startupSwept, which logs as before and, only on a clean sweep, marks rootfs admission swept (MarkRootfsSwept); same Sweep call, no read added;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): sets svc.Fleet = fleetWakeFor(os.Getenv, identity, identErr, fleetStore) from the identity it already resolves once and the deployment store the fleet loops already opened, and logs an ERROR naming the identity error when the box is on a fleet with an invalid identity. fleetWakeFor reads CARLOS_REGION and CARLOS_FLEET from the same environment. Read sites unchanged (6). Agent, not root; a platform box is unchanged.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: one call more beside armRunsPass, armInteractivePass(svc, reg, rolloutSink, boxJudge), in the same activator Configure hook, handing it the same box judge; fix round 1 (Astra P2, shutdown): after svc.Shutdown(ctx), shutdownInteractive(ctx) ends and joins every interactive session under the same shutdown budget; the worker's own reads are its units' (interactive.go); this body reads nothing new, the same six sites; merge of origin/main 6f1f6ca6: main's svc.Fleet = fleetWakeFor(...) and its invalid-identity ERROR line are kept as main has them (census-ruling-managed-fleets-1b); this branch's change is the same as above; read sites unchanged (6);rev3=census-ruling-fix-set-aside-exdev;basis=set-aside EXDEV fix: one field more on the agent ExecBackend literal, RawInstanceDir: layout.RawInstanceDir (a pure path join: <dataDir>/.instances/<InstanceID(host)>), so the start rule set-aside moves a copy out through the raw directory instead of through the nosymfollow bind; this body reads nothing new, the same six sites;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: one more assignment beside eb.FilesStore: eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), the agent's own environment parsed by appconfig.ParsePrivateKey as the moves pass parses it (unset or unparseable: a log line and nil, and HA publication refuses on the box). No path is opened or read, no read site added; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 4: one more goroutine beside configSyncLoop: go escrowLoop(agentCtx, reg, svc), the escrow sweep every 30 s over the same registry and Service. This body reads nothing new itself; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 5: one more call beside eb.EscrowKey: wireRawSecretPages(eb, PageOperator, metricsBoxLabel(os.Getenv, readMachineID())), which sets eb.OnRawSecret to page an operator (alerting.Page through PageOperator, LevelIncident) on its own goroutine with a 20 s timeout; metricsBoxLabel and readMachineID are the reads this body already makes for the moves refusal log; no new read site; the same six sites, offsets moved; B,C,D,F authority retained. Merge of origin/main 90c4d3aa: main's own later changes to this body are kept as main has them, under main's rulings; this branch's change is the same as above. Merge of origin/main 00bf5b8c (fleet set-aside EXDEV fix): main's change to this body is kept as main has it, under its own census ruling; this branch's change is unchanged.;rev3=census-ruling-probe-burst-limit;basis=two more sink wirings beside setAnalyticsSink: setProtectionSink(e.SetProtectionRecordOnly) and setAssetOwnersSource(e.AssetOwners), function values the telemetry pass calls; this body reads nothing new, the same six sites; authority B,C,D,F retained; no new root read or write kind;rev3=census-ruling-region-ha-p1b3a;basis=Arm HA placement exactly once on the existing Service before activatorStart and edges publication, wiring AwakeApps and the PageOperator callback; existing six read sites unchanged, no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Final review I3: start the concrete coordinator's renewal worker with agent setup; existing closeReplicaCoordinator shutdown cancels and joins it before release. No new read sites or credentials. Merge origin/main c59715e7: retain main's armHAPlacement(svc, PageOperator) wiring beside the existing activator setup; stateless coordinator and shutdown wiring remain. Same read sites; no new root read or credential.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): in the edge-ready callback, calls act.SetHeldWakeHook(e.HeldWake) when act is non-nil (installing the non-blocking wake callback) and stores e.HeldStreamsForStatus in heldStreamsSource. Wiring of in-memory callbacks only; no read added.;rev3=census-ruling-region-ha-p1b3b-t;basis=Wire Service.SetDutyView to the live edge DutySnapshot in the ready callback. No new read; no new loop or cloud operation. B2 wires the registry as the persistent DutyStore before service startup; no new cloud or filesystem path. B3b: arm one journal-backed termination consumer before service startup using agentCtx and the shared confirmer; expose edge tick and join at edge shutdown. No new direct read sites.;rev3=census-ruling-agent-start-demo-1;basis=Passes the existing registry, data store and hibernation prefix into the demo worker, and the existing instance-control client into the demo before-exec hook. No alternate data store or polling loop. Merge resolution against origin/main 9bd45488 retains main's HA departure controller, lifecycle and duty wiring alongside the demo data store and worker; no read site added by the resolution.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: install closed fixed admission before every launch source, bind activator/backend and edge, wire the real termination Started lifecycle and role reader after the change index; close before cancellation/child shutdown. No new external reads or cloud authority. Fix R1: move bind/lifecycle/edge-option wiring into wireAgentAdmission and worker listing into runWorkerBootPassAfterAdmission. Worker boot waits for admission before listing then uses unchanged bounded wakes and per-host serialization; whole Route read moves to the helper. No new storage, cloud, or root execution authority. Preserve merged main's agent wiring and census basis; the branch removes one whole Route use by moving worker iteration to the helper, with no added read kind.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: arms a fleet-only worker using the existing registry, activator, backend and authenticated console transport. Owned worker stops and joins at shutdown. No new bucket reader. merge of origin/main 9b8b2c50: retain HA duty/departure lifecycle, wake-slot and existing agent wiring alongside the replica placement worker; no new read introduced by resolution. merge of origin/main 6be08467: Retain main demo configuration, admission, build and expiry wiring alongside the replica worker; merge-only body change, no additional read. merge of origin/main 7920cccf: Retain main box-role/group admission wiring and boot publication beside the owned replica worker and shutdown; main moves the boot registry List into runWorkerBootPassAfterAdmission, removing its inline whole Route site. No new read introduced by conflict resolution.;rev3=census-ruling-stateless-replicas-3;basis=Task 1 fix round 1 M3: retain the private snapshot source and cancel/join ownership, but use the replica-health-specific retry loop. It logs its first failure only and retains the existing exponential backoff capped at 30 seconds; unsupported builds return nil. Existing five direct read sites unchanged; no new credentials, bucket reader or app lifecycle action. Fix round 1 Q20: publish Edge.ReplicaSnapshots as a separate in-memory status source, leaving the tenant-visible Upstreams source unchanged. No new external reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Load root-written group marker/configuration, configure signed boot binding and agent receipt completer, wire cancellable admission into departure work and expose cached GroupReaderSnapshot. New indirect boot reads use protected root files; agent-owned receipt controls duplicate initial completion only, never root restart permission. Same five direct sites. Merge 45cebde4 retains the replica health socket lifecycle and setReplicaSource beside GroupReaderSnapshot; no extra read beyond main.;rev3=census-ruling-agent-start-demo-2;basis=agent.go:309-329 opens demo-traffic.db beside the operator-configured registry when a demo domain exists, closes it at shutdown and wires drain-before-purge; :1010-1019 shares the worker and write gate; :1164-1177 installs the fleet identity and closed-until-worker serving callback. One added whole Route pass; the new indirect filesystem/SQL reads are claimed in openDemoTraffic and worker/store units. No request chooses the database pathname.;rev3=census-ruling-region-ha-p1b3b-s;basis=Wire the service duty view to authoritative cached sidecar manifest placement in LifetimeIndex and the edge sidecar projection; missing policy denies duty. Existing instance duty wiring remains.;rev3=census-ruling-region-ha-g2-t3;basis=T3a: wire eb.Page = PageOperator beside OwnerTerminated before departures arm, so suspect-holder pages work if departure setup fails; no new read; existing nine sites and authority unchanged; pages through the existing sink. T3b: publish the same backend through an atomic pointer for the metrics observer, and clear it on return; no new external read or authority.;rev3=census-ruling-agent-start-demo-3;basis=Wire the claim activator and root snapshot client into the demo worker; pass moved readiness to status reporting. Census read-site delta: unchanged (9).;rev3=census-ruling-region-ha-g2-fixes;basis=Wire local pool evidence, live withdrawal activator, startup ingress scan and alias publication, and edge lookup; no new direct sites; new indirect record/claim reads use existing store/judge paths described in ingress helpers.;rev3=census-ruling-region-ha-g2r-fixes;basis=W3: starts the existing record-view backstop loop with a departure-inventory listener (non-blocking, coalesced signal) even without an armed RecordView; it requests the existing full pass (backstopFullDue) there. Same nine read sites; no new read or authority.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Derive one signal-time deadline with a 90-second budget; cap departure stop and startup/seed/service shutdown joins by it. No read added.;rev3=census-ruling-static-sweep-periodic;basis=in the edge-ready callback, publishes e.LargestStaticTree in staticTreeSource for the disk alert line (diskAlertFrac in the metrics loop); in-memory wiring only, no read added; read sites unchanged (9);rev3=census-ruling-edge-page-cache-1;basis=wires the exec backend's CurrentInputs into the edge cache (wireCurrentInputs) and, in the ready hook after armEdgeAssetCache (whose returned store it now keeps), calls armEdgePageCache, which does nothing unless CARLOS_PAGE_CACHE=1; read sites unchanged (9); no read added;rev3=census-ruling-gvisor-demos;basis=Capture sandbox resolution and refusal once; log errors once; gate route admission and BeforeExec before process launch. No new root read. Task 5: pass the once-captured sandbox effective mode/config error into ExecBackend, UnitBackend and the immutable Client expectation. Same startup environment/registry reads; swapArming declines gVisor before placement. Task 8: arm read-only status projection with the existing Client.SandboxStatus callback. Agent status now queries the existing root /ready endpoint; no new root authority or guest-file input. Merge2 e8a1ddde: retain main wireCurrentInputs and armEdgePageCache through the existing asset-store ready hook alongside branch once-captured sandbox mode, wake gates and root status wiring. No new direct read; main page-cache helpers retain their own census overlays.;rev3=census-ruling-region-ha-held-build;basis=wires the drain state: svc.SetDrainingSource(boxDrain.IsDraining), svc.SetPeerDrainView(e.PeerDraining), e.SetPeerDrainedHook(svc.DropHoldersNaming); in-memory only; no read added; region HA held-requests Task 5: on group members, starts the drain driver over the activator, the edge and boxDrain, and serves its root-only drain socket; no read added beyond the socket's own Branch review r1: the drain state follows the root start fence on group members (the fence reader is the existing fenceLocation.read, a root-owned fixed path); e.SetPeerUndrainedHook(svc.AllowHoldersNaming) beside the drained hook (memory only); the drain socket serves only the agent's own user. No read added.;rev3=census-ruling-security-review-mitigations;basis=Wire the cached operator flat-layout choice into the exec backend's new-resident refusal; no read source added, existing authority retained.;rev3=census-ruling-w6-ingress-drain;basis=agent (user carlos), not root. Builds the ingress drain (newIngressDrain) with arming read at ask time from os.Getenv (CARLOS_REGION_HA, CARLOS_INGRESS_TARGET_GROUPS, both from the root-owned host.env), the fixed admission and lease.CurrentSelf (existing IMDS identity); its reader is awstg.Load, the box role's credentials calling ELB DescribeTargetHealth/DescribeTargetGroupAttributes (new AWS reads, by the agent). Wires admission.closeStartsForIngressDrain, the lbhealth drain condition, ingress.setEdge, and ingress.shutdownStarted in WithShutdownStarted. The drain socket (/run/carlos/.ha-drain/drain.sock, agent-user only, existing) is now also served on a fixed box with the drain configured (was group members only), routing /v1/ingress/* to the ingress drain and the group drain verbs to 404 there. armHADepartures now takes fixtureDepartureGetenv() and MakeQueue fixtureDepartureQueue(), which in a production (non-rootrunner) build are os.Getenv and nil, as before. Read sites unchanged (9).;rev3=census-ruling-stateless-replicas-4-task1;basis=Arms the fleet-only replica swap worker next to the placement worker: same console URL and fleet token as the existing replicaCoordinatorAPI, the existing activator Service; stops and joins at shutdown. No new read site, credential or bucket reader.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: sets deployWorker.step to the rollout scheduler answer for the record permit (replicaStepOf over armedRollout), an in-memory callback; no read site, credential or bucket reader added.;rev3=census-ruling-stateless-replicas-4-task2-fix2;basis=Task 2 fix round 2: the swap worker step is armedReplicaStep, the same lazy scheduler lookup as before as a named function; no read site added.;rev3=census-ruling-stateless-replicas-4-merge-main;basis=Merge of main 5fac2ff1: both sides changed it. Main (01d6ca78, linked-deployments-slice1) starts linkLoop beside tunnelLoop; this branch keeps its replica coordinator wiring. Both kept as-is; no read added.;rev3=census-ruling-stateless-replicas-4-final;basis=#511 final wave item 2: wires the swap worker's drive (armedReplicaDrive, the armed rollout manager's DriveReplicaRelease); no read added;rev3=census-ruling-stateless-replicas-4-merge-main2;basis=Merge of main af871da0 (v0.34.49): both sides changed it. Main (178dcfe5, member-backups-2a) moves the inline duty-view closure into armDutyView/dutyView and starts verifyAssignLoop; its sites drop by registry:Host and whole:Route x2 as main recorded them. This branch keeps its replica coordinator, swap worker and drive wiring. Both kept as-is; no read added.;rev3=census-ruling-stateless-replicas-4-drill3;basis=drill 3 R24: makes one in-memory channel, closes it (once) inside the edge's existing shutdown-started callback after ingress.shutdownStarted, and passes it to tunnelLoop, which drains only a fleet channel name; no read added, same six sites; touches no admission, lease, ingress drain, listener or file; the agent process, no root decision;rev3=census-ruling-edge-ppv2;basis=Agent (uid carlos), not root. memwatchLoop now gets edgeProxyCounters(&demoEdge) (in-process counters, no read). The drain socket's driver is newAgentDrainSocket(ingress, e, os.Getenv), which attaches the edge trust handler only when CARLOS_INGRESS_PROXY_SOURCES in the agent's environment (from the root-owned host.env) parses to a non-empty list; the socket is served when drainSocketServed: a group member or a configured ingress drain (both as before), or a box armed for PROXY protocol (new). The socket's path and agent-user-only permissions are unchanged. Read sites unchanged (6).;rev3=census-ruling-same-box-edge-fence;basis=Agent (uid carlos), not root. One added line: armEdgeFenceStatus(ctl.EdgeFence), beside the existing armExecSandboxStatus, so the layout report can ask root's /ready for the edge fence state over the control socket client the agent already holds. No read added.;rev3=census-ruling-platform-mail-submission;basis=Task 4: sets eb.Mail = mailsubmit.SocketForwarder{} on every box, and eb.MailSwitch to a mailSwitchCache's On that opens the deploy store itself through openDeployStore, retried at most once a minute with an error line until it opens (review round 1, Task 4 P3), armed for the serial-move refresh (armedMailSwitch). Task 6: also sets the ExecBackend's ManifestOf, the same staged-manifest read as TierOf (rt.App and RouteAccount(rt), hence +registry:App and +whole:Route), for the spawn-time check of decision 10, which logs and emits an event and never refuses. Agent, not root. Fable final P2-2: eb.MailSwitch is the cache's State (three-valued: on, off, unknown) in place of On; an unreadable switch is unknown, never off. No read added.;rev3=census-ruling-fleet-drain-followups;basis=P3 (#1008 T9): one call after armChangeIndex, requestBootFullPass(v, &backstopFullDue), which stores true in the existing in-memory backstopFullDue flag only when no record view is armed, so the fast loop runs its existing full pass on its first tick instead of instancesLoop a minute later; armed boxes unchanged. No read added; read sites unchanged (8); agent, not root.;rev3=census-ruling-fleet-first-reconcile-speed;basis=Startup timing log lines only: runDuties builds a step logger (newStartupLog, which reads the in-memory agent start time) and logs one line after the wait on the activator startup latch and after each existing duty before go fastConvergeLoop. One newStartupLog().at line in the edge ready hook before go tunnelLoop. No read added; read sites unchanged (8). Agent, not root.;rev3=census-ruling-ha-1192;basis=sets the group drain driver's departed hook to armedPeerDeparted (the armed departure controller's PeerDeparted: local registry identity + departure journal); no new read;rev3=census-ruling-replica-wake-gap-r3;basis=Calls lease.SetContinuityDir(<data dir>/.continuity) beside the existing obligation store: the agent's own 0700 directory for clean records, outside every instance tree (#1290 round 3). No new read; failure is logged and every start then takes a full image.;rev3=census-ruling-fleet-restart-wake;basis=Fleet restart wake Task 2: cfg.ReplicaRecord = replicaRecordFacts(boxLifetimes, cfg.Record): hands the existing judged record read (haRecordFacts over openDeployStore and boxJudge) as the live read on a lifetime index miss. No read site added here; agent, not root.;rev3=census-ruling-alias-publish-precert-1293;basis=starts edgesFileLoop with one more argument, edgeAcmeDir(os.Getenv, peekAcmeCache(args)): the agent's own -acme-cache flag (already parsed for domainsLoop) or $CARLOS_DATA_DIR/acme; a string computed from the operator's command line and environment, no read. Same 8 read sites.;rev3=census-ruling-console-addr-from-install;basis=publishes the running edge to consoleFleetEdgeSource for the heartbeat; no read added;rev3=census-ruling-instance-ready-before-wake;basis=the agent as carlos: sets svc.ConfigBeforeWake = configBeforeWake(reg, dd, claims.Writes) beside BeforeExec, before Start. Read sites unchanged, offsets moved.;rev3=census-ruling-managed-fleets-2b2;basis=takes RunAgent's one managed/BYO startup decision (decideAgentStartup, made before any fatal group preflight): a managed box gets its join (refused on an identity error or any group configuration: every admission predicate closed, edge/status/probes running, no Fatalf), never reads group configuration and never builds fixedAdmission; a BYO box reads and validates group configuration exactly as on main; binds the join as activator/exec/edge admission; ReconcileConfig.Joining on both provisioning loops; the worker boot pass runs once, at admission; Task 5: appends managedProbeOption(join) to the edge options when it is non-nil (a managed box with a valid root identity); BYO boxes unchanged; no read added; final wave: when runAgent makes the startup decision itself it also arms it (armedAgentStartup), as RunAgent does, so later group-configuration consumers follow it; no read added; merge of origin/main 173c7033: main's edge page cache arming, gVisor demos sandbox capture, region HA drain wiring and the flat-layout refusal wiring, not this branch; merge of origin/main 65951fbb: main's W6 ingress drain, linkLoop, duty view (armDutyView), replica swap worker, PPv2 drain socket, edge fence status, mail forwarder and switch, boot full pass, startup timing, peer departed hook, continuity dir, replica record facts, edges file ACME dir, console fleet edge source and ConfigBeforeWake, not this branch; code-health split: the startup decision fallback, BYO group configuration read and fixed admission build moved to agentAdmissionAtStart, the join binding to managedAdmissionOr, the boot pass branch to agentBootPass and the probe option to appendManagedProbe (managedagent.go), same calls in the same order, no read added;rev3=census-ruling-s3-polling-3;basis=The log and error shipping goroutines move unchanged into startLogLoops (internal/host/logloops.go), which also starts s3meter.LogEvery on the agent's context: an hourly log line of the process's in-memory S3 request counts. Same sinks, same label; adds no read.;rev3=census-ruling-instance-usage;basis=builds the usage meter through newUsageMeter(os.Getenv) (internal/host/instance_usage.go), which reads the env var CARLOS_INSTANCE_USAGE once (the same host.env the agent already reads) and, when it is off, calls m.DisableInstances and logs; runAgent then starts usageLoop with instances=!off so the usage loop arms the per-instance flusher (internal/host/instance_usage.go). The flusher adds one store read (spec section 12): (1) what is read: the box's own count objects usage/instances/<box>/<date>/<account>/<app>.json in the deployment bucket (or a fleet's rebased prefix), by the agent's usage flush, before each conditional write; (2) who writes them: the agent processes of the same box label through this flush; the bucket's * grant lets any platform box write any key, the same exposure as usage/edge/; tenants, apps and their credentials cannot write there, and a fleet box's store door confines it to its fleet's prefix; (3) what is checked: the body parses as v1 and its box, date, account and app match the key (usage.DecodeInstanceDay); anything else stops that object's write, is logged, and leaves the batch queued until the 24h drop horizon; (4) what it decides: only whether a batch is already merged (applied[writer]) and the totals the merge adds to; a forged object can cause an undercount or false totals, and can open, run or follow nothing;rev3=census-ruling-stage-spool-1582;basis=#1582: the agent (uid carlos, carlos-edge.service) arms through armRolloutAndStageRelay (stagerelay.go): armRolloutAndRelay, which no longer arms the relay, then the stage relay on every box; root never runs this; read sites unchanged |
| +- `internal/host/metrics_loop.go` `sampler.tick`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-remote-instance-metrics;basis=calls the owners probe before and after the unit read and tags readings with metrics.TagUnits and metrics.CarryTags; no read added;rev3=census-ruling-remote-metrics-nested;basis=clears the tenant tag of a reading marked leftover (a nested unit present at agent start) before CarryTags, and takes no CPU delta when a nested reading's set of cgroups changed since the previous tick; no read added;rev3=census-ruling-region-ha-p1b3b-t;basis=B5: Add one optional aggregate departure sample to the existing buffered sample; no per-host labels or separate writer. |
| + |
| +Seal: `83cd5238dcd073e8fc89934a72f9c60b96081f15054f32a168f6cd594c88f49c` → `dc00dc6bab094e8c81ab4e083a0b6a122ea886a70f8dca4885b5cf8a2bc3b177`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-backhaul-streams-1535.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/reviews/backhaul-streams-1535/ASTRA-CENSUS-AND-FIX-CHECK.md b/docs/superpowers/reviews/backhaul-streams-1535/ASTRA-CENSUS-AND-FIX-CHECK.md| new file mode 100644 |
| index 000000000..9a18c0961 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/backhaul-streams-1535/ASTRA-CENSUS-AND-FIX-CHECK.md |
| @@ -0,0 +1,25 @@ |
| +Reviewed `87f84c41f5155614518bd2a7ad5b9e0a11042d12` within round 2’s budget, excluding merged-main changes. No new P1 or P2 findings. |
| + |
| +**Overall census verdict: APPROVED.** |
| + |
| +| Unit / envelope / pin | Verdict | Basis | |
| +|---|---|---| |
| +| `RunWithActivatorReady` | APPROVED | [Numeric environment setting only](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/edge/edge.go:5486); existing read sites and disposition preserved. | |
| +| `runAgent` | APPROVED | [In-process counter getter](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/host/agent.go:1407); no new read or authority. | |
| +| `sampler.tick` | APPROVED | [Adds counters to the existing sample](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/host/metrics_loop.go:155); no new read. | |
| +| `internal/alerting` | APPROVED | [Rule metadata and wording](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/alerting/ruletext.go:89); no authority change. | |
| +| `internal/edge` | APPROVED | [Pool admission and response handling](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/edge/edge.go:5048); no new root input or weakened trust check. | |
| +| `internal/host` | APPROVED | [Counter sampling and failed-publication carry](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/host/metrics_loop.go:678) retain existing paths and authority. | |
| +| `internal/hostenv` | APPROVED | [One named numeric setting](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/hostenv/hostenv.go:89) added. | |
| +| `internal/metrics` | APPROVED | [Additive counters](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/metrics/backhaul.go:12) and in-memory evaluation; no new I/O authority. | |
| +| `serveAssetFar` group-name pin | APPROVED | [Function pin](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/host/group_names_test.go:541) and function unchanged in this delta; group-name checks passed. | |
| + |
| +- **Astra R2 P2: resolved.** A locally refused 101 invokes `onResponse` before returning the admission error, preserving the destination’s health observation. |
| +- **Fable R2 P2-1: resolved.** A full stream pool refuses upgrade-shaped requests before request-slot acquisition or dialling; the 101 check still handles races. |
| +- **Astra R2 P1: closed by the scope cut.** Defaults are **64 requests / 128 streams** per sender per destination. The [README](/home/paulca/amadan.net/carlos/platform-backhaul-1535/README.md:1104) agrees and identifies the aggregate receiving-side limit as future work, tracked as #1660. |
| + |
| +Targeted defaults, host, metrics, hostenv and group-name checks passed. Socket tests were blocked by sandbox listener permissions; root census tests were blocked by the read-only Go cache. Those runtime checks remain unverified here. |
| + |
| +The worktree is clean. Go’s incidental `go.mod` rewrite was restored exactly; no changes remain. |
| + |
| +FIXES CONFIRMED |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/backhaul-streams-1535/ASTRA-FINDINGS-R1.md b/docs/superpowers/reviews/backhaul-streams-1535/ASTRA-FINDINGS-R1.md| new file mode 100644 |
| index 000000000..c8373e41a |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/backhaul-streams-1535/ASTRA-FINDINGS-R1.md |
| @@ -0,0 +1,49 @@ |
| +Reviewed `583fac44fb7e..9ac6ad3e70cc9a7baf7f590664a82f1a7283383f`, round 1 of 3. |
| + |
| +1. **P1 — The larger defaults can exhaust the home box’s memory before admission refuses traffic.** |
| + **Evidence:** [edge.go:4711](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/edge/edge.go:4711) makes inbound capacity the sum of siblings’ caps; [edge.go:4745](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/edge/edge.go:4745) permits 1,024 persistent streams per sender. Local upgrades reach the ordinary reverse proxy at [edge.go:2957](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/edge/edge.go:2957), without an aggregate home-box stream budget. |
| + **Failure scenario:** 32 siblings can maintain 32,768 upgraded connections to one home. The TLS reverse-proxy copy loops alone allocate two 32-KiB buffers per connection: **2 GiB before TLS state, goroutine stacks, requests or applications**. The slice’s 80% memory ceiling therefore forces reclamation or kills on a 2-GiB home before these sender caps protect it. The tunnel’s per-channel cap does not protect locally hosted applications or aggregate multiple channels. |
| + **Fix:** Use a conservative starting default of **128 streams and retain 64 requests**, then establish the supported sibling count and measured memory budget before raising them. Arbitrarily large fleets need an aggregate receiving-side budget; no fixed per-sender number alone establishes safety. |
| + **Fault family:** Aggregate home-box resource containment. |
| + |
| +2. **P1 — A failed publish permanently consumes a shed alert’s triggering counts.** |
| + **Evidence:** [metrics_loop.go:668](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/host/metrics_loop.go:668) advances `prev` immediately. [metrics_loop.go:1097](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/host/metrics_loop.go:1097) does this before `alertTick`, which retains the old alert state when publication fails. |
| + **Failure scenario:** A tick observes 40 refusals, but publishing the firing state fails. The next quiet tick produces zero because the watch already consumed those 40. The rule remains non-firing, emits nothing, and never retries the lost warning. There is no box-sink delivery for this rule. |
| + **Fix:** Retain the pending firing transition until publication succeeds, independently of advancing the sampling baseline. Add a failed-publish → quiet-tick regression test. |
| + **Fault family:** Alert publication and observation commit ordering. |
| + |
| +3. **P2 — The concurrency test never exercises saturation or rollback contention.** |
| + **Evidence:** [backhaul_streams_test.go:270](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/edge/backhaul_streams_test.go:270) sets sixteen slots but starts only eight workers, each releasing before acquiring again. |
| + **Failure scenario:** Broken concurrent refusal or rollback accounting can pass this test because at most eight acquisitions overlap. Simply adding workers also makes its raw-counter assertion unsuitable: count-first admission deliberately allows temporary increments above the cap before rollback. |
| + **Fix:** Coordinate more contenders than slots with barriers; verify admitted holders, refusals, share accounting and final zero counts. |
| + **Fault family:** Admission-accounting test coverage. |
| + |
| +No P3 findings. |
| + |
| +The normal upgrade path selects the separate pool correctly; far asset fills explicitly retain request slots. Slot releases remain once-guarded, and refusal counters are incremented at the response-writing boundary. The metrics addition is additive JSON, uses atomics without new polling, and the console registration consistently treats the rule as a warning. |
| + |
| +Census source-review verdicts: |
| + |
| +| Unit | Verdict | Basis | |
| +|---|---|---| |
| +| `Edge.serveAssetFar` | APPROVED | [assetcatch.go:1296](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/edge/assetcatch.go:1296): request-pool selection only; existing seven read sites and owner binding unchanged. | |
| +| `RunWithActivatorReady` | APPROVED | [edge.go:5375](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/edge/edge.go:5375): numeric environment setting; existing five read sites unchanged; no new root path or authority. | |
| +| `runAgent` | APPROVED | [agent.go:1407](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/host/agent.go:1407): publishes an in-process getter; existing authority disposition and eight read sites unchanged. | |
| +| `sampler.tick` | APPROVED | [metrics_loop.go:155](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/host/metrics_loop.go:155): samples memory into the existing output path; existing read site unchanged. | |
| + |
| +| Envelope / additional pin | Verdict | Basis | |
| +|---|---|---| |
| +| `internal/alerting` | APPROVED | [ruletext.go:89](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/alerting/ruletext.go:89): copy and rule metadata only. | |
| +| `internal/edge` | APPROVED | Pool accounting and atomic counters add no root input or execution authority. Operational default issue remains finding 1. | |
| +| `internal/host` | APPROVED | Getter, sampling and alert wiring add no filesystem or store-read authority. Publication defect remains finding 2. | |
| +| `internal/hostenv` | APPROVED | [hostenv.go:89](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/hostenv/hostenv.go:89): one named numeric setting; no arbitrary environment allowance. | |
| +| `internal/metrics` | APPROVED | [backhaul.go:23](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/metrics/backhaul.go:23) and additive sample/rule fields introduce no I/O authority. | |
| +| `serveAssetFar` group-name re-pin | APPROVED | [group_names_test.go:534](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/host/group_names_test.go:534): no name derivation or owner-binding change; both group-name census tests passed. | |
| + |
| +**Overall census source-review verdict: APPROVED.** This does not clear the operational findings above. |
| + |
| +Targeted metrics, host, hostenv, classification/default and console registration tests passed. Socket-based tests were blocked by sandbox socket permissions. Root-read census and scope tests were blocked by the read-only default Go cache, so their mechanical verification remains outstanding. |
| + |
| +No tracked-file changes remain. The test command’s incidental `go.mod` rewrite was restored. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/backhaul-streams-1535/ASTRA-FINDINGS-R2.md b/docs/superpowers/reviews/backhaul-streams-1535/ASTRA-FINDINGS-R2.md| new file mode 100644 |
| index 000000000..69faf4bbf |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/backhaul-streams-1535/ASTRA-FINDINGS-R2.md |
| @@ -0,0 +1,53 @@ |
| +- **Astra R1 P1, memory defaults: partly resolved.** Defaults fell to 512 streams/128 requests; aggregate home-box safety remains unestablished. |
| +- **Astra R1 P1, failed publication: resolved.** The watch commits its baseline only after successful publication; the regression test passes. |
| +- **Astra R1 P2, contention test: resolved in source.** Barriers now coordinate 24 contenders for eight slots and check refusals, shares and releases. Execution remains sandbox-blocked. |
| +- **Fable R1 P2-1, client-controlled classification: resolved.** Admission takes a request slot; only a 101 triggers the swap. |
| +- **Fable R1 P2-2, 1024 default’s classification assumption: resolved as framed.** Classification is corrected and the default reduced; Astra’s aggregate-memory finding remains. |
| +- **Fable R1 P2-3, unscaled share: resolved.** Both shares scale to `min(share, max(1, cap/4))`. |
| + |
| +Reviewed `583fac44fb7e..fb535ebb5dd50fd0c6fd90fbdf799350ad18cd0a`, round 2. |
| + |
| +1. **P1 — The revised defaults still permit home-box memory exhaustion.** |
| + |
| + **Evidence:** [edge.go:4711](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/edge/edge.go:4711) bounds inbound traffic only by summing siblings’ caps. [edge.go:4743](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/edge/edge.go:4743) estimates socket memory but establishes neither a supported sibling count nor a receiving-side budget; [edge.go:4758](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/edge/edge.go:4758) sets 512 streams. The shared edge/instance slice has [MemoryMax=80%](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/host/units/carlos.slice:24). |
| + |
| + **Failure scenario:** 64 senders can maintain 32,768 upgraded hops to one home. The two 32-KiB proxy copy buffers alone require **2 GiB**, before TLS state, goroutine stacks, ordinary requests and applications. A 2-GiB home reaches memory pressure before these admission limits protect it. The existing absence of a direct-upgrade cap does not establish safety for this enlarged backhaul allowance. |
| + |
| + **Fix:** The R1 recommendation remains a conservative **128 streams/64 requests**, conditional on an explicit fleet-size and measured memory budget. No fixed per-sender default establishes safety for arbitrarily many siblings. |
| + |
| + **Fault family:** Aggregate home-box resource containment — repeated in rounds 1 and 2. The stopping rule now requires a decision before another fix attempt: enforce a fleet-size/memory gate, cut the capacity increase, or enforce one aggregate receiving-side budget. I recommend the aggregate budget. |
| + |
| +2. **P2 — Refusing a 101 skips the forwarder’s healthy-response observation.** |
| + |
| + **Evidence:** [edge.go:5085](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/edge/edge.go:5085) returns a stream-admission error before invoking the existing response callback. That callback [records the upstream status and holder](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/edge/forwardha.go:463). Without it, `forwardHANoted` [reports status zero](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/edge/forwardha.go:326); the placement classifier [treats that as failure](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/activator/haplacement_peers.go:101). |
| + |
| + **Failure scenario:** A placement target successfully answers 101, but the sender’s stream cap or client share refuses it. The healthy destination is then marked suspect. For a holder already reported silent during a slow handshake, the confirming response is likewise lost. |
| + |
| + **Fix:** Preserve the upstream-response observation before returning the local stream refusal. Keep the refusal interception that prevents retries. Add a regression covering a successful upstream 101 rejected by local stream admission. |
| + |
| + **Fault family:** Local admission failures contaminating destination-health observations. |
| + |
| +No P3 findings. |
| + |
| +Census verdicts for the reviewed commit: |
| + |
| +| Unit | Verdict | Basis | |
| +|---|---|---| |
| +| `RunWithActivatorReady` | APPROVED | [edge.go:5438](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/edge/edge.go:5438): numeric environment configuration; existing read sites and disposition preserved. | |
| +| `runAgent` | APPROVED | [agent.go:1407](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/host/agent.go:1407): publishes an in-process getter; no new root input or authority. | |
| +| `sampler.tick` | APPROVED | [metrics_loop.go:155](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/host/metrics_loop.go:155): adds in-memory counters to the existing sample; no new external read. | |
| + |
| +| Envelope / additional pin | Verdict | Basis | |
| +|---|---|---| |
| +| `internal/alerting` | APPROVED | [ruletext.go:89](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/alerting/ruletext.go:89): rule metadata and copy only. | |
| +| `internal/edge` | APPROVED | [edge.go:4832](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/edge/edge.go:4832): pool accounting, response handling and counters introduce no new root input or execution authority. Operational findings remain above. | |
| +| `internal/host` | APPROVED | [metrics_loop.go:671](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/host/metrics_loop.go:671): observation and publication ordering use existing paths and authority. | |
| +| `internal/hostenv` | APPROVED | [hostenv.go:89](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/hostenv/hostenv.go:89): one specific numeric setting added. | |
| +| `internal/metrics` | APPROVED | [backhaul.go:12](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/metrics/backhaul.go:12), [alert.go:491](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/metrics/alert.go:491): additive data and in-memory evaluation; no I/O authority. | |
| +| `serveAssetFar` group-name pin | APPROVED | [group_names_test.go:533](/home/paulca/amadan.net/carlos/platform-backhaul-1535/internal/host/group_names_test.go:533): both the function and pin are unchanged from the review base after R2. | |
| + |
| +**Overall census verdict: APPROVED.** This does not clear the operational findings. |
| + |
| +Targeted census, group-name census, metrics, host, hostenv, default-value and console-registration checks passed, as did the enabled code-health gate. Socket-based tests were blocked by sandbox listener permissions; their runtime behavior remains unverified here. No files were edited; tracked working-tree and index diffs remain empty. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/backhaul-streams-1535/CENSUS-AND-FIX-CHECK.md b/docs/superpowers/reviews/backhaul-streams-1535/CENSUS-AND-FIX-CHECK.md| new file mode 100644 |
| index 000000000..a4f621e0c |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/backhaul-streams-1535/CENSUS-AND-FIX-CHECK.md |
| @@ -0,0 +1,11 @@ |
| +# Census and fix check: backhaul-streams-1535 (within round 2's budget; no round 3) |
| + |
| +8a3d302 cut scope after round 2 (2026-12-02): split pools with sockets classified on the 101 is the fix; requests stay at 64 and sockets get 128 per sending edge per home box; the receiving-side aggregate budget is follow-up #1660. Merge after the P2 fixes, Astra's census check and green CI; no fourth round. Your round-2 findings: ASTRA-FINDINGS-R2.md in this directory. |
| + |
| +Read the delta `git diff fb535ebb5dd50fd0c6fd90fbdf799350ad18cd0a HEAD -- . ':!docs/superpowers/reviews'` (it includes a merge of main; review only this branch's changes in it). |
| + |
| +1. **Census:** verdict per unit and envelope on docs/superpowers/notes/census-proposal-backhaul-streams-1535.md, and on the group-name pin. Overall APPROVED / REJECTED. |
| +2. **Fix check:** one line each: your R2 P2 (a 101 refused locally keeps the destination's health observation): resolved, partly, not; Fable R2 P2-1 (refuse before dialling when the stream pool is full): resolved, partly, not. Your R2 P1 is closed by the scope cut (defaults 64/128 plus #1660); confirm the defaults and docs say that. |
| +3. A new finding only if this delta introduced it and it is unsafe (P1) or wrong (P2). Known and filed, not to be raised: a refusal at the sender's own admission on the region-HA forward path still notes status 0 (#1662; the request-pool case predates this branch). |
| + |
| +End with one line: FIXES CONFIRMED or FIXES NOT CONFIRMED. Do not edit files; targeted tests only. |
diff --git a/docs/superpowers/reviews/backhaul-streams-1535/FABLE-FINDINGS-R1.md b/docs/superpowers/reviews/backhaul-streams-1535/FABLE-FINDINGS-R1.md| new file mode 100644 |
| index 000000000..e92ba0496 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/backhaul-streams-1535/FABLE-FINDINGS-R1.md |
| @@ -0,0 +1,47 @@ |
| +# Review R1: backhaul stream pool (#1535), commit 9ac6ad3e7 |
| + |
| +No P1. Targeted tests pass: `go test ./internal/edge/ -run Backhaul`, plus the Backhaul/alert tests in `internal/metrics`, `internal/host`, `internal/hostenv` and `internal/console`. Census skipped as instructed. |
| + |
| +## P1 |
| + |
| +None. |
| + |
| +## P2 |
| + |
| +**P2-1. The Upgrade header buys any request out of the request pool (brief item 1).** |
| +- **Problem:** the pool is chosen from the request alone, with no method, body or response check. Any request sent with `Connection: Upgrade` and `Upgrade: x` takes a stream slot and keeps it for its whole response when the home answers 200. |
| +- **Evidence:** `internal/edge/edge.go:4800-4803` (the predicate), `edge.go:5085-5086` (pool choice at admission), `edge.go:5030-5036` (slot held until `ServeHTTP` returns). The code comment at `edge.go:4797-4799` accepts this on the grounds that the stream pool is "just as capped". The home edge's own ruling says the opposite at `edge.go:2919-2926`: "the header is the client's to send, so it must not buy a slow request out of the busy count", and it releases only at the 101 hijack. |
| +- **Failure scenario:** one address adds the two headers to ordinary large GETs. It holds 512 concurrent byte-carrying hops toward one home box before any share applies (busy starts at `limit/2`, `edge.go:4903`), then 64 more per extra address up to 1024. The honest request pool allows it 128, then 8. So the egress ruling's bound (`edge.go:4702-4706`, concurrent streams × bandwidth) is 1024 bulk transfers per sender per home box, not the 256 the README states for ordinary requests. The same trick lets SSE and long polls dodge the request pool, which the README says they hold (`README.md`, "Server-sent events and long polls are ordinary requests here"). |
| +- **Fix:** follow the home edge's precedent and classify on the 101. Either admit an upgrade request on a request slot and swap to a stream slot in `ModifyResponse` when `resp.StatusCode == 101` (503 if the stream pool is full); or keep the stream slot at admission and swap to a request slot on any non-101 final answer. Add a test: upgrade headers plus a 200 body must end up counted in the request pool. |
| +- **Fault family:** client-controlled classification. |
| + |
| +**P2-2. Default of 1024 streams is only justified once P2-1 is fixed (brief item 3).** |
| +- **Problem:** as real idle sockets, 1024 per sender is acceptable on memory. As 1024 possible bulk transfers it is 16 times the 2026-08-24 ruling's 64. |
| +- **Evidence:** `edge.go:4745` (`defaultBackhaulMaxStreams = 1024`), `edge.go:4712-4714` (bound is the sum of both pools over every sibling). The home edge has no cap of its own on direct client upgrades (`internal/edge/planthrottle.go:85-92` only refuses throttled accounts), so hop sockets add no exposure that direct sockets do not already have. |
| +- **Memory estimate (not measured):** roughly 100 KB per upgraded hop on each box, from the proxy's two 32 KB copy buffers, bufio, three goroutine stacks and TLS state. That is about 100 MB per sender on the home box at a full pool, or about 400 MB with four siblings, and the same per home box on the sender. |
| +- **Fix:** keep 1024 if P2-1 lands. If P2-1 is deferred, ship 256 streams so the worst case stays near the request default, and record the per-socket cost in the `backhaulMaxStreams` doc. |
| +- **Fault family:** default sized on an assumption the code does not enforce. |
| + |
| +**P2-3. A lowered stream cap silently loses the fair share.** |
| +- **Problem:** the share is a constant 64 regardless of the configured cap. |
| +- **Evidence:** `edge.go:4788` (`backhaulStreamClientShare = 64`), `edge.go:4840` (passed unscaled), `edge.go:4903-4904` (refuses only when held ≥ share while busy). |
| +- **Failure scenario:** an operator sets `CARLOS_BACKHAUL_MAX_STREAMS=64` (the old cap). One client can then take all 64 slots, which is the incident shape again, for sockets. At 100, one client holds 64 of 100. |
| +- **Fix:** use `min(backhaulStreamClientShare, max(1, limit/4))` or similar in `streamPool()`, with a test at a small cap. The README sentence "64 sockets once half used" needs the same qualifier. |
| +- **Fault family:** constant not scaled with its knob. |
| + |
| +## P3 |
| + |
| +- **Lost reading on a failed publish.** `backhaulShedWatch.read` advances `prev` (`internal/host/metrics_loop.go:669`) before `alertTick` knows whether the publish succeeded. When it fails, the state does not advance (`metrics_loop.go:617-621`) but the delta is gone. A one-minute burst that coincides with a store error never fires. Every other rule re-evaluates from a level reading. |
| +- **Flapping.** The rule fires at more than 10 and clears on the first zero tick with no sustain (`internal/metrics/alert.go:486-497`). Bursts on alternate minutes notify on every cycle. Fair-share 429s count too (`edge.go:5100`), so one scraper being correctly limited raises "Visitors are already getting errors" (`internal/alerting/ruletext.go:103`). Consider counting only the two saturation kinds toward the rule, or holding the clear for a few quiet ticks. |
| +- **Two upgrade predicates.** `isUpgradeRequest` (`edge.go:3138`, Connection token only) and `backhaulUpgrade` (`edge.go:4800`, token plus Upgrade header) now coexist. The retry path uses the first (`internal/edge/backhaul_holder.go:292`). It is safe today, since the mismatch lands in the request pool, but one should be defined in terms of the other. |
| +- **Sample size.** Every sample on every box now carries `backhaul_sheds` with three zeros once the edge is ready, including single-box deployments (`internal/host/agent.go:4927-4934`). Returning nil while all three are zero would keep old chunks byte-identical. |
| +- **Tests (brief item 6).** `TestBackhaulWebSocketsDoNotStarveRequests` (`internal/edge/backhaul_streams_test.go:448`) does prove the incident through the real handler. Missing: the P2-1 case, the share at a small cap, and a share test through `backhaulAdmit` with real client addresses (the current share tests call `backhaulAcquireStream` with a literal key, `backhaul_streams_test.go:557`). |
| + |
| +## Checked and clean |
| + |
| +- **Classification otherwise (item 1).** The predicate matches `ReverseProxy`'s `upgradeType` and the transport's HTTP/1.1 forcing. `backhaulProxy` uses `Rewrite` (`edge.go:5238`), so the proxy reads the same headers admission did. HTTP/2 clients cannot send `Connection`. Door and tunnel callers stay unkeyed as before (`edge.go:4813`). Far asset fills are pinned to the request pool (`internal/edge/assetcatch.go:1296`). |
| +- **Accounting (item 2).** Count-first with rollback on both refusals, a once-guarded release, and observe mode re-acquiring unconditionally (`edge.go:4886-4928`). Each refusal is counted once, in `backhaulAdmitPool` only (`edge.go:5097-5113`), and observe mode is not counted. |
| +- **Metric seam (item 4).** Atomics only, no store reads or new polling. The watch lives on the metrics loop goroutine alone (`metrics_loop.go:1048`, `1097`). A counter reset counts from zero (`internal/metrics/backhaul.go:28-30`). A nil reading holds the state. The new JSON field is `omitempty` and nothing in the read path uses `DisallowUnknownFields`. The box sink does not page for it (`internal/host/disktrend.go:103-105`). |
| +- **Console (item 5).** Level, order, copy, page copy and valued entries are all present. The console reads box rules generically (`internal/console/alertsignals.go:400-408`), so an older console shows it as a warning with a bare title. |
| + |
| +**Verdict: READY AFTER FIXES** |
diff --git a/docs/superpowers/reviews/backhaul-streams-1535/FABLE-FINDINGS-R2.md b/docs/superpowers/reviews/backhaul-streams-1535/FABLE-FINDINGS-R2.md| new file mode 100644 |
| index 000000000..e683f9d4d |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/backhaul-streams-1535/FABLE-FINDINGS-R2.md |
| @@ -0,0 +1,60 @@ |
| +# Review R2: backhaul stream pool (#1535), commit fb535ebb5 |
| + |
| +No P1. One new P2, in the 101 swap. Targeted tests pass in `internal/edge` (`Backhaul|AssetFar|Handover`), `internal/metrics`, `internal/host`, `internal/hostenv` and `internal/console`. I did not run `-race`. Census skipped as instructed. |
| + |
| +## Round 1 findings |
| + |
| +| Finding | Status | Evidence | |
| +|---|---|---| |
| +| Astra P1-1, home-box memory defaults | Partly | Now 512 streams and 128 requests (`internal/edge/edge.go:4758`, `4726`), not the 128 and 64 asked for. No aggregate receiving-side budget, and the cost is estimated, not measured (`edge.go:4743`). The parity argument holds: the home edge does not cap direct upgrades. Residue is P3-1 and P3-2, not a blocker. | |
| +| Astra P1-2, alert lost on failed publish | Resolved | The watch commits only when `alertTick` returns nil (`internal/host/metrics_loop.go:671-681`), and `alertTick` returns only the publish error (`metrics_loop.go:630`). Pinned by `TestBackhaulShedFiresAfterAFailedPublish` (`internal/host/metrics_backhaul_test.go:203`). | |
| +| Astra P2-3, contention test | Resolved | 24 contenders on 8 slots behind a barrier, checking holders, shares, zero counts and refusal counts (`internal/edge/backhaul_streams_test.go:331`). | |
| +| Fable P2-1, client-controlled classification | Resolved | Every hop is admitted on a request slot and swaps at the 101 (`edge.go:5084-5098`). Pinned by `TestBackhaulUpgradeRequestAnswered200StaysInRequestPool` (`backhaul_streams_test.go:674`). | |
| +| Fable P2-2, 1024 default | Resolved | 512, with the per-socket cost in the doc (`edge.go:4743-4751`). | |
| +| Fable P2-3, unscaled share | Resolved | `backhaulShare` caps the share at a quarter of the limit (`edge.go:4807`). Tested at a small cap (`backhaul_streams_test.go:220`, `718`). | |
| + |
| +## P1 |
| + |
| +None. |
| + |
| +## P2 |
| + |
| +**P2-1. A full stream pool no longer refuses without dialling, so socket retries spend request slots.** |
| +- **Problem:** the stream refusal now happens only after the home has answered 101. Every over-cap socket attempt holds a request slot for the whole handshake and opens a fresh TLS connection across the region. It also reaches the app, which accepts the socket and is then cut off. |
| +- **Evidence:** |
| + - Admission is request-pool only (`edge.go:5045`), and the stream pool is first consulted inside `ModifyResponse` (`edge.go:5085-5089`). |
| + - The test requires the dial: "it must be refused at the 101, not at admission" (`backhaul_streams_test.go:648-650`). |
| + - The containment ruling still says a hop at the limit is answered "rather than dialling" (`edge.go:4692`). |
| + - The handshake wait is bounded only by `backhaulHeaderTimeout`, 30 s (`edge.go:4994`). |
| +- **Failure scenario:** 512 sockets are open toward one home box and several hundred more clients reconnect on backoff. Each attempt holds a request slot until the app answers the handshake. If the app is slowed by that churn to about a second per handshake, around 128 attempts a second fill the request pool and ordinary requests get 503. That is the incident's shape again, driven by sockets. Short of that, a sleeping instance is woken by sockets that are refused straight away. |
| +- **Fix:** keep the slot swap at the 101, and add an advisory check at admission. If the request is upgrade-shaped and the box's stream counter is already at the cap, answer `backhaul-streams-busy` with no dial and count it as a stream shed. The header only gets a client refused earlier, so Fable P2-1 stays closed. Re-pin the test: no dial when the pool is already full, with the 101 refusal kept for the race. |
| +- **Fault family:** refusal placed after the cost it bounds. |
| + |
| +## P3 |
| + |
| +- **P3-1. Unbounded catch-up in the shed watch.** The comment says a held-back count "may count two minutes" (`metrics_loop.go:669-670`). A store outage of any length fails every tick that has an event, so `prev` never advances. A trickle of 11 refusals over hours then fires "more than 10 in a minute" on recovery. Either cap the carry to the pending firing transition or correct the comment. |
| +- **P3-2. Sender-side sum missing from the doc.** The `backhaulMaxStreams` doc sums the cost over siblings for the home box (`edge.go:4749-4751`). It does not say the sender pays about 50 MB per destination box, so its worst case scales with the number of home boxes. |
| +- **P3-3. No reason given for 128.** The doc says the request pool "holds no open sockets, and its default is 128" (`edge.go:4700`). With sockets gone, 64 already has more headroom than before. The doubling of the 2026-08-24 bulk-transfer bound needs its reason stated (presumably SSE and long polls) or should go back to 64. |
| +- **P3-4. Stale value while firing.** `RuleState.Value` keeps the first reading for as long as the rule fires (`internal/metrics/alert.go:498-500`), so a worsening shed shows the opening count. |
| +- **P3-5. Two upgrade predicates remain.** The R1 P3 on `isUpgradeRequest` still stands and is now harmless, since classification is by response. The P2-1 fix should reuse it, not add a third. |
| + |
| +## Checked and clean |
| + |
| +- **101 swap.** |
| + - It acquires the stream slot before releasing the request slot, on the `ServeHTTP` goroutine, with one deferred release of whichever slot is held (`edge.go:5054-5055`, `5090-5092`). |
| + - A refusal returns before `onResponse` or the scrub runs, and the stdlib closes the backend connection. |
| + - A 101 that the proxy then rejects for a protocol mismatch releases its stream slot through the defer. |
| +- **Holder and forward hooks.** |
| + - Stream errors are answered before `onError`, so the holder path sets no retry target and drops no holder (`internal/edge/backhaul_holder.go:298-317`). |
| + - On the forward path the result keeps status 0 with no holder, which the holder cache treats as no information (`internal/activator/hacache.go:516-521`). |
| + - Holder and handover retries fire only on a 503 at the transport, never on a 101. |
| +- **Accounting.** Each refusal is counted once: request-pool refusals in `backhaulAdmit`, stream-pool refusals in `backhaulStreamAt101`. Door callers stay unkeyed (`backhaul_streams_test.go:755`). |
| +- **Alert.** |
| + - It holds through two quiet minutes and clears on the third (`alert.go:491-503`). |
| + - A nil reading holds the state. |
| + - A restored fire clears because the loop reads the counters directly, not the sample's nil-when-zero copy (`metrics_loop.go:1107-1113`). |
| + - Fair-share 429s are excluded from the rule (`internal/metrics/backhaul.go:20`). |
| + - Quiet boxes' samples are unchanged (`internal/host/agent.go:4938-4944`). |
| +- **Console.** Level, order, valued entry, value text and copy are all registered, and the console tests pass. |
| + |
| +**Verdict: READY AFTER FIXES** |
diff --git a/docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-BRIEF-1.md b/docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-BRIEF-1.md| new file mode 100644 |
| index 000000000..86d0f6db0 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-BRIEF-1.md |
| @@ -0,0 +1,15 @@ |
| +# Copy review: backhaul shed alert and settings (#1535), Luna pass 1 |
| + |
| +You are the copy-review gate; Paul delegated copy review to Luna. Do not run any copy-review skill or start a server. |
| + |
| +Feature: when a CARLOS box forwards ("backhauls") requests to the box that runs an app and too many are already in flight, it refuses with 503 or 429. WebSockets now have their own limit (CARLOS_BACKHAUL_MAX_STREAMS) separate from ordinary requests (CARLOS_BACKHAUL_MAX_INFLIGHT), and a new box alert rule `backhaul_shed` fires when a box refuses more than 10 forwarded requests in a minute. Readers: deployment operators. |
| + |
| +Review: |
| +1. internal/alerting/ruletext.go: the BackhaulShed* constants. |
| +2. The console's copy for the rule (grep backhaul_shed in internal/console: alertCopy, alertPageCopy, alertValueText). |
| +3. README.md: the section "Forwarding between boxes" and the backhaul_shed row in the Fleet alerts rule table. |
| +4. Edge journal lines in internal/edge/edge.go containing "backhaul to" and the env fallback line for these two settings (operator-facing logs; keep the facts, may keep technical terms). |
| + |
| +Facts to keep: the box itself does not page for this rule (warning through the console's alert engine); the threshold is fixed (more than 10 in a minute), clears after a minute with none; raising a limit is done in host.env, or as a /carlos/<deployment>/<region>/ or /shared/ parameter on a box its region's group launched. |
| + |
| +House voice: plain, direct, no em dashes, sentence case. Answer with a table key | new text (or approved) | why; full text for changed paragraphs; then flags for substance. Do not edit files. |
diff --git a/docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-BRIEF-2.md b/docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-BRIEF-2.md| new file mode 100644 |
| index 000000000..333581e2a |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-BRIEF-2.md |
| @@ -0,0 +1,3 @@ |
| +# Copy review: backhaul shed alert (#1535), Luna pass 2 |
| + |
| +You are the copy-review gate (Paul's delegation). Do not run any copy-review skill or start a server. Your pass 1 is in LUNA-COPY-RESULT-1.md in this directory and is applied. Review ONLY the strings marked "adjusted after Luna pass 1" (a Go comment in internal/alerting/ruletext.go, HTML comments in README.md) plus the README defaults and the new socket sentence. They changed because the fix changed: only refusals at a limit (503) count toward the rule, not a visitor's fair-share 429s; it clears after three minutes with none; defaults are 128 requests and 512 sockets; the share is 8 requests or 64 sockets, or a quarter of the limit if fewer; a socket request counts as an ordinary request until the destination box accepts it; alert text is plain text (no backticks). Answer: key | new text or approved | why; then substance flags. Do not edit files. |
diff --git a/docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-BRIEF-3.md b/docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-BRIEF-3.md| new file mode 100644 |
| index 000000000..e5d0ea09c |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-BRIEF-3.md |
| @@ -0,0 +1,3 @@ |
| +# Copy review: backhaul limits (#1535), Luna pass 3 |
| + |
| +You are the copy-review gate (Paul's delegation). Do not run any copy-review skill or start a server. Passes 1 and 2 are applied (LUNA-COPY-RESULT-1.md, -2.md in this directory). Review ONLY the README strings marked "adjusted after Luna pass 2" or "added after Luna pass 2" in the "Forwarding between boxes" section. Facts: defaults are 64 ordinary requests and 128 sockets per sending box per destination box; the split is the fix, so defaults stay small; raise a limit per sending box in host.env or as a group parameter; about 100 KB per open socket on each box; a destination box's worst case is the sum over the boxes forwarding to it; a single destination-side limit is planned. Also say whether the fair-share sentence should state the effective socket share at the 128 default (32, a quarter of the limit). Answer: key | new text or approved | why; then substance flags. Do not edit files. |
diff --git a/docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-RESULT-1.md b/docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-RESULT-1.md| new file mode 100644 |
| index 000000000..4b51b2d86 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-RESULT-1.md |
| @@ -0,0 +1,32 @@ |
| +Verdict: changes required before approval. |
| + |
| +| Key | New text (or approved) | Why | |
| +|---|---|---| |
| +| `BackhaulShedTitle` | Approved: “Forwarded requests refused” | Clear and sentence case. | |
| +| `BackhaulShedHowLong` | “Forwarded requests are being refused while the limit is reached. This is a warning in the console's alert engine. The box does not page for it.” | Adds the required delivery distinction and removes vague “visitors.” | |
| +| `BackhaulShedWhatToDo` | “Read the box's journal for `backhaul to` lines. They show which destination box was limiting traffic and why. If traffic needs more room, raise the relevant limit in `host.env`, or set it as a `/carlos/<deployment>/<region>/` or `/shared/` parameter on a box launched by its region's group.” | “Full” is inaccurate for fair-share refusals. Includes both supported configuration paths. | |
| +| `BackhaulShedWhat`, `BackhaulShedWhatNone` | “`%s refused forwarded requests.” / “A box refused forwarded requests.” | Shorter and more direct. | |
| +| `BackhaulShedWhen` | “A box refuses more than 10 forwarded requests in a minute.” | Removes the awkward relative clause. | |
| +| `BackhaulShedThreshold` | “Fixed at more than 10 forwarded requests in a minute. Clears after a minute with none. Not configurable.” | Makes the measured thing explicit. | |
| +| `BackhaulShedValue` | “`%d forwarded requests refused in a minute`” | Clearer standalone value. | |
| +| Console `alertCopy` | Approved as wiring. It already uses the `alerting.BackhaulShed*` strings. | The revised constants will flow through automatically. | |
| +| Console `alertPageCopy` | Approved as wiring. It already uses `BackhaulShedWhen` and `BackhaulShedThreshold`. | No separate copy is needed. | |
| +| Console `alertValueText` | Use the revised `BackhaulShedValue`. | Keeps the displayed measurement clear. | |
| +| README configuration paragraph | See full text below. | Current text omits parameter-based configuration. | |
| +| README alert paragraph | See full text below. | Current text omits that this is console-only and not a box page. | |
| +| Fleet alerts row | Change severity to `warning (console only)`. | Makes delivery unambiguous in the table. | |
| +| Edge journal lines containing `backhaul to` | Replace the em dash with a semicolon: `... holds %d of them; %s the request ...`; and `... cap (...); answering 503 with Retry-After: 2`. | Matches the house voice while preserving technical facts. | |
| +| Environment fallback log | `edge: %s=%q is not a positive integer; using the default of %d %s` | Removes the em dash and keeps the diagnostic precise. | |
| + |
| +Full changed README paragraphs: |
| + |
| +> Set either one in the sending box's `/etc/carlos/host.env`, or as a `/carlos/<deployment>/<region>/` or `/shared/` parameter on a box launched by its region's group. Restart `carlos-edge` after changing `host.env`. A value that is not a positive whole number is logged and the default is used. Neither limit can be turned off. |
| + |
| +> When either limit is reached, the sending box returns `503` with `Retry-After: 2`, and its journal has a line that starts `backhaul to <box>` and names the destination box. While `CARLOS_RATE_LIMIT` is `enforce`, one visitor address may also hold at most 8 ordinary requests, or 64 sockets, once that limit is half used. More than that gets `429`. The `backhaul_shed` rule is a warning in the console's alert engine. The box does not page for it. It fires when a box refuses more than 10 forwarded requests in a minute and clears after a minute with none (see [Fleet alerts](#fleet-alerts)). |
| + |
| +Substance flags: |
| + |
| +- The current copy does not say that `backhaul_shed` is console-only and does not page from the box. |
| +- The current copy documents only `host.env`, omitting the `/carlos/<deployment>/<region>/` and `/shared/` parameter sources. |
| +- “Which box was full” overstates fair-share refusals, which occur when a box is at least half full and a client exceeds its share. |
| +- The current operator-facing log lines use em dashes, contrary to the brief’s voice requirement. |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-RESULT-2.md b/docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-RESULT-2.md| new file mode 100644 |
| index 000000000..e1d69f7d2 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-RESULT-2.md |
| @@ -0,0 +1,17 @@ |
| +Verdict: changes required before approval. |
| + |
| +| Key | New text or approved | Why | |
| +|---|---|---| |
| +| `BackhaulShedWhatToDo` plain-text adjustment | Approved | The alert string uses quotes/plain text and no backticks. | |
| +| `BackhaulShedWhen` | Approved | Clearly identifies refusals caused by a reached destination limit. | |
| +| `BackhaulShedThreshold` | “Fixed at more than 10 forwarded requests refused because a limit was reached in one minute. Clears after three minutes with none. Not configurable.” | “Refused at the limit” is awkward and less direct. | |
| +| README defaults | Approved | 128 ordinary requests and 512 sockets are clear. | |
| +| README socket explanation | “Once the destination box accepts the upgrade, the socket keeps its place until it closes, using the socket pool rather than ordinary-request capacity. The request to open it counts against ordinary-request capacity until acceptance. If the socket pool is full when the destination accepts it, the request gets `503` with `Retry-After: 2`.” | Makes the request-slot-to-socket-slot handoff unambiguous. | |
| +| README fair-share sentence | “While `CARLOS_RATE_LIMIT` is `enforce`, once the relevant backhaul pool is at least half full, one visitor address may hold at most 8 ordinary requests in the request pool or 64 sockets in the stream pool. If one quarter of that pool's limit is lower, the lower value applies. Requests over the share get `429`.” | The current “that limit” and “that is fewer” are ambiguous about which pool they describe. | |
| +| README exclusion sentence | “Requests refused because a visitor exceeded its share do not count toward it.” | A visitor is not itself refused; its requests are. | |
| + |
| +Substance flags: |
| + |
| +- The current fair-share wording could make an operator apply the request share to sockets or vice versa. |
| +- The socket wording should state explicitly that the request occupies ordinary-request capacity until the destination accepts the upgrade. |
| +- No files were edited. |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-RESULT-3.md b/docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-RESULT-3.md| new file mode 100644 |
| index 000000000..38e835abf |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/backhaul-streams-1535/LUNA-COPY-RESULT-3.md |
| @@ -0,0 +1,13 @@ |
| +Verdict: changes required before approval. |
| + |
| +| Key | New text or approved | Why | |
| +|---|---|---| |
| +| `CARLOS_BACKHAUL_MAX_INFLIGHT` | Approved | Correctly states 64 ordinary requests per destination by default. | |
| +| `CARLOS_BACKHAUL_MAX_STREAMS` | Approved | Correctly states 128 sockets per destination by default and explains the pool handoff. | |
| +| Backhaul capacity paragraph | Approved | Accurately explains the split, per-sending-box tuning, ~100 KB per socket on both boxes, aggregate destination exposure, and planned destination-side limit. | |
| +| Fair-share sentence | “While `CARLOS_RATE_LIMIT` is `enforce`, once the relevant backhaul pool is at least half full, one visitor address may hold at most 8 ordinary requests in the request pool or 64 sockets in the stream pool. If one quarter of that pool's limit is lower, the lower value applies. At the default stream limit of 128, the effective socket share is 32. Requests over the share get `429`.” | The current wording presents 64 as the apparent socket allowance but does not state that the quarter-limit rule reduces it to 32 at the default. | |
| + |
| +Substance flags: |
| + |
| +- The only remaining issue is the fair-share sentence’s effective default socket share. |
| +- No other substance issues found in the marked strings. |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/backhaul-streams-1535/REVIEW-BRIEF-R1.md b/docs/superpowers/reviews/backhaul-streams-1535/REVIEW-BRIEF-R1.md| new file mode 100644 |
| index 000000000..38b3542d4 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/backhaul-streams-1535/REVIEW-BRIEF-R1.md |
| @@ -0,0 +1,31 @@ |
| +# Review brief: backhaul stream pool (#1535), round 1 of 3 |
| + |
| +Repo carlos/platform, branch `backhaul-streams-1535`, commit named in your prompt. Under review: the diff `583fac44fb7e..HEAD` (git diff 583fac44 HEAD -- . ':!docs/superpowers/reviews'). Authorities: everything on main, especially internal/edge/edge.go's backhaul containment ruling (backhaulMaxInflight doc), backhaul-share, and the metrics/alert path (internal/metrics, internal/host/metrics_loop.go, alertsink.go, internal/alerting, the console's alert engine). |
| + |
| +Incident (amadan #1535): upgraded websocket responses hold a backhaul slot for the socket's life, so ~64 open sockets filled the per-home-box in-flight cap and every ordinary request to that home box got 503 for two hours. The fix: upgrade requests take slots from a separate per-box stream pool (CARLOS_BACKHAUL_MAX_STREAMS, default 1024, per-client share 64 once half full); the request/response default rises 64 -> 256; refusals are counted in-process and raise a `backhaul_shed` box alert (warning, via the console's alert engine, not the box's own sink) through the existing metrics sample path. |
| + |
| +## Fixed: do not re-argue |
| +- Containment stays: there is still a finite bound per home box on each pool; no "off" value. |
| +- SSE / long-poll responses are not reclassified in this slice (documented follow-up). |
| +- The alert is a warning through the existing console alert engine, not a box-sink page. |
| + |
| +## What to check |
| +1. Classification: can a client get a request onto the stream pool or vice versa in a way that defeats containment or fairness (header tricks, upgrade without 101, HTTP/2 hops, door/tunnel callers)? Is the upgrade test identical to what ReverseProxy actually treats as an upgrade? |
| +2. Accounting: no slot or share drift in either pool (count-first-rollback, release once, observe/enforce modes, concurrent paths), and every refusal counted exactly once. |
| +3. The home box: the inbound bound is now sum of siblings' (request + stream) caps. Is 1024 streams per sender per home box with 256 requests a safe default for the home box's memory (each hop costs the home box a TLS conn, proxy goroutines and buffers, and for a fleet hub a tunnel stream onward)? If not, say what default is. |
| +4. The shed metric seam (agent.go edge-ready callback -> backhaulShedSource -> sampler -> backhaulShedWatch -> alertTick -> Evaluate): correct deltas across restarts and counter resets, no new polling or S3 reads, no data race, published state shape additive and parseable by older consoles. |
| +5. Console alert registration (alertRuleLevels, order, copy, page copy, valued): consistent with the other box rules; nothing on the Rules page breaks. |
| +6. Tests: do they actually prove the incident cannot recur (sockets never shed requests) and the share works? |
| +7. Census (Astra only): verdict per unit and envelope on docs/superpowers/notes/census-proposal-backhaul-streams-1535.md per AGENTS.md "The census: the reviewer decides", and on internal/host/group_names_test.go's serveAssetFar re-pin. Overall APPROVED / REJECTED. |
| + |
| +## 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. Follow-up list; never a reason for another round. |
| + |
| +A P1 states its failure scenario and evidence (file:line). Do not raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| +Findings ranked P1, P2, P3, each with problem, evidence (file:line, verified), failure scenario, fix, fault family. End with exactly one verdict: READY / READY AFTER FIXES / NOT READY. Astra: census tables and an overall census verdict too. |
| + |
| +Do not edit files. Do not spawn reviewers or subagents. Targeted go tests only (e.g. go test ./internal/edge/ -run Backhaul); not the full suites. |
diff --git a/docs/superpowers/reviews/backhaul-streams-1535/REVIEW-BRIEF-R2.md b/docs/superpowers/reviews/backhaul-streams-1535/REVIEW-BRIEF-R2.md| new file mode 100644 |
| index 000000000..d614ea79d |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/backhaul-streams-1535/REVIEW-BRIEF-R2.md |
| @@ -0,0 +1,35 @@ |
| +# Review brief: backhaul stream pool (#1535), round 2 of 3 |
| + |
| +Repo carlos/platform, branch `backhaul-streams-1535`, commit named in your prompt. Under review: the diff `583fac44fb7e..HEAD` (git diff 583fac44 HEAD -- . ':!docs/superpowers/reviews'). Authorities: everything on main, especially internal/edge/edge.go's backhaul containment ruling (backhaulMaxInflight doc), backhaul-share, and the metrics/alert path (internal/metrics, internal/host/metrics_loop.go, alertsink.go, internal/alerting, the console's alert engine). |
| + |
| +Incident (amadan #1535): upgraded websocket responses hold a backhaul slot for the socket's life, so ~64 open sockets filled the per-home-box in-flight cap and every ordinary request to that home box got 503 for two hours. The fix: upgrade requests take slots from a separate per-box stream pool (CARLOS_BACKHAUL_MAX_STREAMS, default 512, per-client share min(64, cap/4) once half full; since round 1 a hop is admitted on a request slot and swaps to a stream slot only at the home's 101); the request/response default rises 64 -> 128 (round 1 changed it from 256); refusals are counted in-process and raise a `backhaul_shed` box alert (warning, via the console's alert engine, not the box's own sink) through the existing metrics sample path. |
| + |
| +## Fixed: do not re-argue |
| +- Containment stays: there is still a finite bound per home box on each pool; no "off" value. |
| +- SSE / long-poll responses are not reclassified in this slice (documented follow-up). |
| +- The alert is a warning through the existing console alert engine, not a box-sink page. |
| + |
| +## What to check |
| +1. Classification: can a client get a request onto the stream pool or vice versa in a way that defeats containment or fairness (header tricks, upgrade without 101, HTTP/2 hops, door/tunnel callers)? Is the upgrade test identical to what ReverseProxy actually treats as an upgrade? |
| +2. Accounting: no slot or share drift in either pool (count-first-rollback, release once, observe/enforce modes, concurrent paths), and every refusal counted exactly once. |
| +3. The home box: the inbound bound is now sum of siblings' (request + stream) caps. Is 1024 streams per sender per home box with 256 requests a safe default for the home box's memory (each hop costs the home box a TLS conn, proxy goroutines and buffers, and for a fleet hub a tunnel stream onward)? If not, say what default is. |
| +4. The shed metric seam (agent.go edge-ready callback -> backhaulShedSource -> sampler -> backhaulShedWatch -> alertTick -> Evaluate): correct deltas across restarts and counter resets, no new polling or S3 reads, no data race, published state shape additive and parseable by older consoles. |
| +5. Console alert registration (alertRuleLevels, order, copy, page copy, valued): consistent with the other box rules; nothing on the Rules page breaks. |
| +6. Tests: do they actually prove the incident cannot recur (sockets never shed requests) and the share works? |
| +7. Census (Astra only): verdict per unit and envelope on docs/superpowers/notes/census-proposal-backhaul-streams-1535.md per AGENTS.md "The census: the reviewer decides", and on internal/host/group_names_test.go's serveAssetFar re-pin. Overall APPROVED / REJECTED. |
| + |
| +## Round 2 |
| + |
| +Round 1: Astra NOT READY (ASTRA-FINDINGS-R1.md: P1 home-box memory defaults, P1 alert lost on failed publish, P2 contention test); Fable READY AFTER FIXES (FABLE-FINDINGS-R1.md: P2 client-controlled classification, P2 1024 default, P2 unscaled share, P3s). All were taken; see the commits after 9ac6ad3e. First give one line per round-1 P1/P2 from BOTH files: resolved, partly, not. Then new findings, especially in the 101 swap (ModifyResponse/ErrorHandler wrapping in hopTo, interaction with the holder and forward hooks and retries), the alert's quiet-run clearing and commit-on-success watch, and the defaults' justification in the backhaulMaxStreams doc. |
| + |
| +## 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. Follow-up list; never a reason for another round. |
| + |
| +A P1 states its failure scenario and evidence (file:line). Do not raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| +Findings ranked P1, P2, P3, each with problem, evidence (file:line, verified), failure scenario, fix, fault family. End with exactly one verdict: READY / READY AFTER FIXES / NOT READY. Astra: census tables and an overall census verdict too. |
| + |
| +Do not edit files. Do not spawn reviewers or subagents. Targeted go tests only (e.g. go test ./internal/edge/ -run Backhaul); not the full suites. |
diff --git a/internal/alerting/ruletext.go b/internal/alerting/ruletext.go| index 76f7ef2d8..e4c614d5e 100644 |
| --- a/internal/alerting/ruletext.go |
| +++ b/internal/alerting/ruletext.go |
| @@ -86,8 +86,37 @@ var BoxRuleText = map[string]RuleText{ |
| HowLong: "Nothing is down. Owners see an old test date until it catches up.", |
| WhatToDo: "Give the nightly run more time on that box, or spread its instances over more boxes.", |
| }, |
| + "backhaul_shed": { |
| + Title: BackhaulShedTitle, |
| + HowLong: BackhaulShedHowLong, |
| + WhatToDo: BackhaulShedWhatToDo, |
| + }, |
| } |
| +// The backhaul_shed rule's words (#1535), every one in this block: a box |
| +// refused requests it was forwarding to the box that hosts their app (the |
| +// backhaul) because its limit toward that box was reached. The console's |
| +// messages and Rules page read the rest of them from here too. Approved by |
| +// Luna passes 1 and 2. |
| +const ( |
| + BackhaulShedTitle = "Forwarded requests refused" |
| + BackhaulShedHowLong = "Forwarded requests are being refused while the limit is reached. This is a warning in the console's alert engine. The box does not page for it." |
| + // Plain text and quotes, no backticks: an alert message is plain text. |
| + BackhaulShedWhatToDo = "Read the box's journal for \"backhaul to\" lines. They show which destination box was limiting traffic and why. If traffic needs more room, raise the relevant limit in host.env, or set it as a /carlos/<deployment>/<region>/ or /shared/ parameter on a box launched by its region's group." |
| + // BackhaulShedWhat and BackhaulShedWhatNone open a message; %s is |
| + // the box. |
| + BackhaulShedWhat = "%s refused forwarded requests." |
| + BackhaulShedWhatNone = "A box refused forwarded requests." |
| + // BackhaulShedWhen and BackhaulShedThreshold are the Rules page's |
| + // lines. The numbers are metrics.DefaultRules()'s BackhaulShedCount |
| + // and BackhaulShedQuiet. Only refusals at a limit count, not a |
| + // visitor's fair-share refusals. |
| + BackhaulShedWhen = "A box refuses more than 10 forwarded requests in a minute because its limit for the destination box is reached." |
| + BackhaulShedThreshold = "Fixed at more than 10 forwarded requests refused because a limit was reached in one minute. Clears after three minutes with none. Not configurable." |
| + // BackhaulShedValue is the last reading; %d is the count. |
| + BackhaulShedValue = "%d forwarded requests refused in a minute" |
| +) |
| + |
| // VerifyReason is one reason code a restore test's verdict carries |
| // (dbverify.Verdict.Reason) and the words for it. |
| type VerifyReason struct { |
diff --git a/internal/console/alertengine_pass.go b/internal/console/alertengine_pass.go| index 476f970b3..a549c0a3a 100644 |
| --- a/internal/console/alertengine_pass.go |
| +++ b/internal/console/alertengine_pass.go |
| @@ -382,7 +382,7 @@ func alertRuleConnectors(st alertRuleSetting, conns []alertConnector) []int64 { |
| // alertValued are the rules whose value means something in a message. |
| var alertValued = map[string]bool{ |
| "disk": true, "mem": true, "cpu": true, "lag": true, "geoip": true, "disk_eta": true, "box_silent": true, "cert_expiring": true, |
| - "restarts": true, |
| + "restarts": true, "backhaul_shed": true, |
| } |
| // alertEmitNote is what one emit says, stored without links (ruling R-2). |
| @@ -761,6 +761,8 @@ func alertValueText(rule string, value float64) string { |
| return fmt.Sprintf("%.0f days left", value) |
| case "restarts": |
| return fmt.Sprintf("%d restarts in 10 minutes", int(value)) |
| + case "backhaul_shed": |
| + return fmt.Sprintf(alerting.BackhaulShedValue, int(value)) |
| case "verify_unverified": |
| // A reason, not a measurement (alerting.VerifyReasons). |
| if label, ok := alerting.VerifyReasonLabel(value); ok { |
diff --git a/internal/console/alertnotify.go b/internal/console/alertnotify.go| index 85359abf2..e4d2812fa 100644 |
| --- a/internal/console/alertnotify.go |
| +++ b/internal/console/alertnotify.go |
| @@ -224,6 +224,13 @@ var alertCopy = map[string]string{ |
| "rule.verify_coverage.how_long": alerting.BoxRuleText["verify_coverage"].HowLong, |
| "rule.verify_coverage.what_to_do": alerting.BoxRuleText["verify_coverage"].WhatToDo, |
| + // The backhaul refusal rule (#1535): every line is alerting's. |
| + "rule.backhaul_shed.title": alerting.BackhaulShedTitle, |
| + "rule.backhaul_shed.what": alerting.BackhaulShedWhat, |
| + "rule.backhaul_shed.what.none": alerting.BackhaulShedWhatNone, |
| + "rule.backhaul_shed.how_long": alerting.BackhaulShedHowLong, |
| + "rule.backhaul_shed.what_to_do": alerting.BackhaulShedWhatToDo, |
| + |
| "rule.box_silent.title": "Box silent", |
| "rule.box_silent.what": "%s has stopped reporting.", |
| "rule.box_silent.what.none": "A box has stopped reporting.", |
diff --git a/internal/console/alertpages.go b/internal/console/alertpages.go| index b55ef7d12..44d2a6b41 100644 |
| --- a/internal/console/alertpages.go |
| +++ b/internal/console/alertpages.go |
| @@ -14,6 +14,8 @@ import ( |
| "strings" |
| "time" |
| "unicode" |
| + |
| + "github.com/carlosframework/platform/internal/alerting" |
| ) |
| // alertPageCopy is every word of the Alerts pages and the token doors: the |
| @@ -194,6 +196,10 @@ var alertPageCopy = map[string]string{ |
| "rules.th.verify_unverified": "Fixed at 3 nights in a row. Not configurable.", |
| "rules.when.verify_coverage": "An instance on a box hasn't had a restore test for more than 7 days.", |
| "rules.th.verify_coverage": "Fixed at 7 days. Not configurable.", |
| + |
| + // The backhaul refusal rule (#1535); its words are alerting's. |
| + "rules.when.backhaul_shed": alerting.BackhaulShedWhen, |
| + "rules.th.backhaul_shed": alerting.BackhaulShedThreshold, |
| } |
| // The operator Alerts pages (fleet alerts spec §5, plan 1 Task 10): |
| @@ -224,7 +230,7 @@ const ( |
| // the console's. It names every rule in alertRuleLevels |
| // (TestAlertRuleOrderCoversEveryRule). |
| var alertRuleOrder = []string{"disk_eta", "disk", "mem", "cpu", "lag", "geoip", "engine_silent", "restarts", |
| - "verify_failed", "verify_unverified", "verify_coverage", |
| + "verify_failed", "verify_unverified", "verify_coverage", "backhaul_shed", |
| "box_silent", "service_down", "cert_expiring", "alert_delivery_broken", "mailer_unarmed", "demo_sandbox", "seal_key"} |
| // alertThresholdBounds are the editable thresholds' whole-number bounds: |
diff --git a/internal/console/alertpages_test.go b/internal/console/alertpages_test.go| index ccc22e512..9ef7e2149 100644 |
| --- a/internal/console/alertpages_test.go |
| +++ b/internal/console/alertpages_test.go |
| @@ -14,6 +14,7 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/alerting" |
| + "github.com/carlosframework/platform/internal/metrics" |
| ) |
| // alertsPageFixture is an operator signed in to a console whose alert |
| @@ -944,3 +945,44 @@ func TestAlertRuleOrderCoversVerify(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// The backhaul refusal rule (#1535) is a box rule the console knows: a |
| +// warning, after the restore drill's rules, with its words from alerting and |
| +// its value read as a count. The Rules page's number is the box's default. |
| +func TestAlertRuleBackhaulShed(t *testing.T) { |
| + const rule = "backhaul_shed" |
| + if rule != metrics.BackhaulShedRule { |
| + t.Fatalf("rule ID %q, the box publishes %q", rule, metrics.BackhaulShedRule) |
| + } |
| + if i := slices.Index(alertRuleOrder, "verify_coverage"); i < 0 || i+1 >= len(alertRuleOrder) || alertRuleOrder[i+1] != rule { |
| + t.Fatalf("alertRuleOrder = %v, want %s after verify_coverage", alertRuleOrder, rule) |
| + } |
| + if alertRuleLevel(rule) != alerting.LevelWarning { |
| + t.Fatalf("level = %q, want a warning", alertRuleLevel(rule)) |
| + } |
| + v := alertRuleRow(rule, nil, nil, alertNoise{}) |
| + if v.When != alerting.BackhaulShedWhen || v.Threshold != alerting.BackhaulShedThreshold || v.Editable || v.BoxEnv { |
| + t.Fatalf("row: when %q, threshold %q (editable %v, box env %v)", v.When, v.Threshold, v.Editable, v.BoxEnv) |
| + } |
| + if n := metrics.DefaultRules().BackhaulShedCount; !strings.Contains(alerting.BackhaulShedWhen, "more than 10 ") || n != 10 { |
| + t.Fatalf("the page says more than 10, the box fires above %v", n) |
| + } |
| + if q := metrics.DefaultRules().BackhaulShedQuiet; !strings.Contains(alerting.BackhaulShedThreshold, "three minutes") || q != 3*time.Minute { |
| + t.Fatalf("the page says three minutes, the box clears after %v", q) |
| + } |
| + if got := alertRuleTitle(rule); got != alerting.BackhaulShedTitle { |
| + t.Fatalf("title = %q", got) |
| + } |
| + if got := alertValueText(rule, 37); got != "37 forwarded requests refused in a minute" { |
| + t.Fatalf("value = %q", got) |
| + } |
| + if !alertValued[rule] { |
| + t.Fatal("the value is not shown in a message") |
| + } |
| + for _, s := range []string{alerting.BackhaulShedTitle, alerting.BackhaulShedHowLong, alerting.BackhaulShedWhatToDo, |
| + alerting.BackhaulShedWhat, alerting.BackhaulShedWhatNone, alerting.BackhaulShedWhen, alerting.BackhaulShedThreshold, alerting.BackhaulShedValue} { |
| + if strings.ContainsAny(s, "—–") { |
| + t.Errorf("dash in %q", s) |
| + } |
| + } |
| +} |
diff --git a/internal/console/alertsignals.go b/internal/console/alertsignals.go| index bca6e7280..57a4e9546 100644 |
| --- a/internal/console/alertsignals.go |
| +++ b/internal/console/alertsignals.go |
| @@ -848,6 +848,7 @@ var alertRuleLevels = map[string]string{ |
| "verify_failed": alerting.LevelIncident, |
| "verify_unverified": alerting.LevelWarning, |
| "verify_coverage": alerting.LevelWarning, |
| + "backhaul_shed": alerting.LevelWarning, |
| "box_silent": alerting.LevelIncident, |
| "service_down": alerting.LevelIncident, |
| "cert_expiring": alerting.LevelWarning, |
diff --git a/internal/edge/asset_far_test.go b/internal/edge/asset_far_test.go| index 00ba7b206..ac9dd5924 100644 |
| --- a/internal/edge/asset_far_test.go |
| +++ b/internal/edge/asset_far_test.go |
| @@ -1007,6 +1007,7 @@ func TestBackhaulScrubsTheAssetVocabulary(t *testing.T) { |
| func TestFarFillShedByTheFairShareIs429(t *testing.T) { |
| s := newFarScene(t, assetOK(laBody)) |
| s.e.rateMode = RateEnforce |
| + backhaulCap(t, 64) // 32 held is half full |
| req := s.req(http.MethodGet, "/assets/app.js") |
| key := s.e.backhaulClientKey(req) |
| if key == "" { |
| @@ -1334,6 +1335,7 @@ func TestFarLocalAnswersAreRecorded(t *testing.T) { |
| s := newFarScene(t, assetOK(laBody)) |
| rec := watched(t, s) |
| s.e.rateMode = RateEnforce |
| + backhaulCap(t, 64) // 32 held is half full |
| req := s.req(http.MethodGet, p) |
| key := s.e.backhaulClientKey(req) |
| for i := 0; i < 32; i++ { |
diff --git a/internal/edge/backhaul_share_test.go b/internal/edge/backhaul_share_test.go| index 25754429c..74a7f73ad 100644 |
| --- a/internal/edge/backhaul_share_test.go |
| +++ b/internal/edge/backhaul_share_test.go |
| @@ -35,6 +35,9 @@ func newShareScene(t *testing.T, mode RateMode) *shareScene { |
| t.Helper() |
| e, m, _ := hopEdge(t, "annie", "local.test") |
| e.rateMode = mode |
| + // The arithmetic below is a cap of 64 (half is 32); pinned so the |
| + // tests read the same whatever the default. |
| + backhaulCap(t, 64) |
| rec, eip := fakeHomeEdge(t, nil) |
| homedOn(t, m, "betty", eip, "example.com") |
| front := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
diff --git a/internal/edge/backhaul_streams_test.go b/internal/edge/backhaul_streams_test.go| new file mode 100644 |
| index 000000000..b6bf49ee5 |
| --- /dev/null |
| +++ b/internal/edge/backhaul_streams_test.go |
| @@ -0,0 +1,897 @@ |
| +package edge |
| + |
| +// Two pools per destination box (#1535): an upgraded hop (a WebSocket) holds |
| +// its slot for the life of the socket, so a hop the home answers with 101 |
| +// moves from the request pool to a stream pool of its own, and open sockets |
| +// can never fill the request pool that ordinary hops share. |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "crypto/tls" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// backhaulStreamCap sets the stream pool's cap for one test and restores it |
| +// after, the seam backhaulCap gives the request pool. |
| +func backhaulStreamCap(t *testing.T, n int64) { |
| + t.Helper() |
| + old := backhaulMaxStreams.Load() |
| + backhaulMaxStreams.Store(n) |
| + t.Cleanup(func() { backhaulMaxStreams.Store(old) }) |
| +} |
| + |
| +func poolCount(m *sync.Map, box string) int64 { |
| + v, ok := m.Load(box) |
| + if !ok { |
| + return 0 |
| + } |
| + return v.(*atomic.Int64).Load() |
| +} |
| + |
| +// The defaults, and the share scaled to a quarter of a small cap. |
| +func TestBackhaulPoolDefaults(t *testing.T) { |
| + if defaultBackhaulMaxInflight != 64 { |
| + t.Fatalf("defaultBackhaulMaxInflight = %d, want 64 (main's)", defaultBackhaulMaxInflight) |
| + } |
| + if defaultBackhaulMaxStreams != 128 { |
| + t.Fatalf("defaultBackhaulMaxStreams = %d, want 128", defaultBackhaulMaxStreams) |
| + } |
| + if backhaulClientShare != 8 || backhaulStreamClientShare != 64 { |
| + t.Fatalf("shares = %d, %d, want 8, 64", backhaulClientShare, backhaulStreamClientShare) |
| + } |
| + for _, tc := range []struct { |
| + share int |
| + limit int64 |
| + want int |
| + }{ |
| + {8, defaultBackhaulMaxInflight, 8}, |
| + {64, defaultBackhaulMaxStreams, 32}, |
| + {64, 256, 64}, |
| + {8, 64, 8}, |
| + {64, 100, 25}, |
| + {64, 8, 2}, |
| + {8, 8, 2}, |
| + {64, 3, 1}, |
| + {8, 1, 1}, |
| + {8, 0, 1}, |
| + } { |
| + if got := backhaulShare(tc.share, tc.limit); got != tc.want { |
| + t.Errorf("backhaulShare(%d, %d) = %d, want %d", tc.share, tc.limit, got, tc.want) |
| + } |
| + } |
| + e := &Edge{} |
| + if p := e.requestPool(); p.limit != backhaulMaxInflight.Load() || p.share != backhaulShare(backhaulClientShare, p.limit) { |
| + t.Fatalf("request pool %d/%d", p.limit, p.share) |
| + } |
| + if p := e.streamPool(); p.limit != backhaulMaxStreams.Load() || p.share != backhaulShare(backhaulStreamClientShare, p.limit) { |
| + t.Fatalf("stream pool %d/%d", p.limit, p.share) |
| + } |
| +} |
| + |
| +// The stream knob follows the request knob's rules: unset, unparseable and |
| +// non-positive all mean the default, never uncapped and never zero. |
| +func TestBackhaulMaxStreamsFromEnv(t *testing.T) { |
| + const name = "CARLOS_BACKHAUL_MAX_STREAMS" |
| + ambient, had := os.LookupEnv(name) |
| + t.Cleanup(func() { |
| + if had { |
| + os.Setenv(name, ambient) |
| + return |
| + } |
| + os.Unsetenv(name) |
| + }) |
| + for _, tc := range []struct { |
| + set bool |
| + raw string |
| + want int |
| + }{ |
| + {set: false, want: defaultBackhaulMaxStreams}, |
| + {set: true, raw: "", want: defaultBackhaulMaxStreams}, |
| + {set: true, raw: " ", want: defaultBackhaulMaxStreams}, |
| + {set: true, raw: "lots", want: defaultBackhaulMaxStreams}, |
| + {set: true, raw: "0", want: defaultBackhaulMaxStreams}, |
| + {set: true, raw: "-1", want: defaultBackhaulMaxStreams}, |
| + {set: true, raw: "4096", want: 4096}, |
| + {set: true, raw: " 16 ", want: 16}, |
| + } { |
| + if tc.set { |
| + t.Setenv(name, tc.raw) |
| + } else { |
| + os.Unsetenv(name) |
| + } |
| + if got := backhaulStreamsFromEnv(); got != tc.want { |
| + t.Fatalf("%s=%q (set=%v) → %d, want %d", name, tc.raw, tc.set, got, tc.want) |
| + } |
| + } |
| +} |
| + |
| +// Streams filling their pool take nothing from the request pool, and the |
| +// request pool full takes nothing from the stream pool. |
| +func TestBackhaulPoolsAreSeparate(t *testing.T) { |
| + e, _, _ := hopEdge(t, "annie", "local.test") |
| + backhaulCap(t, 2) |
| + backhaulStreamCap(t, 3) |
| + for i := 0; i < 3; i++ { |
| + rel, ok, shed := e.backhaulAcquireStream("betty", "") |
| + if !ok || shed { |
| + t.Fatalf("stream %d: ok=%v shed=%v", i+1, ok, shed) |
| + } |
| + t.Cleanup(rel) |
| + } |
| + if _, ok, _ := e.backhaulAcquireStream("betty", ""); ok { |
| + t.Fatal("a fourth stream was admitted over a cap of 3") |
| + } |
| + for i := 0; i < 2; i++ { |
| + rel, ok, _ := e.backhaulAcquire("betty", "") |
| + if !ok { |
| + t.Fatalf("request %d refused while only streams were held", i+1) |
| + } |
| + t.Cleanup(rel) |
| + } |
| + if _, ok, _ := e.backhaulAcquire("betty", ""); ok { |
| + t.Fatal("a third request was admitted over a cap of 2") |
| + } |
| + if got := poolCount(&e.backhaulInflight, "betty"); got != 2 { |
| + t.Fatalf("request pool = %d, want 2", got) |
| + } |
| + if got := poolCount(&e.backhaulStreamInflight, "betty"); got != 3 { |
| + t.Fatalf("stream pool = %d, want 3", got) |
| + } |
| +} |
| + |
| +// One client opening many sockets is refused its share of a busy stream |
| +// pool while another client still gets streams. Requests are not affected. |
| +func TestBackhaulStreamShare(t *testing.T) { |
| + e, _, _ := hopEdge(t, "annie", "local.test") |
| + e.rateMode = RateEnforce |
| + backhaulStreamCap(t, 256) |
| + const a, b = "203.0.113.1/32", "203.0.113.2/32" |
| + for i := 0; i < 64; i++ { // unkeyed: a quarter of the pool |
| + rel, ok, _ := e.backhaulAcquireStream("betty", "") |
| + if !ok { |
| + t.Fatalf("unkeyed stream %d refused", i+1) |
| + } |
| + t.Cleanup(rel) |
| + } |
| + for i := 0; i < backhaulStreamClientShare; i++ { |
| + rel, ok, shed := e.backhaulAcquireStream("betty", a) |
| + if !ok || shed { |
| + t.Fatalf("A's stream %d: ok=%v shed=%v", i+1, ok, shed) |
| + } |
| + t.Cleanup(rel) |
| + } |
| + if _, ok, shed := e.backhaulAcquireStream("betty", a); ok || !shed { |
| + t.Fatalf("A over its share of a half-full stream pool: ok=%v shed=%v, want a fair-share refusal", ok, shed) |
| + } |
| + if got := poolCount(&e.backhaulStreamInflight, "betty"); got != 64+int64(backhaulStreamClientShare) { |
| + t.Fatalf("stream pool = %d after the refusal, want %d: the refusal must roll back", got, 64+backhaulStreamClientShare) |
| + } |
| + rel, ok, shed := e.backhaulAcquireStream("betty", b) |
| + if !ok || shed { |
| + t.Fatalf("B: ok=%v shed=%v, want a stream", ok, shed) |
| + } |
| + rel() |
| + rel, ok, shed = e.backhaulAcquire("betty", a) |
| + if !ok || shed { |
| + t.Fatalf("A's ordinary request: ok=%v shed=%v, want the request pool's slot", ok, shed) |
| + } |
| + rel() |
| +} |
| + |
| +// In a busy stream pool a client may hold exactly backhaulStreamClientShare |
| +// sockets, not the request pool's 8: a browser with several tabs open is |
| +// one visitor, not a flood. |
| +func TestBackhaulStreamShareInABusyPool(t *testing.T) { |
| + e, _, _ := hopEdge(t, "annie", "local.test") |
| + e.rateMode = RateEnforce |
| + backhaulStreamCap(t, 256) |
| + for i := 0; i < 128; i++ { // half full before A arrives |
| + rel, ok, _ := e.backhaulAcquireStream("betty", "") |
| + if !ok { |
| + t.Fatalf("unkeyed stream %d refused", i+1) |
| + } |
| + t.Cleanup(rel) |
| + } |
| + const a = "203.0.113.1/32" |
| + for i := 0; i < backhaulStreamClientShare; i++ { |
| + rel, ok, shed := e.backhaulAcquireStream("betty", a) |
| + if !ok || shed { |
| + t.Fatalf("A's socket %d in a busy pool: ok=%v shed=%v, want admitted up to %d", i+1, ok, shed, backhaulStreamClientShare) |
| + } |
| + t.Cleanup(rel) |
| + } |
| + if _, ok, shed := e.backhaulAcquireStream("betty", a); ok || !shed { |
| + t.Fatalf("A's socket %d: ok=%v shed=%v, want the fair-share refusal", backhaulStreamClientShare+1, ok, shed) |
| + } |
| +} |
| + |
| +// A lowered cap scales the share down with it: at a cap of 8 one client may |
| +// hold 2 once the pool is half used, in either pool, not 8 or 64. |
| +func TestBackhaulShareScalesWithASmallCap(t *testing.T) { |
| + for name, acquire := range map[string]func(*Edge) func(string, string) (func(), bool, bool){ |
| + "request": func(e *Edge) func(string, string) (func(), bool, bool) { return e.backhaulAcquire }, |
| + "stream": func(e *Edge) func(string, string) (func(), bool, bool) { return e.backhaulAcquireStream }, |
| + } { |
| + e, _, _ := hopEdge(t, "annie", "local.test") |
| + e.rateMode = RateEnforce |
| + backhaulCap(t, 8) |
| + backhaulStreamCap(t, 8) |
| + take := acquire(e) |
| + for i := 0; i < 4; i++ { |
| + rel, ok, _ := take("betty", "") |
| + if !ok { |
| + t.Fatalf("%s: unkeyed slot %d refused", name, i+1) |
| + } |
| + t.Cleanup(rel) |
| + } |
| + for i := 0; i < 2; i++ { |
| + rel, ok, shed := take("betty", "203.0.113.1/32") |
| + if !ok || shed { |
| + t.Fatalf("%s: A's slot %d: ok=%v shed=%v", name, i+1, ok, shed) |
| + } |
| + t.Cleanup(rel) |
| + } |
| + if _, ok, shed := take("betty", "203.0.113.1/32"); ok || !shed { |
| + t.Fatalf("%s: A's third slot at a cap of 8: ok=%v shed=%v, want the share (2) refused", name, ok, shed) |
| + } |
| + if rel, ok, shed := take("betty", "203.0.113.2/32"); !ok || shed { |
| + t.Fatalf("%s: B: ok=%v shed=%v, want a slot", name, ok, shed) |
| + } else { |
| + rel() |
| + } |
| + } |
| +} |
| + |
| +// Under half full, the stream share takes no part. |
| +func TestBackhaulStreamShareQuiet(t *testing.T) { |
| + e, _, _ := hopEdge(t, "annie", "local.test") |
| + e.rateMode = RateEnforce |
| + backhaulStreamCap(t, 1024) |
| + for i := 0; i < backhaulStreamClientShare+10; i++ { |
| + rel, ok, shed := e.backhaulAcquireStream("betty", "203.0.113.1/32") |
| + if !ok || shed { |
| + t.Fatalf("stream %d under half full: ok=%v shed=%v", i+1, ok, shed) |
| + } |
| + t.Cleanup(rel) |
| + } |
| +} |
| + |
| +// Observe mode logs the refusal and admits; off takes no part. |
| +func TestBackhaulStreamShareModes(t *testing.T) { |
| + for _, mode := range []RateMode{RateObserve, RateOff} { |
| + e, _, _ := hopEdge(t, "annie", "local.test") |
| + e.rateMode = mode |
| + backhaulStreamCap(t, 128) |
| + buf := captureLog(t) |
| + for i := 0; i < backhaulStreamClientShare+1; i++ { |
| + rel, err := e.backhaulStreamAt101("betty", "192.0.2.5", "203.0.113.1/32") |
| + if err != nil { |
| + t.Fatalf("mode %v stream %d: %v, want admitted", mode, i+1, err) |
| + } |
| + t.Cleanup(rel) |
| + } |
| + logged := strings.Contains(buf.String(), "would refuse") |
| + if logged != (mode == RateObserve) { |
| + t.Fatalf("mode %v: \"would refuse\" logged = %v: %s", mode, logged, buf.String()) |
| + } |
| + if got := e.BackhaulSheds(); got != (BackhaulSheds{}) { |
| + t.Fatalf("mode %v counted sheds %+v, want none: nothing was refused", mode, got) |
| + } |
| + } |
| +} |
| + |
| +// Every slot and share of both pools comes back, once, however often |
| +// release is called. |
| +func TestBackhaulPoolsReleaseOnce(t *testing.T) { |
| + e, _, _ := hopEdge(t, "annie", "local.test") |
| + e.rateMode = RateEnforce |
| + const key = "198.51.100.7/32" |
| + var rels []func() |
| + for i := 0; i < 8; i++ { |
| + for _, acquire := range []func(string, string) (func(), bool, bool){e.backhaulAcquire, e.backhaulAcquireStream} { |
| + rel, ok, shed := acquire("betty", key) |
| + if !ok || shed { |
| + t.Fatalf("slot %d: ok=%v shed=%v", i+1, ok, shed) |
| + } |
| + rels = append(rels, rel) |
| + } |
| + } |
| + for _, rel := range rels { |
| + rel() |
| + rel() |
| + } |
| + for name, m := range map[string]*sync.Map{"request": &e.backhaulInflight, "stream": &e.backhaulStreamInflight} { |
| + if got := poolCount(m, "betty"); got != 0 { |
| + t.Fatalf("%s pool = %d after every release, want 0", name, got) |
| + } |
| + } |
| + for name, m := range map[string]*sync.Map{"request": &e.backhaulShares, "stream": &e.backhaulStreamShares} { |
| + sv, _ := m.Load("betty") |
| + if got := sv.(interface{ Held(string) int }).Held(key); got != 0 { |
| + t.Fatalf("client still holds %d %s share(s) after every release", got, name) |
| + } |
| + } |
| +} |
| + |
| +// Contention on both pools, round by round: more contenders than slots start |
| +// together, and at the barrier after every attempt the admitted holders are |
| +// within the cap, every attempt was either admitted or refused and counted, |
| +// each client's share count is its holders, and after the releases both |
| +// pools and every share are back at zero. Run under -race. |
| +func TestBackhaulPoolsUnderContention(t *testing.T) { |
| + e, _, _ := hopEdge(t, "annie", "local.test") |
| + e.rateMode = RateEnforce |
| + const slots, clients, perClient, rounds = 8, 4, 6, 25 |
| + backhaulCap(t, slots) |
| + backhaulStreamCap(t, slots) |
| + peers := []string{"203.0.113.1", "203.0.113.2", "203.0.113.3", "203.0.113.4"} |
| + |
| + type attempt struct { |
| + release func() |
| + ok bool |
| + } |
| + pools := []struct { |
| + name string |
| + counts *sync.Map |
| + shares *sync.Map |
| + try func(peer string) (func(), bool) |
| + }{ |
| + {"request", &e.backhaulInflight, &e.backhaulShares, func(peer string) (func(), bool) { |
| + r := httptest.NewRequest(http.MethodGet, "http://example.com/", nil) |
| + r.RemoteAddr = net.JoinHostPort(peer, "40000") |
| + return e.backhaulAdmit(httptest.NewRecorder(), r, "192.0.2.5", "betty") |
| + }}, |
| + {"stream", &e.backhaulStreamInflight, &e.backhaulStreamShares, func(peer string) (func(), bool) { |
| + rel, err := e.backhaulStreamAt101("betty", "192.0.2.5", peer+"/32") |
| + return rel, err == nil |
| + }}, |
| + } |
| + for _, p := range pools { |
| + before := e.BackhaulSheds() |
| + var refused int |
| + for round := 0; round < rounds; round++ { |
| + start := make(chan struct{}) |
| + results := make([]attempt, clients*perClient) |
| + var wg sync.WaitGroup |
| + for i := range results { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + <-start |
| + rel, ok := p.try(peers[i%clients]) |
| + results[i] = attempt{rel, ok} |
| + }() |
| + } |
| + close(start) |
| + wg.Wait() // the barrier: every attempt has been admitted or refused |
| + admitted := 0 |
| + perPeer := map[string]int{} |
| + for i, a := range results { |
| + if a.ok { |
| + admitted++ |
| + perPeer[peers[i%clients]]++ |
| + } else { |
| + refused++ |
| + } |
| + } |
| + if admitted > slots { |
| + t.Fatalf("%s round %d: %d holders admitted over a cap of %d", p.name, round, admitted, slots) |
| + } |
| + if got := poolCount(p.counts, "betty"); got != int64(admitted) { |
| + t.Fatalf("%s round %d: pool count %d, %d holders", p.name, round, got, admitted) |
| + } |
| + sv, _ := p.shares.Load("betty") |
| + for _, peer := range peers { |
| + if got := sv.(interface{ Held(string) int }).Held(peer + "/32"); got != perPeer[peer] { |
| + t.Fatalf("%s round %d: %s's share count %d, %d holders", p.name, round, peer, got, perPeer[peer]) |
| + } |
| + } |
| + for _, a := range results { |
| + if a.ok { |
| + a.release() |
| + a.release() |
| + } |
| + } |
| + if got := poolCount(p.counts, "betty"); got != 0 { |
| + t.Fatalf("%s round %d: pool count %d after every release", p.name, round, got) |
| + } |
| + for _, peer := range peers { |
| + if got := sv.(interface{ Held(string) int }).Held(peer + "/32"); got != 0 { |
| + t.Fatalf("%s round %d: %s still holds %d share(s)", p.name, round, peer, got) |
| + } |
| + } |
| + } |
| + after := e.BackhaulSheds() |
| + counted := after.Requests + after.Streams + after.FairShare - before.Requests - before.Streams - before.FairShare |
| + if counted != uint64(refused) { |
| + t.Fatalf("%s: %d refusals, %d counted", p.name, refused, counted) |
| + } |
| + if refused < rounds*(clients*perClient-slots) { |
| + t.Fatalf("%s: %d refusals over %d rounds of %d attempts at %d slots", p.name, refused, rounds, clients*perClient, slots) |
| + } |
| + } |
| +} |
| + |
| +// Each refusal is counted once by kind: the request pool's cap and share at |
| +// admission, the stream pool's cap and share at the 101. |
| +func TestBackhaulShedCounts(t *testing.T) { |
| + e, _, _ := hopEdge(t, "annie", "local.test") |
| + e.rateMode = RateEnforce |
| + backhaulCap(t, 4) |
| + backhaulStreamCap(t, 4) |
| + buf := captureLog(t) |
| + req := func(peer string) *http.Request { |
| + r := httptest.NewRequest(http.MethodGet, "http://example.com/", nil) |
| + r.RemoteAddr = net.JoinHostPort(peer, "40000") |
| + return r |
| + } |
| + // At a cap of 4 the share is 1, from 2 held: A gets 2 while the pool is |
| + // quiet, then its third is refused. |
| + for i := 0; i < 2; i++ { |
| + rel, ok := e.backhaulAdmit(httptest.NewRecorder(), req(shareClientA), "192.0.2.5", "betty") |
| + if !ok { |
| + t.Fatalf("A's request %d refused", i+1) |
| + } |
| + t.Cleanup(rel) |
| + } |
| + rec := httptest.NewRecorder() |
| + if _, ok := e.backhaulAdmit(rec, req(shareClientA), "192.0.2.5", "betty"); ok || rec.Code != http.StatusTooManyRequests { |
| + t.Fatalf("A over its request share: ok=%v %d, want 429", ok, rec.Code) |
| + } |
| + for i := 0; i < 2; i++ { |
| + rel, ok, _ := e.backhaulAcquire("betty", "") |
| + if !ok { |
| + t.Fatalf("unkeyed request %d refused below the cap", i+1) |
| + } |
| + t.Cleanup(rel) |
| + } |
| + rec = httptest.NewRecorder() |
| + if _, ok := e.backhaulAdmit(rec, req(shareClientB), "192.0.2.5", "betty"); ok || rec.Code != http.StatusServiceUnavailable || rec.Header().Get("Retry-After") != "2" { |
| + t.Fatalf("over the request cap: ok=%v %d Retry-After %q, want 503 + 2", ok, rec.Code, rec.Header().Get("Retry-After")) |
| + } |
| + for i := 0; i < 2; i++ { |
| + rel, err := e.backhaulStreamAt101("betty", "192.0.2.5", shareClientA+"/32") |
| + if err != nil { |
| + t.Fatalf("A's stream %d: %v", i+1, err) |
| + } |
| + t.Cleanup(rel) |
| + } |
| + if _, err := e.backhaulStreamAt101("betty", "192.0.2.5", shareClientA+"/32"); !errors.Is(err, errBackhaulStreamShare) { |
| + t.Fatalf("A over its stream share: %v", err) |
| + } |
| + for i := 0; i < 2; i++ { |
| + rel, err := e.backhaulStreamAt101("betty", "192.0.2.5", "") |
| + if err != nil { |
| + t.Fatalf("unkeyed stream %d: %v", i+1, err) |
| + } |
| + t.Cleanup(rel) |
| + } |
| + if _, err := e.backhaulStreamAt101("betty", "192.0.2.5", ""); !errors.Is(err, errBackhaulStreamsBusy) { |
| + t.Fatalf("over the stream cap: %v", err) |
| + } |
| + if got, want := e.BackhaulSheds(), (BackhaulSheds{Requests: 1, Streams: 1, FairShare: 2}); got != want { |
| + t.Fatalf("BackhaulSheds = %+v, want %+v", got, want) |
| + } |
| + out := buf.String() |
| + if !strings.Contains(out, "in-flight cap (4); answering 503 with Retry-After: 2") || |
| + !strings.Contains(out, "stream cap (4 open WebSockets); answering 503 with Retry-After: 2") { |
| + t.Fatalf("log lacks a line for each saturated pool: %s", out) |
| + } |
| + if strings.ContainsAny(out, "—–") { |
| + t.Fatalf("a backhaul log line has a dash: %s", out) |
| + } |
| + // Four throttle keys: each pool's cap and each pool's share. |
| + if n := strings.Count(out, "occurrence #1"); n != 4 { |
| + t.Fatalf("%d first-occurrence lines, want 4: %s", n, out) |
| + } |
| +} |
| + |
| +// wsHome is a home edge that answers an upgrade with 101 and holds the |
| +// socket open, echoing each line, until the test ends; any other request |
| +// gets the ordinary body. With slow set it answers an upgrade request 200 |
| +// instead, with a body it finishes only when slow is closed. |
| +func wsHome(t *testing.T, slow chan struct{}) http.Handler { |
| + t.Helper() |
| + stop := make(chan struct{}) |
| + t.Cleanup(func() { close(stop) }) |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.Header.Get("Upgrade") == "" { |
| + fmt.Fprint(w, homeEdgeBody) |
| + return |
| + } |
| + if slow != nil { |
| + fmt.Fprint(w, "first ") |
| + w.(http.Flusher).Flush() |
| + <-slow |
| + fmt.Fprint(w, "last") |
| + return |
| + } |
| + conn, buf, err := w.(http.Hijacker).Hijack() |
| + if err != nil { |
| + return |
| + } |
| + defer conn.Close() |
| + buf.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n") |
| + if buf.Flush() != nil { |
| + return |
| + } |
| + go func() { <-stop; conn.Close() }() |
| + for { |
| + line, err := buf.ReadString('\n') |
| + if err != nil { |
| + return |
| + } |
| + buf.WriteString("home:" + line) |
| + if buf.Flush() != nil { |
| + return |
| + } |
| + } |
| + }) |
| +} |
| + |
| +// openBackhaulSocket opens one WebSocket-shaped upgrade through the sending |
| +// edge at srv, from peer when it is not empty (rlPeerHeader), and returns |
| +// the connection, or the refusal's response. |
| +func openBackhaulSocket(t *testing.T, srv *httptest.Server, peer string) (net.Conn, *http.Response) { |
| + t.Helper() |
| + c, err := net.Dial("tcp", strings.TrimPrefix(srv.URL, "http://")) |
| + if err != nil { |
| + t.Fatalf("dial edge: %v", err) |
| + } |
| + t.Cleanup(func() { c.Close() }) |
| + if err := c.SetDeadline(time.Now().Add(15 * time.Second)); err != nil { |
| + t.Fatal(err) |
| + } |
| + hdr := "" |
| + if peer != "" { |
| + hdr = rlPeerHeader + ": " + peer + "\r\n" |
| + } |
| + if _, err := fmt.Fprintf(c, "GET /cable HTTP/1.1\r\nHost: example.com\r\nConnection: keep-alive, Upgrade\r\nUpgrade: websocket\r\n%s\r\n", hdr); err != nil { |
| + t.Fatalf("write handshake: %v", err) |
| + } |
| + br := bufio.NewReader(c) |
| + resp, err := http.ReadResponse(br, nil) |
| + if err != nil { |
| + t.Fatalf("read handshake response: %v", err) |
| + } |
| + if resp.StatusCode != http.StatusSwitchingProtocols { |
| + return nil, resp |
| + } |
| + if _, err := fmt.Fprint(c, "ping\n"); err != nil { |
| + t.Fatalf("write frame: %v", err) |
| + } |
| + if line, err := br.ReadString('\n'); err != nil || line != "home:ping\n" { |
| + t.Fatalf("echo = %q (%v), want home:ping", line, err) |
| + } |
| + return c, resp |
| +} |
| + |
| +// peerFront serves e behind a front that takes each request's peer address |
| +// from rlPeerHeader, as shareScene does. |
| +func peerFront(t *testing.T, e *Edge) *httptest.Server { |
| + t.Helper() |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if p := r.Header.Get(rlPeerHeader); p != "" { |
| + r.Header.Del(rlPeerHeader) |
| + r.RemoteAddr = net.JoinHostPort(p, "40000") |
| + } |
| + e.ServeHTTP(w, r) |
| + })) |
| + t.Cleanup(srv.Close) |
| + return srv |
| +} |
| + |
| +// The incident, end to end through the real backhaul handler: more open |
| +// WebSockets than the request pool has slots, each moved to the stream pool |
| +// at its 101, and ordinary GETs to the same home box still succeed. Then the |
| +// stream pool saturates: the next socket is refused before it dials with |
| +// 503 + Retry-After 2, no slot leaks in either pool, and a socket that ends |
| +// gives its slot back. |
| +func TestBackhaulWebSocketsDoNotStarveRequests(t *testing.T) { |
| + e, m, _ := hopEdge(t, "annie", "local.test") |
| + const n = 3 |
| + backhaulCap(t, n) |
| + backhaulStreamCap(t, n+2) |
| + rec, eip := fakeHomeEdge(t, wsHome(t, nil)) |
| + homedOn(t, m, "betty", eip, "example.com") |
| + srv := httptest.NewServer(e) |
| + t.Cleanup(srv.Close) |
| + get := backhaulGetter(t, e) |
| + |
| + var socks []net.Conn |
| + for i := 0; i < n+1; i++ { |
| + c, resp := openBackhaulSocket(t, srv, "") |
| + if c == nil { |
| + t.Fatalf("socket %d refused: %d", i+1, resp.StatusCode) |
| + } |
| + socks = append(socks, c) |
| + } |
| + if got := poolCount(&e.backhaulStreamInflight, "betty"); got != n+1 { |
| + t.Fatalf("stream pool = %d with %d sockets open, want %d", got, n+1, n+1) |
| + } |
| + if got := poolCount(&e.backhaulInflight, "betty"); got != 0 { |
| + t.Fatalf("request pool = %d with only sockets open, want 0: each gave its request slot back at its 101", got) |
| + } |
| + for i := 0; i < 2*n; i++ { |
| + resp, err := get("example.com") |
| + if err != nil { |
| + t.Fatalf("GET %d: %v", i+1, err) |
| + } |
| + body, _ := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + if resp.StatusCode != http.StatusOK || string(body) != homeEdgeBody { |
| + t.Fatalf("GET %d with %d sockets open: %d %q, want the home's 200", i+1, n+1, resp.StatusCode, body) |
| + } |
| + } |
| + |
| + c, _ := openBackhaulSocket(t, srv, "") // the pool's last slot |
| + if c == nil { |
| + t.Fatal("socket n+2 refused below the stream cap") |
| + } |
| + socks = append(socks, c) |
| + homeSaw := rec.get().n |
| + _, refused := openBackhaulSocket(t, srv, "") |
| + if refused == nil || refused.StatusCode != http.StatusServiceUnavailable || refused.Header.Get("Retry-After") != "2" || |
| + refused.Header.Get("X-Carlos-Answer") != "backhaul-streams-busy" { |
| + t.Fatalf("socket over the stream cap: %+v, want 503 + Retry-After 2 from backhaul-streams-busy", refused) |
| + } |
| + io.Copy(io.Discard, refused.Body) |
| + if rec.get().n != homeSaw { |
| + t.Fatal("the socket over a full stream pool reached the home: it must be refused before the dial") |
| + } |
| + if got := e.BackhaulSheds(); got.Streams != 1 || got.Requests != 0 { |
| + t.Fatalf("BackhaulSheds = %+v, want one stream shed", got) |
| + } |
| + waitFor(t, 10*time.Second, "the refused hop's request slot back", func() bool { |
| + return poolCount(&e.backhaulInflight, "betty") == 0 |
| + }) |
| + if got := poolCount(&e.backhaulStreamInflight, "betty"); got != n+2 { |
| + t.Fatalf("stream pool = %d after the refusal, want %d", got, n+2) |
| + } |
| + |
| + socks[0].Close() |
| + waitFor(t, 10*time.Second, "a closed socket's slot back", func() bool { |
| + return poolCount(&e.backhaulStreamInflight, "betty") == n+1 |
| + }) |
| + if c, resp := openBackhaulSocket(t, srv, ""); c == nil { |
| + t.Fatalf("socket after one closed: %d, want 101", resp.StatusCode) |
| + } |
| +} |
| + |
| +// The Upgrade header buys nothing: an upgrade request the home answers 200 |
| +// with a long body holds a request slot for its whole life and never a |
| +// stream slot, and with the request pool full an upgrade request is refused |
| +// like any other. |
| +func TestBackhaulUpgradeRequestAnswered200StaysInRequestPool(t *testing.T) { |
| + e, m, _ := hopEdge(t, "annie", "local.test") |
| + slow := make(chan struct{}) |
| + _, eip := fakeHomeEdge(t, wsHome(t, slow)) |
| + homedOn(t, m, "betty", eip, "example.com") |
| + srv := httptest.NewServer(e) |
| + t.Cleanup(srv.Close) |
| + |
| + c, resp := openBackhaulSocket(t, srv, "") |
| + if c != nil || resp.StatusCode != http.StatusOK { |
| + t.Fatalf("upgrade request answered 200: %+v", resp) |
| + } |
| + first := make([]byte, len("first ")) |
| + if _, err := io.ReadFull(resp.Body, first); err != nil || string(first) != "first " { |
| + t.Fatalf("first chunk %q (%v)", first, err) |
| + } |
| + if got := poolCount(&e.backhaulInflight, "betty"); got != 1 { |
| + t.Fatalf("request pool = %d mid-body, want 1", got) |
| + } |
| + if got := poolCount(&e.backhaulStreamInflight, "betty"); got != 0 { |
| + t.Fatalf("stream pool = %d, want 0: no 101, no stream slot", got) |
| + } |
| + close(slow) |
| + if rest, err := io.ReadAll(resp.Body); err != nil || string(rest) != "last" { |
| + t.Fatalf("rest %q (%v)", rest, err) |
| + } |
| + waitFor(t, 10*time.Second, "the request slot back", func() bool { |
| + return poolCount(&e.backhaulInflight, "betty") == 0 |
| + }) |
| + |
| + backhaulCap(t, 1) |
| + rel, ok, _ := e.backhaulAcquire("betty", "") |
| + if !ok { |
| + t.Fatal("request slot refused") |
| + } |
| + t.Cleanup(rel) |
| + if c, resp := openBackhaulSocket(t, srv, ""); c != nil || resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") != "2" { |
| + t.Fatalf("upgrade request with the request pool full: %+v, want 503 + Retry-After 2", resp) |
| + } |
| +} |
| + |
| +// The stream share through the real handler with real client addresses: a |
| +// client over its share of a busy stream pool gets the 429 at its 101, |
| +// another client still gets sockets, and the refused hop leaks no slot. |
| +func TestBackhaulStreamShareAt101(t *testing.T) { |
| + e, m, _ := hopEdge(t, "annie", "local.test") |
| + e.rateMode = RateEnforce |
| + backhaulStreamCap(t, 8) // share 2, busy from 4 held |
| + _, eip := fakeHomeEdge(t, wsHome(t, nil)) |
| + homedOn(t, m, "betty", eip, "example.com") |
| + srv := peerFront(t, e) |
| + |
| + for i := 0; i < 4; i++ { |
| + if c, resp := openBackhaulSocket(t, srv, shareClientB); c == nil { |
| + t.Fatalf("B's socket %d: %d", i+1, resp.StatusCode) |
| + } |
| + } |
| + for i := 0; i < 2; i++ { |
| + if c, resp := openBackhaulSocket(t, srv, shareClientA); c == nil { |
| + t.Fatalf("A's socket %d: %d", i+1, resp.StatusCode) |
| + } |
| + } |
| + _, resp := openBackhaulSocket(t, srv, shareClientA) |
| + if resp.StatusCode != http.StatusTooManyRequests { |
| + t.Fatalf("A's third socket in a busy pool of 8: %d, want 429", resp.StatusCode) |
| + } |
| + if got := e.BackhaulSheds(); got != (BackhaulSheds{FairShare: 1}) { |
| + t.Fatalf("BackhaulSheds = %+v, want one share refusal", got) |
| + } |
| + waitFor(t, 10*time.Second, "the refused hop's request slot back", func() bool { |
| + return poolCount(&e.backhaulInflight, "betty") == 0 |
| + }) |
| + if got := poolCount(&e.backhaulStreamInflight, "betty"); got != 6 { |
| + t.Fatalf("stream pool = %d, want the 6 open sockets", got) |
| + } |
| + if c, resp := openBackhaulSocket(t, srv, "203.0.113.9"); c == nil { |
| + t.Fatalf("another client's socket: %d, want 101", resp.StatusCode) |
| + } |
| +} |
| + |
| +// A door caller is the box's own traffic: no share at the 101 either. |
| +func TestBackhaulStreamDoorExempt(t *testing.T) { |
| + e, _, _ := hopEdge(t, "annie", "local.test") |
| + e.rateMode = RateEnforce |
| + backhaulStreamCap(t, 8) |
| + r := httptest.NewRequest(http.MethodGet, "http://example.com/", nil) |
| + r.RemoteAddr = net.JoinHostPort(shareClientA, "40000") |
| + r = r.WithContext(context.WithValue(r.Context(), doorCallerKey{}, doorCaller{Account: "shop", App: "web"})) |
| + key := e.backhaulClientKey(r) |
| + for i := 0; i < 8; i++ { |
| + rel, err := e.backhaulStreamAt101("betty", "192.0.2.5", key) |
| + if err != nil { |
| + t.Fatalf("door caller's socket %d: %v", i+1, err) |
| + } |
| + t.Cleanup(rel) |
| + } |
| +} |
| + |
| +// armHopObserve runs fn once, on the first hop event named event: the |
| +// moment after admission and before the dial (hopTo). |
| +func armHopObserve(t *testing.T, event string, fn func()) { |
| + t.Helper() |
| + var once sync.Once |
| + hook := func(ev, _ string) { |
| + if ev == event { |
| + once.Do(fn) |
| + } |
| + } |
| + regionalObserve.Store(&hook) |
| + t.Cleanup(func() { regionalObserve.Store(nil) }) |
| +} |
| + |
| +// The advisory check: with the stream pool already full, an upgrade request |
| +// is refused before it dials or takes a request slot, while an ordinary GET |
| +// to the same box is untouched. |
| +func TestBackhaulUpgradeRefusedBeforeDialWhenStreamsFull(t *testing.T) { |
| + e, m, _ := hopEdge(t, "annie", "local.test") |
| + backhaulStreamCap(t, 1) |
| + rec, eip := fakeHomeEdge(t, wsHome(t, nil)) |
| + homedOn(t, m, "betty", eip, "example.com") |
| + srv := httptest.NewServer(e) |
| + t.Cleanup(srv.Close) |
| + rel, ok, _ := e.backhaulAcquireStream("betty", "") |
| + if !ok { |
| + t.Fatal("stream slot refused") |
| + } |
| + t.Cleanup(rel) |
| + |
| + c, resp := openBackhaulSocket(t, srv, "") |
| + if c != nil || resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") != "2" || |
| + resp.Header.Get("X-Carlos-Answer") != "backhaul-streams-busy" { |
| + t.Fatalf("socket toward a full stream pool: %+v, want 503 + Retry-After 2 from backhaul-streams-busy", resp) |
| + } |
| + if n := rec.get().n; n != 0 { |
| + t.Fatalf("the home saw %d request(s), want none: no dial", n) |
| + } |
| + if got := e.BackhaulSheds(); got != (BackhaulSheds{Streams: 1}) { |
| + t.Fatalf("BackhaulSheds = %+v, want one stream shed", got) |
| + } |
| + if got := poolCount(&e.backhaulInflight, "betty"); got != 0 { |
| + t.Fatalf("request pool = %d, want 0: the refusal took no request slot", got) |
| + } |
| + resp2, err := backhaulGetter(t, e)("example.com") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp2.Body.Close() |
| + if resp2.StatusCode != http.StatusOK { |
| + t.Fatalf("GET with the stream pool full: %d, want 200", resp2.StatusCode) |
| + } |
| +} |
| + |
| +// The race the advisory check cannot see: the stream pool has room at |
| +// admission and fills before the home's 101. The 101 is refused, the home |
| +// was reached, and neither pool leaks. |
| +func TestBackhaulStreamRaceRefusedAt101(t *testing.T) { |
| + e, m, _ := hopEdge(t, "annie", "local.test") |
| + backhaulStreamCap(t, 1) |
| + rec, eip := fakeHomeEdge(t, wsHome(t, nil)) |
| + homedOn(t, m, "betty", eip, "example.com") |
| + srv := httptest.NewServer(e) |
| + t.Cleanup(srv.Close) |
| + armHopObserve(t, "backhaul", func() { |
| + rel, ok, _ := e.backhaulAcquireStream("betty", "") |
| + if !ok { |
| + t.Error("the racing stream slot was refused") |
| + return |
| + } |
| + t.Cleanup(rel) |
| + }) |
| + |
| + c, resp := openBackhaulSocket(t, srv, "") |
| + if c != nil || resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("X-Carlos-Answer") != "backhaul-streams-busy" { |
| + t.Fatalf("socket that lost the race: %+v, want the 503 at its 101", resp) |
| + } |
| + if n := rec.get().n; n != 1 { |
| + t.Fatalf("the home saw %d request(s), want 1: refused at the 101", n) |
| + } |
| + if got := e.BackhaulSheds(); got != (BackhaulSheds{Streams: 1}) { |
| + t.Fatalf("BackhaulSheds = %+v, want one stream shed", got) |
| + } |
| + waitFor(t, 10*time.Second, "the request slot back", func() bool { |
| + return poolCount(&e.backhaulInflight, "betty") == 0 |
| + }) |
| + if got := poolCount(&e.backhaulStreamInflight, "betty"); got != 1 { |
| + t.Fatalf("stream pool = %d, want only the racing slot", got) |
| + } |
| +} |
| + |
| +// A forward whose destination answers 101 but whose stream slot is refused |
| +// here is still noted as the destination's 101: a local refusal must not |
| +// mark a healthy destination suspect. |
| +func TestForwardHAStreamRefusalAt101NotesTheDestination101(t *testing.T) { |
| + x := newFwScene(t, fwOpts{}) |
| + backhaulStreamCap(t, 1) |
| + armHopObserve(t, "forward", func() { |
| + rel, ok, _ := x.a.edge.backhaulAcquireStream("betty", "") |
| + if !ok { |
| + t.Error("the racing stream slot was refused") |
| + return |
| + } |
| + t.Cleanup(rel) |
| + }) |
| + raw, err := net.DialTimeout("tcp", x.a.tlsAddr, 10*time.Second) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c := tls.Client(raw, &tls.Config{ServerName: fwHost, RootCAs: x.ca.pool, MinVersion: tls.VersionTLS12}) |
| + defer c.Close() |
| + c.SetDeadline(time.Now().Add(10 * time.Second)) |
| + fmt.Fprintf(c, "GET /socket HTTP/1.1\r\nHost: %s\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n", fwHost) |
| + resp, err := http.ReadResponse(bufio.NewReader(c), nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("X-Carlos-Answer") != "backhaul-streams-busy" { |
| + t.Fatalf("handshake = %d (%s), want the stream pool's 503", resp.StatusCode, resp.Header.Get("X-Carlos-Answer")) |
| + } |
| + laWaitFor(t, "the forward's note", func() bool { return len(x.aAct.noted()) == 1 }) |
| + x.wantNote(t, fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Ref: "betty", Status: http.StatusSwitchingProtocols}}) |
| +} |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 7bb926a7b..233b57c76 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -444,6 +444,15 @@ type Edge struct { |
| // holds, for the fair share in backhaulAcquire. Keyed by box for the |
| // reason backhaulInflight is; each Shares bounds its own client keys. |
| backhaulShares sync.Map // box → *ratelimit.Shares |
| + // backhaulStreamInflight and backhaulStreamShares are the same pair for |
| + // the stream pool: the slots upgrade requests (WebSockets) take, held |
| + // for the life of the socket (backhaulAcquireStream). Keyed by box for |
| + // the same reason. |
| + backhaulStreamInflight sync.Map // box → *atomic.Int64 |
| + backhaulStreamShares sync.Map // box → *ratelimit.Shares |
| + // backhaulShed counts the hops backhaulAdmit refused, by kind, since |
| + // this edge started (BackhaulSheds). |
| + backhaulShed struct{ requests, streams, fairShare atomic.Uint64 } |
| // bodyReads counts, per client, the request bodies this edge is still |
| // waiting on (readBoundedBody), built on first use. Its own Shares, not |
| // a box's: the wait happens before any hop is admitted. |
| @@ -4678,9 +4687,19 @@ func fleetProxy(fleet, boxLabel string, authoritative bool, hub *TunnelHub) *htt |
| // its edges file. |
| // backhaulMaxInflight is the containment ruling of 2026-08-24: at most this |
| -// many backhauled requests may be in flight toward any ONE home box at a |
| -// time, counted on the SENDING edge. At the limit the sender answers 503 + |
| -// Retry-After: 2 (backhaul, below) rather than dialling. |
| +// many backhauled request/response hops may be in flight toward any ONE home |
| +// box at a time, counted on the SENDING edge. At the limit the sender answers |
| +// 503 + Retry-After: 2 (backhaulAdmit, below) rather than dialling. |
| +// |
| +// Since #1535 it is one of TWO pools per destination box. An upgraded hop (a |
| +// WebSocket) holds its slot for the life of the socket, so a few dozen |
| +// dashboard tabs holding sockets open filled the old single cap of 64 and |
| +// every ordinary request to that box got 503. Every hop is still admitted |
| +// here, upgrade request or not, and one the home answers with a 101 moves to |
| +// the stream pool (backhaulMaxStreams) at that moment (hopTo). So this pool |
| +// holds no open sockets. Its default stays 64, the ruling's number: the |
| +// split is the fix, not a larger cap. An operator who needs more raises |
| +// either limit per sending edge, in its host.env or as a group parameter. |
| // |
| // A concurrency bound and not a rate: cross-region egress is (concurrent |
| // streams × per-stream bandwidth), so a request-rate cap would neither bound |
| @@ -4692,7 +4711,9 @@ func fleetProxy(fleet, boxLabel string, authoritative bool, hub *TunnelHub) *htt |
| // Sender-side because every backhauled byte traverses BOTH legs (home → |
| // sender, sender → client), so one cap here bounds both boxes' egress at |
| // once; the home box needs no twin, its inbound hops being bounded by the sum |
| -// of its siblings' caps. |
| +// of its siblings' caps. With two pools that bound is the sum of both pools |
| +// over every sibling: at most backhaulMaxInflight + backhaulMaxStreams hops |
| +// from each sending edge toward any one box. |
| // |
| // A var, not a const, so a test can shorten it — the same reason backhaulPort |
| // is one. There is deliberately no "off" value: an unbounded cross-region |
| @@ -4706,29 +4727,96 @@ var backhaulMaxInflight atomic.Int64 |
| const defaultBackhaulMaxInflight = 64 |
| -func init() { backhaulMaxInflight.Store(defaultBackhaulMaxInflight) } |
| +// backhaulMaxStreams is the stream pool's cap: at most this many upgraded |
| +// hops (WebSockets) may be open toward any one home box at a time, counted |
| +// on the sending edge like backhaulMaxInflight and for the same egress |
| +// ruling. A var and atomic for backhaulMaxInflight's reasons. |
| +// |
| +// The pool is chosen from the RESPONSE, as the home edge's own rate limit |
| +// does (ServeHTTP's upgrade branch): the Upgrade header is the client's to |
| +// send, so it must not buy a request out of the request pool. A hop is |
| +// admitted on a request slot, and only when the home answers 101 does it |
| +// take a stream slot (with the stream pool's own fair share, for the same |
| +// client key) and give the request slot back (backhaulStreamAt101). A |
| +// stream pool with no room fails the hop there: the backend connection is |
| +// closed and the client gets 503 + Retry-After: 2, or the 429 for a share |
| +// refusal. So a stream slot is only ever a real upgraded socket. An upgrade |
| +// request toward a box whose stream pool is already full is refused the |
| +// same way before it dials (hopTo), so retries against a full pool cost no |
| +// request slot and never reach the app. |
| +// |
| +// What a socket costs, estimated and not measured: about 100 KB per upgraded |
| +// hop on each of the two boxes, from the proxy's two 32 KiB copy buffers, |
| +// the TLS state and three goroutines. A full default pool of 128 is about |
| +// 13 MB on the home box per sending sibling. The sender pays the same per |
| +// destination box, so its own worst case is that times the number of home |
| +// boxes it forwards to. The home box carries that same cost for a visitor |
| +// who opens the socket to it directly, and it has no cap on direct upgrades |
| +// (planthrottle.go's refusal of a throttled account aside), so a relayed |
| +// socket adds no exposure beyond the same visitors connecting directly. The |
| +// sum over the home box's sending edges is its worst case. One aggregate |
| +// budget on the receiving side, across every sender, is a follow-up. |
| +// |
| +// Not reclassified in this slice: a long-lived response to an ordinary |
| +// request (server-sent events, a long poll) still holds a request-pool slot |
| +// for its life. Moving those is a follow-up. |
| +var backhaulMaxStreams atomic.Int64 |
| + |
| +const defaultBackhaulMaxStreams = 128 |
| + |
| +func init() { |
| + backhaulMaxInflight.Store(defaultBackhaulMaxInflight) |
| + backhaulMaxStreams.Store(defaultBackhaulMaxStreams) |
| +} |
| // backhaulInflightFromEnv reads CARLOS_BACKHAUL_MAX_INFLIGHT. Unset, |
| // unparseable or ≤ 0 all mean the default: a typo'd knob must not silently |
| // uncap (or, worse, zero-cap) a deployment's backhaul. |
| func backhaulInflightFromEnv() int { |
| - raw := strings.TrimSpace(os.Getenv("CARLOS_BACKHAUL_MAX_INFLIGHT")) |
| + return backhaulCapFromEnv("CARLOS_BACKHAUL_MAX_INFLIGHT", defaultBackhaulMaxInflight, "concurrent backhauled requests per home box") |
| +} |
| + |
| +// backhaulStreamsFromEnv reads CARLOS_BACKHAUL_MAX_STREAMS, by |
| +// backhaulInflightFromEnv's rules. |
| +func backhaulStreamsFromEnv() int { |
| + return backhaulCapFromEnv("CARLOS_BACKHAUL_MAX_STREAMS", defaultBackhaulMaxStreams, "open backhauled WebSockets per home box") |
| +} |
| + |
| +func backhaulCapFromEnv(name string, def int, what string) int { |
| + raw := strings.TrimSpace(os.Getenv(name)) |
| if raw == "" { |
| - return defaultBackhaulMaxInflight |
| + return def |
| } |
| n, err := strconv.Atoi(raw) |
| if err != nil || n <= 0 { |
| - log.Printf("edge: CARLOS_BACKHAUL_MAX_INFLIGHT=%q is not a positive integer — using the default of %d concurrent backhauled requests per home box", raw, defaultBackhaulMaxInflight) |
| - return defaultBackhaulMaxInflight |
| + log.Printf("edge: %s=%q is not a positive integer; using the default of %d %s", name, raw, def, what) |
| + return def |
| } |
| return n |
| } |
| // backhaulClientShare is the most slots one client may hold toward a |
| // destination box while the box is at least half full. A fixed number, not a |
| -// setting: the sending edge has no route row to read one from (#358). |
| +// setting: the sending edge has no route row to read one from (#358). It is |
| +// scaled down for a small cap (backhaulShare). |
| const backhaulClientShare = 8 |
| +// backhaulStreamClientShare is the same for the stream pool: the most open |
| +// sockets one client may hold toward a box while that box's stream pool is |
| +// at least half full. Larger than backhaulClientShare because a real |
| +// visitor's browser holds several sockets for as long as its tabs are open, |
| +// and no more than a quarter of any pool (backhaulShare), so one client |
| +// cannot fill it: at the default cap of 128 the share is 32, and the whole |
| +// 64 applies from a cap of 256. |
| +const backhaulStreamClientShare = 64 |
| + |
| +// backhaulShare is a pool's per-client share at cap limit: the pool's |
| +// constant, but never more than a quarter of the cap (and at least one), so |
| +// an operator who lowers a cap does not leave one client able to fill it. |
| +func backhaulShare(share int, limit int64) int { |
| + return int(min(int64(share), max(1, limit/4))) |
| +} |
| + |
| // backhaulSharesMaxKeys bounds the clients tracked per destination box. |
| const backhaulSharesMaxKeys = 10_000 |
| @@ -4750,12 +4838,34 @@ func (e *Edge) backhaulClientKey(r *http.Request) string { |
| return p.String() |
| } |
| -// backhaulAcquire reserves one in-flight slot toward box, or reports why it |
| -// cannot: saturation (ok and shed both false, the box's cap is spent) or a |
| +// backhaulPool is one of a box's two pools: where its counts live, its cap |
| +// and fair share, and the names its log lines use. |
| +type backhaulPool struct { |
| + inflight, shares *sync.Map |
| + limit int64 |
| + share int |
| + logKey string // throttle key prefix for a share refusal |
| + slots string // what the log line calls the pool's slots |
| +} |
| + |
| +func (e *Edge) requestPool() backhaulPool { |
| + limit := backhaulMaxInflight.Load() |
| + return backhaulPool{&e.backhaulInflight, &e.backhaulShares, limit, backhaulShare(backhaulClientShare, limit), |
| + "backhaul-share ", "slots"} |
| +} |
| + |
| +func (e *Edge) streamPool() backhaulPool { |
| + limit := backhaulMaxStreams.Load() |
| + return backhaulPool{&e.backhaulStreamInflight, &e.backhaulStreamShares, limit, backhaulShare(backhaulStreamClientShare, limit), |
| + "backhaul-streams-share ", "stream slots"} |
| +} |
| + |
| +// backhaulAcquire reserves one request-pool slot toward box, or reports why |
| +// it cannot: saturation (ok and shed both false, the box's cap is spent) or a |
| // fair-share refusal (shed true). releaseSlot must be called exactly once |
| -// when the hop's ServeHTTP returns — a streaming or upgraded response holds |
| -// its slot for the life of the stream, deliberately: a long-lived stream IS |
| -// sustained cross-region egress, which is the thing being bounded. |
| +// when the hop's ServeHTTP returns — a streaming response holds its slot for |
| +// the life of the stream, deliberately: a long-lived stream IS sustained |
| +// cross-region egress, which is the thing being bounded. |
| // |
| // The fair share is the home edge's rule over the sending edge's slots: while |
| // the box's slots are at least half taken, a client that already holds |
| @@ -4774,16 +4884,28 @@ func (e *Edge) backhaulClientKey(r *http.Request) string { |
| // cross-region bytes the cap exists to prevent. A fair-share refusal rolls |
| // the count back the same way. |
| func (e *Edge) backhaulAcquire(box, clientKey string) (releaseSlot func(), ok bool, shed bool) { |
| + return e.acquirePoolSlot(e.requestPool(), box, clientKey) |
| +} |
| + |
| +// backhaulAcquireStream is backhaulAcquire over the stream pool, for a hop |
| +// the home has answered with a 101: its own counts, its own cap |
| +// (backhaulMaxStreams) and its own fair share (backhaulStreamClientShare), |
| +// with every rule above. An upgraded hop holds its slot for the life of the |
| +// socket. |
| +func (e *Edge) backhaulAcquireStream(box, clientKey string) (releaseSlot func(), ok bool, shed bool) { |
| + return e.acquirePoolSlot(e.streamPool(), box, clientKey) |
| +} |
| + |
| +func (e *Edge) acquirePoolSlot(p backhaulPool, box, clientKey string) (releaseSlot func(), ok bool, shed bool) { |
| // Load first, like backhaulTransport: LoadOrStore would allocate a |
| // counter per backhauled request just to throw it away on the hit path. |
| - v, hit := e.backhaulInflight.Load(box) |
| + v, hit := p.inflight.Load(box) |
| if !hit { |
| - v, _ = e.backhaulInflight.LoadOrStore(box, new(atomic.Int64)) |
| + v, _ = p.inflight.LoadOrStore(box, new(atomic.Int64)) |
| } |
| n := v.(*atomic.Int64) |
| - limit := backhaulMaxInflight.Load() |
| held := n.Add(1) |
| - if held > limit { |
| + if held > p.limit { |
| n.Add(-1) |
| return nil, false, false |
| } |
| @@ -4793,27 +4915,27 @@ func (e *Edge) backhaulAcquire(box, clientKey string) (releaseSlot func(), ok bo |
| var once sync.Once |
| var releaseShare func() |
| if clientKey != "" && e.rateMode != RateOff { |
| - sv, hit := e.backhaulShares.Load(box) |
| + sv, hit := p.shares.Load(box) |
| if !hit { |
| - sv, _ = e.backhaulShares.LoadOrStore(box, ratelimit.NewShares(backhaulSharesMaxKeys)) |
| + sv, _ = p.shares.LoadOrStore(box, ratelimit.NewShares(backhaulSharesMaxKeys)) |
| } |
| shares := sv.(*ratelimit.Shares) |
| // Busy is the slots already taken, not counting this request. |
| - busy := held-1 >= limit/2 |
| - rel, admitted := shares.Acquire(clientKey, busy, backhaulClientShare) |
| + busy := held-1 >= p.limit/2 |
| + rel, admitted := shares.Acquire(clientKey, busy, p.share) |
| if !admitted { |
| verb := "refused" |
| if e.rateMode == RateObserve { |
| verb = "would refuse" |
| } |
| - e.logThrottled("backhaul-share "+box, fmt.Sprintf( |
| - "backhaul to %s is at least half full (%d of %d slots) and client %s holds %d of them — %s the request (fair share %d)", |
| - box, held-1, limit, clientKey, shares.Held(clientKey), verb, backhaulClientShare)) |
| + e.logThrottled(p.logKey+box, fmt.Sprintf( |
| + "backhaul to %s is at least half full (%d of %d %s) and client %s holds %d of them; %s the request (fair share %d)", |
| + box, held-1, p.limit, p.slots, clientKey, shares.Held(clientKey), verb, p.share)) |
| if e.rateMode == RateEnforce { |
| n.Add(-1) |
| return nil, false, true |
| } |
| - rel, _ = shares.Acquire(clientKey, false, backhaulClientShare) |
| + rel, _ = shares.Acquire(clientKey, false, p.share) |
| } |
| releaseShare = rel |
| } |
| @@ -4827,6 +4949,27 @@ func (e *Edge) backhaulAcquire(box, clientKey string) (releaseSlot func(), ok bo |
| }, true, false |
| } |
| +// BackhaulSheds is how many hops this edge's backhaul has refused since it |
| +// started, by kind: request-pool saturation and stream-pool saturation (both |
| +// a 503) and fair-share refusals of either pool (a 429). Observe mode's |
| +// "would refuse" is not a refusal and is not counted. The agent's metrics |
| +// loop reads it once a tick: all three go into the metrics sample, and the |
| +// two saturation kinds feed the backhaul_shed rule. |
| +type BackhaulSheds struct { |
| + Requests uint64 |
| + Streams uint64 |
| + FairShare uint64 |
| +} |
| + |
| +// BackhaulSheds reads the counters. In-process atomics only: no store read. |
| +func (e *Edge) BackhaulSheds() BackhaulSheds { |
| + return BackhaulSheds{ |
| + Requests: e.backhaulShed.requests.Load(), |
| + Streams: e.backhaulShed.streams.Load(), |
| + FairShare: e.backhaulShed.fairShare.Load(), |
| + } |
| +} |
| + |
| // backhaulPort is the port a home edge answers on. Always 443 in production — |
| // an edges file publishes a bare EIP (Task 1) and every edge's front door is |
| // 443 — and a var only so a test can point the dial at an httptest server, the |
| @@ -4905,14 +5048,32 @@ func (e *Edge) backhaulTo(w http.ResponseWriter, r *http.Request, host, eip, box |
| func (e *Edge) hopTo(w http.ResponseWriter, r *http.Request, host, eip, box string, key []byte, event string, tr http.RoundTripper, |
| onError func(http.ResponseWriter, *http.Request, error), onResponse func(*http.Response)) bool { |
| // Containment (the egress ruling, 2026-08-24), between the last guard and |
| - // the dial: backhaulAdmit answers a refused hop itself. |
| + // the dial: backhaulAdmit answers a refused hop itself. Every hop starts |
| + // on a request slot, upgrade request or not (backhaulMaxStreams). |
| + // |
| + // An upgrade request toward a box whose stream pool is already full is |
| + // refused first, with no dial: it could only be refused at its 101, after |
| + // holding a request slot for the handshake and reaching the app. This is |
| + // advisory, and only ever refuses: the header admits nothing, and the |
| + // stream slot is still taken at the 101, which is refused there if |
| + // another socket took the last slot in between. |
| + if isUpgradeRequest(r) && e.backhaulStreamsFull(box) { |
| + e.refuseBackhaulStream(box, eip) |
| + answerBackhaulStreamsBusy(w) |
| + return false |
| + } |
| + clientKey := e.backhaulClientKey(r) |
| releaseSlot, ok := e.backhaulAdmit(w, r, eip, box) |
| if !ok { |
| return false |
| } |
| - // Held until the hop's ServeHTTP returns, which for a stream or an |
| - // upgraded connection is the life of the stream (backhaulAcquire). |
| - defer releaseSlot() |
| + // Held until the hop's ServeHTTP returns, which for a stream is the |
| + // life of the stream (backhaulAcquire). A 101 swaps it for a stream |
| + // slot (below) before the proxy hijacks the connection. The swap runs |
| + // in the proxy's ModifyResponse, on this goroutine, so slot needs no |
| + // lock. |
| + slot := releaseSlot |
| + defer func() { slot() }() |
| // The MAC is over the CONCRETE request host — never the wildcard map key |
| // that may have matched it — because the home edge verifies against its own |
| // literal request host (hopMAC canonicalizes both, mesh.go). |
| @@ -4935,6 +5096,46 @@ func (e *Edge) hopTo(w http.ResponseWriter, r *http.Request, host, eip, box stri |
| return scrub(resp) |
| } |
| } |
| + // A 101 is an open socket from here on: it takes a stream slot and gives |
| + // the request slot back, or the hop fails. A refusal returned from |
| + // ModifyResponse makes the proxy close the backend connection (the 101's |
| + // body) and call ErrorHandler, which answers it below, before any other |
| + // error handling (a retry must not take a refused upgrade elsewhere). |
| + // The destination did answer, and well: onResponse still sees its 101, |
| + // so a forward's health observation (forwardHAObserved) records a |
| + // success and not a destination failure. Only the scrub is skipped. |
| + modify := p.ModifyResponse |
| + p.ModifyResponse = func(resp *http.Response) error { |
| + if resp.StatusCode == http.StatusSwitchingProtocols { |
| + stream, err := e.backhaulStreamAt101(box, eip, clientKey) |
| + if err != nil { |
| + if onResponse != nil { |
| + onResponse(resp) |
| + } |
| + return err |
| + } |
| + request := slot |
| + slot = stream |
| + request() |
| + } |
| + if modify == nil { |
| + return nil |
| + } |
| + return modify(resp) |
| + } |
| + fail := p.ErrorHandler |
| + p.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) { |
| + switch { |
| + case errors.Is(err, errBackhaulStreamShare): |
| + writeRateLimited(w, time.Second) |
| + case errors.Is(err, errBackhaulStreamsBusy): |
| + answerBackhaulStreamsBusy(w) |
| + case fail != nil: |
| + fail(w, r, err) |
| + default: |
| + w.WriteHeader(http.StatusBadGateway) |
| + } |
| + } |
| // The client boundary for informational responses: a 1xx from the home |
| // reaches w through the proxy's trace hook, past ModifyResponse, so the |
| // asset vocabulary comes off it here (assetInformationalScrub). |
| @@ -4943,10 +5144,12 @@ func (e *Edge) hopTo(w http.ResponseWriter, r *http.Request, host, eip, box stri |
| return true |
| } |
| -// backhaulAdmit takes one backhaul slot toward box for r's client |
| +// backhaulAdmit takes one request-pool slot toward box for r's client |
| // (backhaulAcquire with backhaulClientKey), or answers the refusal on w and |
| -// reports false. It is the one place both refusals are written, for an |
| -// ordinary hop (backhaulTo) and for a far asset fill (serveAssetFar). |
| +// reports false. It is the one place a hop's admission refusals are written |
| +// and counted (BackhaulSheds), for an ordinary hop (hopTo) and for a far |
| +// asset fill (serveAssetFar). An upgrade request is admitted here like any |
| +// other; its stream slot is taken at the 101 (backhaulStreamAt101). |
| // |
| // A saturated home box is answered here, with no dial and no bytes crossing |
| // a region. 503 + Retry-After: 2 is this package's established "come back |
| @@ -4963,18 +5166,67 @@ func (e *Edge) backhaulAdmit(w http.ResponseWriter, r *http.Request, eip, box st |
| if shed { |
| // The fair share, not saturation: this client holds its share of a |
| // busy hop. The same 429 the home edge gives (writeRateLimited). |
| + e.backhaulShed.fairShare.Add(1) |
| writeRateLimited(w, time.Second) |
| return nil, false |
| } |
| if !ok { |
| + e.backhaulShed.requests.Add(1) |
| e.logThrottled("backhaul-saturated "+box, |
| - fmt.Sprintf("backhaul to %s (%s) is at its in-flight cap (%d) — answering 503 + Retry-After: 2", box, eip, backhaulMaxInflight.Load())) |
| + fmt.Sprintf("backhaul to %s (%s) is at its in-flight cap (%d); answering 503 with Retry-After: 2", box, eip, backhaulMaxInflight.Load())) |
| Unavailable(w, "backhaul-busy", "temporarily busy", 2) |
| return nil, false |
| } |
| return releaseSlot, true |
| } |
| +// The refusals backhaulStreamAt101 returns, which hopTo's ErrorHandler |
| +// answers: the stream pool's fair share (429) and its cap (503). |
| +var ( |
| + errBackhaulStreamShare = errors.New("backhaul: client holds its share of the stream pool") |
| + errBackhaulStreamsBusy = errors.New("backhaul: stream pool full") |
| +) |
| + |
| +// backhaulStreamAt101 takes a stream slot toward box for the client with |
| +// clientKey, once the home has answered a hop with 101 Switching Protocols, |
| +// or counts and logs the refusal and returns the error that fails the hop. |
| +// The log key is per box, "backhaul-streams-saturated "+box, beside the |
| +// request pool's "backhaul-saturated "+box. |
| +func (e *Edge) backhaulStreamAt101(box, eip, clientKey string) (releaseSlot func(), err error) { |
| + releaseSlot, ok, shed := e.backhaulAcquireStream(box, clientKey) |
| + switch { |
| + case shed: |
| + e.backhaulShed.fairShare.Add(1) |
| + return nil, errBackhaulStreamShare |
| + case !ok: |
| + e.refuseBackhaulStream(box, eip) |
| + return nil, errBackhaulStreamsBusy |
| + } |
| + return releaseSlot, nil |
| +} |
| + |
| +// backhaulStreamsFull reports whether box's stream pool is at its cap now: |
| +// hopTo's advisory refusal of an upgrade request before it dials. A read of |
| +// the counter, so it can be stale either way; the 101 decides. |
| +func (e *Edge) backhaulStreamsFull(box string) bool { |
| + v, ok := e.backhaulStreamInflight.Load(box) |
| + return ok && v.(*atomic.Int64).Load() >= backhaulMaxStreams.Load() |
| +} |
| + |
| +// refuseBackhaulStream counts and logs one stream-pool saturation, at |
| +// admission or at the 101, under one per-box log key. |
| +func (e *Edge) refuseBackhaulStream(box, eip string) { |
| + e.backhaulShed.streams.Add(1) |
| + e.logThrottled("backhaul-streams-saturated "+box, |
| + fmt.Sprintf("backhaul to %s (%s) is at its stream cap (%d open WebSockets); answering 503 with Retry-After: 2", box, eip, backhaulMaxStreams.Load())) |
| +} |
| + |
| +// answerBackhaulStreamsBusy is the stream pool's 503, the one place its |
| +// site is named (each Unavailable site is one call site). |
| +func answerBackhaulStreamsBusy(w http.ResponseWriter) { |
| + Unavailable(w, "backhaul-streams-busy", "temporarily busy", 2) |
| +} |
| + |
| // backhaulTransport is the cached outbound transport for one home box. The |
| // TRANSPORT is what is cached and the ReverseProxy above is what is rebuilt |
| // per request: a proxy value is two closures, while a transport owns the |
| @@ -5231,6 +5483,7 @@ func RunWithActivatorReady(args []string, act Activator, cache *Cache, ready fun |
| // than per request (backhaulMaxInflight). Inert on a single-box |
| // deployment, where nothing is ever backhauled at all. |
| backhaulMaxInflight.Store(int64(backhaulInflightFromEnv())) |
| + backhaulMaxStreams.Store(int64(backhaulStreamsFromEnv())) |
| // GeoIP (geoip spec §5.1): a tunnel client takes the hub's answer and |
| // mirrors nothing; an edge with the deployment store mirrors; anything |
diff --git a/internal/edge/handover_test.go b/internal/edge/handover_test.go| index 61b92910b..27ec084c8 100644 |
| --- a/internal/edge/handover_test.go |
| +++ b/internal/edge/handover_test.go |
| @@ -591,12 +591,14 @@ func TestHandoverExitOnUnfinishedBodies(t *testing.T) { |
| } |
| } |
| -// hoCap puts every hop at its admission cap. |
| +// hoCap puts every hop at its admission cap: both pools, since an upgrade |
| +// request takes a stream slot (#1535). |
| func hoCap(t *testing.T) { |
| t.Helper() |
| - old := backhaulMaxInflight.Load() |
| + old, oldStreams := backhaulMaxInflight.Load(), backhaulMaxStreams.Load() |
| backhaulMaxInflight.Store(0) |
| - t.Cleanup(func() { backhaulMaxInflight.Store(old) }) |
| + backhaulMaxStreams.Store(0) |
| + t.Cleanup(func() { backhaulMaxInflight.Store(old); backhaulMaxStreams.Store(oldStreams) }) |
| } |
| // hoUnreachable makes every forward dial fail at once, as a refused |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index b17568d23..6910a89d0 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -1402,6 +1402,9 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| heldStreamsSource.Store(e.HeldStreamsForStatus) |
| geoIPAlertSource.Store(e.GeoIPAlertCode) |
| staticTreeSource.Store(e.LargestStaticTree) |
| + // The backhaul's refusal counters for the backhaul_shed rule |
| + // (#1535), the same way: in-process, no store read. |
| + backhaulShedSource.Store(e.BackhaulSheds) |
| // The layout pass reloads routing through this as soon as a move |
| // commits, instead of waiting for the 2s registry poll. |
| reload := func() { _ = e.Reload() } |
diff --git a/internal/host/backhaulshed.go b/internal/host/backhaulshed.go| new file mode 100644 |
| index 000000000..40b01bcdd |
| --- /dev/null |
| +++ b/internal/host/backhaulshed.go |
| @@ -0,0 +1,33 @@ |
| +package host |
| + |
| +import ( |
| + "sync/atomic" |
| + |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/metrics" |
| +) |
| + |
| +// backhaulShedSource is the edge's Edge.BackhaulSheds, published once the |
| +// edge exists, for the metrics sample and the backhaul_shed rule (#1535). |
| +var backhaulShedSource atomic.Value // func() edge.BackhaulSheds |
| + |
| +// backhaulShedCounts reads it, false before the edge is ready. |
| +func backhaulShedCounts() (metrics.BackhaulShedSample, bool) { |
| + fn, _ := backhaulShedSource.Load().(func() edge.BackhaulSheds) |
| + if fn == nil { |
| + return metrics.BackhaulShedSample{}, false |
| + } |
| + c := fn() |
| + return metrics.BackhaulShedSample{Requests: c.Requests, Streams: c.Streams, FairShare: c.FairShare}, true |
| +} |
| + |
| +// sampleBackhaulSheds is the counters as a sample carries them: nil before |
| +// the edge is ready and while it has refused nothing, so a quiet box's |
| +// samples are what they were before the counters existed. |
| +func sampleBackhaulSheds() *metrics.BackhaulShedSample { |
| + c, ok := backhaulShedCounts() |
| + if !ok || c == (metrics.BackhaulShedSample{}) { |
| + return nil |
| + } |
| + return &c |
| +} |
diff --git a/internal/host/metrics_backhaul_test.go b/internal/host/metrics_backhaul_test.go| new file mode 100644 |
| index 000000000..de778b2f9 |
| --- /dev/null |
| +++ b/internal/host/metrics_backhaul_test.go |
| @@ -0,0 +1,221 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// setBackhaulShedSource stands in for the edge-ready callback for one test. |
| +func setBackhaulShedSource(t *testing.T, fn func() edge.BackhaulSheds) { |
| + t.Helper() |
| + old := backhaulShedSource.Load() |
| + t.Cleanup(func() { |
| + if old != nil { |
| + backhaulShedSource.Store(old) |
| + } else { |
| + backhaulShedSource.Store((func() edge.BackhaulSheds)(nil)) |
| + } |
| + }) |
| + backhaulShedSource.Store(fn) |
| +} |
| + |
| +// The edge's backhaul refusal counters reach the metrics loop through the |
| +// same in-process seam as the geoip code: a func the edge-ready callback |
| +// publishes. Before the edge is ready there is no reading; while it has |
| +// refused nothing the sample carries none, but the counts still read zero. |
| +func TestSampleBackhaulShedsReadsTheEdge(t *testing.T) { |
| + setBackhaulShedSource(t, nil) |
| + if got := sampleBackhaulSheds(); got != nil { |
| + t.Fatalf("before the edge is ready: %+v, want nil", got) |
| + } |
| + if _, ok := backhaulShedCounts(); ok { |
| + t.Fatal("counts before the edge is ready") |
| + } |
| + counts := edge.BackhaulSheds{} |
| + setBackhaulShedSource(t, func() edge.BackhaulSheds { return counts }) |
| + if got := sampleBackhaulSheds(); got != nil { |
| + t.Fatalf("a quiet edge: %+v, want nil so samples keep their old shape", got) |
| + } |
| + if c, ok := backhaulShedCounts(); !ok || c != (metrics.BackhaulShedSample{}) { |
| + t.Fatalf("a quiet edge's counts: %+v %v, want zeros", c, ok) |
| + } |
| + counts = edge.BackhaulSheds{Requests: 1, Streams: 2, FairShare: 3} |
| + got := sampleBackhaulSheds() |
| + if got == nil || *got != (metrics.BackhaulShedSample{Requests: 1, Streams: 2, FairShare: 3}) { |
| + t.Fatalf("sampleBackhaulSheds = %+v, want the edge's counters", got) |
| + } |
| +} |
| + |
| +// A sample carries the counters when there are any and omits the key when |
| +// there are none. |
| +func TestSamplerCarriesBackhaulSheds(t *testing.T) { |
| + var counts *metrics.BackhaulShedSample |
| + at := time.Date(2026, 12, 2, 12, 0, 0, 0, time.UTC) |
| + probes := sampleProbes{ |
| + procStat: func() *metrics.CPUCounters { return nil }, |
| + loadavg: func() (*float64, *float64, *float64) { return nil, nil, nil }, |
| + memFrac: func() *float64 { return nil }, |
| + diskFrac: func() *float64 { return nil }, |
| + units: func() map[string]unitRaw { return nil }, |
| + now: func() time.Time { return at }, |
| + backhaulSheds: func() *metrics.BackhaulShedSample { return counts }, |
| + } |
| + sm := &sampler{} |
| + sm.tick(probes) |
| + counts = &metrics.BackhaulShedSample{Requests: 5, Streams: 20} |
| + sm.tick(probes) |
| + quiet, err := json.Marshal(sm.buf[0]) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if strings.Contains(string(quiet), "backhaul_sheds") { |
| + t.Fatalf("a quiet sample carries the key: %s", quiet) |
| + } |
| + b, err := json.Marshal(sm.buf[1]) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var back metrics.Sample |
| + if err := json.Unmarshal(b, &back); err != nil || back.BackhaulSheds == nil || *back.BackhaulSheds != *counts { |
| + t.Fatalf("chunk round trip: %s (%v)", b, err) |
| + } |
| +} |
| + |
| +// The watch reads saturation refusals since the last tick, carries the |
| +// largest reading across failed ticks, and clears the carry on a success. |
| +func TestBackhaulShedWatch(t *testing.T) { |
| + var w backhaulShedWatch |
| + var got []any |
| + feed := func(cur *metrics.BackhaulShedSample, fail bool) { |
| + t.Helper() |
| + w.tick(cur, func(r *float64) error { |
| + if r == nil { |
| + got = append(got, nil) |
| + } else { |
| + got = append(got, *r) |
| + } |
| + if fail { |
| + return context.DeadlineExceeded |
| + } |
| + return nil |
| + }) |
| + } |
| + feed(nil, false) |
| + feed(&metrics.BackhaulShedSample{Requests: 5, FairShare: 50}, false) |
| + feed(&metrics.BackhaulShedSample{Requests: 5, Streams: 20, FairShare: 90}, true) |
| + feed(&metrics.BackhaulShedSample{Requests: 5, Streams: 20, FairShare: 90}, false) |
| + feed(&metrics.BackhaulShedSample{Requests: 5, Streams: 20, FairShare: 99}, false) |
| + // A long outage with a trickle: 6 a minute never adds up to a fire. |
| + for i, c := range []uint64{26, 32, 38} { |
| + feed(&metrics.BackhaulShedSample{Requests: 5, Streams: c}, i < 2) |
| + } |
| + feed(&metrics.BackhaulShedSample{Requests: 5, Streams: 38}, false) |
| + want := []any{nil, 5.0, 20.0, 20.0, 0.0, 6.0, 6.0, 6.0, 0.0} |
| + if len(got) != len(want) { |
| + t.Fatalf("readings = %v, want %v", got, want) |
| + } |
| + for i := range want { |
| + if got[i] != want[i] { |
| + t.Fatalf("readings = %v, want %v", got, want) |
| + } |
| + } |
| +} |
| + |
| +// shedRig drives the watch and alertTick one minute at a time, the way |
| +// metricsLoop does, against a store that can be made to fail. |
| +type shedRig struct { |
| + t *testing.T |
| + ctx context.Context |
| + store release.Store |
| + path string |
| + st *metrics.AlertState |
| + sinks *alertSinks |
| + posts *int |
| + watch backhaulShedWatch |
| + at time.Time |
| + counter metrics.BackhaulShedSample |
| +} |
| + |
| +func newShedRig(t *testing.T) *shedRig { |
| + posts := 0 |
| + return &shedRig{ |
| + t: t, ctx: context.Background(), |
| + store: release.NewDirStore(t.TempDir()), |
| + path: filepath.Join(t.TempDir(), "monitor", "alerts.json"), |
| + st: &metrics.AlertState{V: 1, Box: "box-a", Rules: map[string]metrics.RuleState{}}, |
| + sinks: webhookSinks("http://example.test/webhook", func(string, []byte) error { posts++; return nil }), |
| + posts: &posts, |
| + at: time.Date(2026, 12, 2, 12, 0, 0, 0, time.UTC), |
| + } |
| +} |
| + |
| +// tick adds n saturation refusals to the edge's counter, runs a minute on |
| +// store s, and returns the published backhaul_shed state. |
| +func (r *shedRig) tick(s release.Store, n uint64) (metrics.RuleState, error) { |
| + r.t.Helper() |
| + r.at = r.at.Add(time.Minute) |
| + r.counter.Streams += n |
| + cur := r.counter |
| + err := r.watch.tick(&cur, func(reading *float64) error { |
| + return alertTick(r.ctx, s, "box-a", metrics.DefaultRules(), r.st, metrics.Sample{At: r.at}, alertReadings{backhaulSheds: reading}, r.path, r.sinks, nil, nil) |
| + }) |
| + body, _, gerr := r.store.Get(r.ctx, metrics.AlertKey("box-a")) |
| + if gerr != nil { |
| + return metrics.RuleState{}, err |
| + } |
| + var pub metrics.AlertState |
| + if jerr := json.Unmarshal(body, &pub); jerr != nil { |
| + r.t.Fatal(jerr) |
| + } |
| + return pub.Rules[metrics.BackhaulShedRule], err |
| +} |
| + |
| +// backhaul_shed is published to the box's alert object like every box |
| +// rule, fires, holds through two quiet minutes and clears on the third, and |
| +// is not a box-sink rule: it reaches operators through the console's alert |
| +// engine. |
| +func TestAlertTickPublishesBackhaulShed(t *testing.T) { |
| + r := newShedRig(t) |
| + if rs, err := r.tick(r.store, 40); err != nil || !rs.Firing || rs.Value != 40 { |
| + t.Fatalf("40 refusals in a minute: published %+v (%v), want firing with 40", rs, err) |
| + } |
| + for i := 1; i <= 2; i++ { |
| + if rs, _ := r.tick(r.store, 0); !rs.Firing { |
| + t.Fatalf("quiet minute %d: published %+v, want still firing", i, rs) |
| + } |
| + } |
| + if rs, err := r.tick(r.store, 0); err != nil || rs.Firing { |
| + t.Fatalf("third quiet minute: published %+v (%v), want cleared", rs, err) |
| + } |
| + if *r.posts != 0 { |
| + t.Fatalf("the box's own sink got %d post(s), want none: backhaul_shed is not a box-sink rule", *r.posts) |
| + } |
| + if boxSinkRule(metrics.BackhaulShedRule) { |
| + t.Fatal("backhaul_shed is a box-sink rule") |
| + } |
| +} |
| + |
| +// A firing transition whose publish failed is not lost to the next quiet |
| +// minute: the refusals stay in the count until a tick publishes. |
| +func TestBackhaulShedFiresAfterAFailedPublish(t *testing.T) { |
| + r := newShedRig(t) |
| + fail := &failingPutStore{Store: release.NewDirStore(t.TempDir())} |
| + if _, err := r.tick(fail, 40); err == nil { |
| + t.Fatal("the publish against a failing store succeeded") |
| + } |
| + if r.st.Rules[metrics.BackhaulShedRule].Firing { |
| + t.Fatal("committed state fired without a publish") |
| + } |
| + rs, err := r.tick(r.store, 0) // a quiet minute, and the store is back |
| + if err != nil || !rs.Firing || rs.Value != 40 { |
| + t.Fatalf("the quiet minute after the failed publish: published %+v (%v), want the 40 refusals firing", rs, err) |
| + } |
| +} |
diff --git a/internal/host/metrics_loop.go b/internal/host/metrics_loop.go| index 8ac3df446..3dc4ee270 100644 |
| --- a/internal/host/metrics_loop.go |
| +++ b/internal/host/metrics_loop.go |
| @@ -50,6 +50,9 @@ type sampleProbes struct { |
| demoDisk func() *status.DemoDisk |
| now func() time.Time |
| departures func() *metrics.DepartureSample |
| + // backhaulSheds is the edge's backhaul refusal counters |
| + // (sampleBackhaulSheds); nil, or nil from it, puts none in the sample. |
| + backhaulSheds func() *metrics.BackhaulShedSample |
| } |
| // samplerMaxBuf hard-caps sm.buf at ~2h of 60s ticks. metricsFlush only |
| @@ -149,9 +152,14 @@ func (sm *sampler) tick(p sampleProbes) { |
| if p.departures != nil { |
| departures = p.departures() |
| } |
| + var sheds *metrics.BackhaulShedSample |
| + if p.backhaulSheds != nil { |
| + sheds = p.backhaulSheds() |
| + } |
| sm.buf = append(sm.buf, metrics.Sample{ |
| - HADepartures: departures, |
| - At: now, |
| + HADepartures: departures, |
| + BackhaulSheds: sheds, |
| + At: now, |
| Host: metrics.HostSample{ |
| CPUFrac: hostCPU, |
| Load1: l1, |
| @@ -563,6 +571,8 @@ func alertTick(ctx context.Context, s release.Store, box string, rules metrics.R |
| GeoIP: geoIPAlertReading(latest.At), |
| Restarts: extra.restarts, |
| Verify: extra.verify, |
| + // backhaul_shed (#1535): refusals since the last tick. |
| + BackhaulSheds: extra.backhaulSheds, |
| } |
| if trend != nil { |
| v, eta := trend.verdict(latest.At) |
| @@ -640,6 +650,46 @@ type alertReadings struct { |
| // rule reads the higher of it and the data disk's blocks. nil on any |
| // other box. |
| demoFill *diskReading |
| + // backhaulSheds is how many hops the edge's backhaul refused at a cap |
| + // since the last committed tick (backhaulShedWatch); nil leaves |
| + // backhaul_shed as it was. |
| + backhaulSheds *float64 |
| +} |
| + |
| +// backhaulShedWatch turns the edge's cumulative counters into the |
| +// backhaul_shed rule's per-tick reading. One for the life of the loop. |
| +type backhaulShedWatch struct { |
| + prev *metrics.BackhaulShedSample |
| + // carry is the largest reading of the ticks since the last one that |
| + // succeeded: what a failed publish still owes the rule. |
| + carry float64 |
| +} |
| + |
| +// tick gives run the refusals cur counts since the last tick (nil when cur |
| +// is nil: the edge is not ready, and the rule holds), or the carried |
| +// reading if that is larger. run is alertTick, which keeps its committed |
| +// state when the publish fails. A failed tick carries its reading, so a |
| +// firing transition that did not publish is evaluated again next tick with |
| +// the same count rather than lost to a quiet minute. The carry is a maximum |
| +// and never a sum: however long the store is down, the reading is never |
| +// more than one tick's count, so a trickle over an outage cannot add up to |
| +// a fire. A success clears it. |
| +func (w *backhaulShedWatch) tick(cur *metrics.BackhaulShedSample, run func(reading *float64) error) error { |
| + var reading *float64 |
| + if cur != nil { |
| + v := max(*metrics.BackhaulShedsSince(w.prev, cur), w.carry) |
| + reading = &v |
| + } |
| + err := run(reading) |
| + if cur != nil { |
| + w.prev = cur |
| + if err != nil { |
| + w.carry = *reading |
| + } else { |
| + w.carry = 0 |
| + } |
| + } |
| + return err |
| } |
| // verifyWatch reads the restore drill's local copy of this box's record |
| @@ -789,12 +839,13 @@ type unitSources struct { |
| func realSampleProbes(execRoot string, src unitSources, owners func() map[string]metrics.Vouch) sampleProbes { |
| return sampleProbes{ |
| - departures: sampleDepartures, |
| - procStat: readProcStat, |
| - loadavg: readLoadAvg, |
| - memFrac: readMemFrac, |
| - diskFrac: readDiskFrac, |
| - diskBytes: readDiskBytes, |
| + departures: sampleDepartures, |
| + backhaulSheds: sampleBackhaulSheds, |
| + procStat: readProcStat, |
| + loadavg: readLoadAvg, |
| + memFrac: readMemFrac, |
| + diskFrac: readDiskFrac, |
| + diskBytes: readDiskBytes, |
| units: func() map[string]unitRaw { |
| var stamped, nested []string |
| if src.stamped != nil { |
| @@ -1014,6 +1065,9 @@ func metricsLoop(execRoot string, src unitSources, owners func() map[string]metr |
| // alerted is what keeps a standing refusal from paging every minute. |
| // dataDir() is the bake dir the agent hands release.BakeDir. |
| var refusals refusalWatch |
| + // The backhaul's refusal counters are cumulative; the rule reads the |
| + // change from one tick to the next. |
| + var sheds backhaulShedWatch |
| // The restart watch is the one reading taken before the first sleep. It |
| // is loaded from the last run and sampled at once, so an agent that is |
| @@ -1061,7 +1115,18 @@ func metricsLoop(execRoot string, src unitSources, owners func() map[string]metr |
| sm.tick(probes) |
| latest := sm.buf[len(sm.buf)-1] |
| recordDiskPoint(&processDiskTrend, probes.diskBytes, latest.At) |
| - if err := alertTick(ctx, s, box, rules, &st, latest, restartTick(latest.At), statePath, sinks, &processDiskTrend, beat); err != nil { |
| + extra := restartTick(latest.At) |
| + // The counters straight from the edge, not the sample's copy, |
| + // which is nil while they are all zero: a quiet box must still |
| + // read zero, or a fire restored from disk would never clear. |
| + var shedCounts *metrics.BackhaulShedSample |
| + if c, ok := backhaulShedCounts(); ok { |
| + shedCounts = &c |
| + } |
| + if err := sheds.tick(shedCounts, func(reading *float64) error { |
| + extra.backhaulSheds = reading |
| + return alertTick(ctx, s, box, rules, &st, latest, extra, statePath, sinks, &processDiskTrend, beat) |
| + }); err != nil { |
| log.Printf("agent: alert tick: %v", err) |
| } |
diff --git a/internal/hostenv/hostenv.go b/internal/hostenv/hostenv.go| index ad540ef08..c2bcbee5d 100644 |
| --- a/internal/hostenv/hostenv.go |
| +++ b/internal/hostenv/hostenv.go |
| @@ -86,6 +86,7 @@ var Optional = []string{ |
| "CARLOS_ALERT_MEM_PCT", |
| "CARLOS_AWS_REGION", |
| "CARLOS_BACKHAUL_MAX_INFLIGHT", |
| + "CARLOS_BACKHAUL_MAX_STREAMS", |
| "CARLOS_CHANGE_INDEX", |
| "CARLOS_DEMO_API_CONSOLE_ORIGIN", |
| "CARLOS_DEMO_API_ORIGIN", |
diff --git a/internal/hostenv/hostenv_test.go b/internal/hostenv/hostenv_test.go| index 42715167f..24e8d49af 100644 |
| --- a/internal/hostenv/hostenv_test.go |
| +++ b/internal/hostenv/hostenv_test.go |
| @@ -875,3 +875,12 @@ func TestGenerationsSwitchHostEnv(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +// Both backhaul pool caps (#1535) may be delivered to a box's host.env. |
| +func TestBackhaulPoolCapsAllowed(t *testing.T) { |
| + for _, k := range []string{"CARLOS_BACKHAUL_MAX_INFLIGHT", "CARLOS_BACKHAUL_MAX_STREAMS"} { |
| + if !Allowed(k) { |
| + t.Errorf("%s is not allowed in host.env", k) |
| + } |
| + } |
| +} |
diff --git a/internal/metrics/alert.go b/internal/metrics/alert.go| index c9077f902..a9d672cf0 100644 |
| --- a/internal/metrics/alert.go |
| +++ b/internal/metrics/alert.go |
| @@ -33,6 +33,12 @@ type Rules struct { |
| // reporter's window before that unit's restarts rule fires. It is a |
| // count, not a fraction; see UnitRestarts for what clears it. |
| RestartCount float64 // fire >, default 3 |
| + // BackhaulShedCount is how many backhaul saturation refusals one tick |
| + // may count before backhaul_shed fires. A count, not a fraction. |
| + BackhaulShedCount float64 // fire >, default 10 |
| + // BackhaulShedQuiet is how long backhaul_shed must see no refusals |
| + // before it clears, so bursts on alternate minutes do not flap. |
| + BackhaulShedQuiet time.Duration // default 3 * time.Minute |
| } |
| // DefaultRules are the thresholds shipped with the platform. |
| @@ -51,6 +57,9 @@ func DefaultRules() Rules { |
| DiskETAHours: 72, |
| DiskETAHold: 2 * time.Hour, |
| RestartCount: 3, |
| + // backhaul_shed (#1535): fixed, like the restart count. |
| + BackhaulShedCount: 10, |
| + BackhaulShedQuiet: 3 * time.Minute, |
| } |
| } |
| @@ -128,6 +137,10 @@ type Observation struct { |
| // of its record (ReadVerify). nil is "no reading" and leaves every |
| // verify rule as it was. |
| Verify *VerifyReading |
| + // BackhaulSheds is how many hops the edge's backhaul refused since the |
| + // last tick (BackhaulShedsSince). nil is no reading and leaves the |
| + // backhaul_shed rule as it was. |
| + BackhaulSheds *float64 |
| } |
| // UnitRestarts is one unit's restart reading. |
| @@ -185,7 +198,7 @@ type AlertState struct { |
| V int `json:"v"` // 1 |
| Box string `json:"box"` |
| UpdatedAt time.Time `json:"updated_at"` |
| - Rules map[string]RuleState `json:"rules"` // "disk","mem","cpu","lag","geoip","disk_eta","engine_silent","verify_coverage"; "restarts@<unit>" per unit; "verify_failed@<host>", "verify_unverified@<host>" per host |
| + Rules map[string]RuleState `json:"rules"` // "disk","mem","cpu","lag","geoip","disk_eta","engine_silent","verify_coverage","backhaul_shed"; "restarts@<unit>" per unit; "verify_failed@<host>", "verify_unverified@<host>" per host |
| } |
| // Event is emitted on a firing or clearing transition — never on every |
| @@ -470,5 +483,28 @@ func Evaluate(r Rules, st AlertState, obs Observation) (AlertState, []Event) { |
| events = append(events, evalVerify(out.Rules, obs.Verify, obs.At, st.Box)...) |
| } |
| + // backhaul_shed: a count over the last tick, so no sustain. It fires |
| + // above BackhaulShedCount. While it is firing, Since is the last tick |
| + // that counted any refusal, and it clears once BackhaulShedQuiet has |
| + // passed since then with none (three one-minute ticks by default), so a |
| + // box still refusing a few, or refusing in bursts, keeps it up. |
| + if obs.BackhaulSheds != nil { |
| + val := *obs.BackhaulSheds |
| + cur := out.Rules[BackhaulShedRule] |
| + switch { |
| + case !cur.Firing && val > r.BackhaulShedCount: |
| + out.Rules[BackhaulShedRule] = RuleState{Firing: true, Since: obs.At, FiredAt: obs.At, Value: val} |
| + emit(BackhaulShedRule, true, val) |
| + case cur.Firing && val > 0: |
| + // Value stays the reading that fired, as every other rule's |
| + // does between transitions (RuleState.Value). |
| + cur.Since = obs.At |
| + out.Rules[BackhaulShedRule] = cur |
| + case cur.Firing && obs.At.Sub(cur.Since) >= r.BackhaulShedQuiet: |
| + out.Rules[BackhaulShedRule] = RuleState{} |
| + emit(BackhaulShedRule, false, 0) |
| + } |
| + } |
| + |
| return out, events |
| } |
diff --git a/internal/metrics/backhaul.go b/internal/metrics/backhaul.go| new file mode 100644 |
| index 000000000..729a0e4de |
| --- /dev/null |
| +++ b/internal/metrics/backhaul.go |
| @@ -0,0 +1,37 @@ |
| +package metrics |
| + |
| +// BackhaulShedRule is the box rule for forwarded requests the sending edge's |
| +// backhaul refused because a pool was at its cap (#1535): a request-pool or |
| +// stream-pool saturation, each a 503. Fair-share refusals (429s) are one |
| +// client being held to its share, not visitors at large being turned away, |
| +// so they are recorded in the sample but do not count toward the rule. Its |
| +// value is how many in the last tick. |
| +const BackhaulShedRule = "backhaul_shed" |
| + |
| +// BackhaulShedSample is the edge's refusal counters, cumulative since the |
| +// edge started (edge.BackhaulSheds), as a sample carries them. |
| +type BackhaulShedSample struct { |
| + Requests uint64 `json:"requests"` |
| + Streams uint64 `json:"streams"` |
| + FairShare uint64 `json:"fair_share"` |
| +} |
| + |
| +// saturated is the refusals the rule counts: both pools' saturation. |
| +func (s BackhaulShedSample) saturated() uint64 { return s.Requests + s.Streams } |
| + |
| +// BackhaulShedsSince is the backhaul_shed reading: how many saturation |
| +// refusals cur counts that prev did not. nil cur is no reading. nil prev |
| +// counts from zero, which is right because the edge's counters start at zero |
| +// in the same process as the reader. A count lower than prev's is a new |
| +// edge, counted from zero too. |
| +func BackhaulShedsSince(prev, cur *BackhaulShedSample) *float64 { |
| + if cur == nil { |
| + return nil |
| + } |
| + n := cur.saturated() |
| + if prev != nil && prev.saturated() <= n { |
| + n -= prev.saturated() |
| + } |
| + v := float64(n) |
| + return &v |
| +} |
diff --git a/internal/metrics/backhaul_test.go b/internal/metrics/backhaul_test.go| new file mode 100644 |
| index 000000000..f60602aa1 |
| --- /dev/null |
| +++ b/internal/metrics/backhaul_test.go |
| @@ -0,0 +1,94 @@ |
| +package metrics |
| + |
| +import ( |
| + "testing" |
| + "time" |
| +) |
| + |
| +// The backhaul_shed rule (#1535): fires when more than BackhaulShedCount |
| +// saturation refusals were counted in the last tick, holds while any are, |
| +// and clears after three quiet minutes. nil is no reading and leaves it |
| +// alone. |
| +func TestEvaluateBackhaulShed(t *testing.T) { |
| + r := DefaultRules() |
| + if r.BackhaulShedCount != 10 || r.BackhaulShedQuiet != 3*time.Minute { |
| + t.Fatalf("defaults %v, %v, want 10 and 3m", r.BackhaulShedCount, r.BackhaulShedQuiet) |
| + } |
| + st := AlertState{V: 1, Box: "box-a", Rules: map[string]RuleState{}} |
| + at := time.Date(2026, 12, 2, 12, 0, 0, 0, time.UTC) |
| + step := func(v *float64) []Event { |
| + t.Helper() |
| + at = at.Add(time.Minute) |
| + var evs []Event |
| + st, evs = Evaluate(r, st, Observation{At: at, BackhaulSheds: v}) |
| + return evs |
| + } |
| + f := func(v float64) *float64 { return &v } |
| + firing := func() bool { return st.Rules[BackhaulShedRule].Firing } |
| + |
| + if evs := step(f(10)); len(evs) != 0 || firing() { |
| + t.Fatalf("10 sheds (at the line) = %+v, want quiet", evs) |
| + } |
| + evs := step(f(11)) |
| + if len(evs) != 1 || evs[0].Rule != BackhaulShedRule || !evs[0].Firing || evs[0].Value != 11 || evs[0].Box != "box-a" { |
| + t.Fatalf("11 sheds = %+v, want one fire with value 11", evs) |
| + } |
| + if evs := step(nil); len(evs) != 0 || !firing() { |
| + t.Fatalf("nil while firing = %+v, want held", evs) |
| + } |
| + // Bursts on alternate minutes never clear it. |
| + for i, v := range []float64{5, 0, 0, 1, 0, 0, 30, 0, 0} { |
| + if evs := step(f(v)); len(evs) != 0 || !firing() { |
| + t.Fatalf("tick %d (%v sheds) while firing = %+v, want held: no three quiet minutes yet", i, v, evs) |
| + } |
| + } |
| + evs = step(f(0)) |
| + if len(evs) != 1 || evs[0].Firing || evs[0].Value != 0 { |
| + t.Fatalf("third quiet minute = %+v, want one clear", evs) |
| + } |
| + if rs, ok := st.Rules[BackhaulShedRule]; !ok || rs.Firing { |
| + t.Fatalf("cleared state = %+v (present %v), want a quiet entry", rs, ok) |
| + } |
| + if evs := step(f(0)); len(evs) != 0 { |
| + t.Fatalf("0 sheds while quiet = %+v, want nothing", evs) |
| + } |
| + // A nil tick inside the quiet run neither clears nor resets it. |
| + step(f(20)) |
| + step(f(0)) |
| + step(nil) |
| + if evs := step(f(0)); len(evs) != 1 || evs[0].Firing { |
| + t.Fatalf("three minutes after the last shed, across a nil tick = %+v, want the clear", evs) |
| + } |
| +} |
| + |
| +func TestBackhaulShedsSince(t *testing.T) { |
| + s := func(req, str, fair uint64) *BackhaulShedSample { |
| + return &BackhaulShedSample{Requests: req, Streams: str, FairShare: fair} |
| + } |
| + for _, tc := range []struct { |
| + name string |
| + prev, cur *BackhaulShedSample |
| + want *float64 |
| + }{ |
| + {"no reading", s(1, 1, 1), nil, nil}, |
| + {"first reading counts from the edge's start", nil, s(2, 3, 4), ptr(5)}, |
| + {"delta", s(2, 3, 4), s(5, 4, 10), ptr(4)}, |
| + {"fair-share refusals do not count", s(2, 3, 4), s(2, 3, 90), ptr(0)}, |
| + {"none", s(2, 3, 4), s(2, 3, 4), ptr(0)}, |
| + {"a counter went back: a new edge, counted from zero", s(50, 0, 0), s(3, 1, 7), ptr(4)}, |
| + } { |
| + got := BackhaulShedsSince(tc.prev, tc.cur) |
| + if (got == nil) != (tc.want == nil) || (got != nil && *got != *tc.want) { |
| + t.Errorf("%s: got %v, want %v", tc.name, deref(got), deref(tc.want)) |
| + } |
| + } |
| +} |
| + |
| +func ptr(v float64) *float64 { return &v } |
| + |
| +func deref(p *float64) any { |
| + if p == nil { |
| + return nil |
| + } |
| + return *p |
| +} |
diff --git a/internal/metrics/sample.go b/internal/metrics/sample.go| index a2ac8f816..edf6b320f 100644 |
| --- a/internal/metrics/sample.go |
| +++ b/internal/metrics/sample.go |
| @@ -36,10 +36,14 @@ type UnitSample struct { |
| // (e.g. carlos-exec@x.example.com — no .service suffix; written by the |
| // sampler's exec-subtree scan since exec-child accounting). |
| type Sample struct { |
| - HADepartures *DepartureSample `json:"ha_departures,omitempty"` |
| - At time.Time `json:"at"` |
| - Host HostSample `json:"host"` |
| - Units map[string]UnitSample `json:"units"` |
| + HADepartures *DepartureSample `json:"ha_departures,omitempty"` |
| + // BackhaulSheds is the edge's backhaul refusal counters (#1535), nil |
| + // before the edge is ready. Omitted when nil, so older chunks read the |
| + // same. |
| + BackhaulSheds *BackhaulShedSample `json:"backhaul_sheds,omitempty"` |
| + At time.Time `json:"at"` |
| + Host HostSample `json:"host"` |
| + Units map[string]UnitSample `json:"units"` |
| } |
| // RawChunk is an hour's worth of raw samples for one box, the unit of |
diff --git a/internal/provision/testdata/plan14-root-reads-backhaul-streams-1535.tsv b/internal/provision/testdata/plan14-root-reads-backhaul-streams-1535.tsv| new file mode 100644 |
| index 000000000..63eb205ec |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-backhaul-streams-1535.tsv |
| @@ -0,0 +1,12 @@ |
| +# Census overlay backhaul-streams-1535, written by census-propose (#369). census-ruling-backhaul-streams-1535, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-backhaul-streams-1535.md. |
| +# 3 body, 0 sites, 5 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@legacy 0bf4a8bb04b4e96b9c8da8f88005dd03f19c550f28212b5852ace32bd21fcd3c internal/edge/edge.go RunWithActivatorReady legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-certwarm-wake;basis=registers the cert warm's nudge on OnReload and on the home map's new served-hosts wake (#386); nudge only sends on a buffered channel; no read added, same 5 sites;rev3=census-ruling-edge-roll-blip;basis=the :80/:443 (and dev) listeners are bound on the calling goroutine with net.Listen via listen()/listenAddr (same empty-address defaults as ListenAndServe) before the serve goroutines, which now call Serve/ServeTLS on them, and one log line names the bound addresses; no read added, same 5 sites;rev3=census-ruling-edge-held-streams;basis=the edge in the agent (carlos-edge.service, user carlos): the inline home-map arming (newHomeMap, one boot Refresh, Store, run) moves unchanged into the new Edge.ArmHomeMap and is called here as e.ArmHomeMap(); same refresh, same timeout, same order. The reads are moved, none added.;rev3=census-ruling-agent-start-demo-1;basis=Logs the combined explicit wildcard parents through demoWildcardDomains; no new watcher or read loop.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: invoke the local admission Close before HTTP/HTTPS draining and door shutdown in both dev and normal listeners. Preserve merged main's startup behavior and its census basis; the same five read sites, no new reads.;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: defer stopping and joining the edge's replica jobs at shutdown. Existing five direct read sites unchanged; no new reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Wrap dev, HTTP and HTTPS listeners through ConfigureGroupHairpin before serving. Indirectly read protected root boot identity and group-ingress.json; kernel local/peer addresses mark local ingress, never HTTP headers. Agent edge uses verified public source for accounting; direct read sites unchanged and absent marker keeps original listeners. CI fix removes interface enumeration: local peer must match snapshot primary IPv4, an ingress IPv4 installed locally by root, or loopback; kernel destination must still be an ingress EIP on port 80/443. Merge 45cebde4 retains deferred stopReplicaProbes alongside group listener wrapping and shutdown admission closure.;rev3=census-ruling-demo-api-site-route;basis=Change the startup failure context from load routes to initialize because origin validation now runs during construction. Existing five read sites unchanged; no new read or runtime authority.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Invoke the agent shutdown timestamp hook synchronously at SIGTERM/SIGINT receipt before closing admission in dev and TLS paths. No read added.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 5: registers the https and http servers with the connection drain (conns.serve) so a drain can close idle keep-alive connections; no read added;rev3=census-ruling-warm-set-published-724;basis=#724: the inline cert warm construction (newCertWarm over warmSet and dnsGate, then OnReload and setServedWake registering warm.nudge) moves unchanged into the new Edge.newIssuerWarm in certwarm.go and is called here with the same apps domain, parents, perHostCert, warmResolver, edgeIPs and store; the loop still starts here. The warm set it wires now reads the published edges files through the home map (OwnServedHosts and ServedHosts, both already polled) instead of the local route table, regional names aside. It is a different source, not a subset: an attached name not yet published as pointing is no longer listed, while a name the route table has already dropped stays listed until this box's next edges file write and the home map's next poll catch up (HostPolicy still refuses an order for a name the registry no longer holds). A name published not pointing is not a warm candidate at all, whether or not its certificate is cached: the warm neither looks it up, orders it nor re-arms its renewal until its home box publishes it pointing again (a cached certificate keeps serving and re-arms on a handshake at the issuer). The warm reads the set only after the issuer gate, and the read is in memory (route table and the home map's last snapshot); it also drops a DNS-miss entry for a name that has left the set before probing it. It keeps a failure record while any box publishes the exact name (the home map DeployedHosts: every box's file, own included, pointing or not, the same in-memory snapshot) or the name is a regional route-table name, and prunes it only once no box publishes it. That retention set has no apps-domain or wildcard filter (those stay on candidacy only), so a name published not pointing, or one a wildcard parent starts covering, keeps the record that explains its backoff; the set is never a source of candidates. No read site added in this unit, same 5 sites.;rev3=census-ruling-w6-ingress-drain;basis=the two public servers are built by e.publicServers (internal/edge/ingressdrain.go): :443 as before (same handler, TLS config and ReadHeaderTimeout 10 s), :80 now wrapped by plainTracked so the ingress drain can count and close its requests (its barrier is never §25's); Serve's error test is listenerFailed(err) = err != nil && !errors.Is(err, http.ErrServerClosed) (was err != ErrServerClosed), so a graceful Shutdown by the drain is not fatal. New Edge.plain connDrain field. Same flags, addresses and listeners; read sites unchanged (5); no read added.;rev3=census-ruling-edge-ppv2;basis=Edge process (uid carlos), not root. Edge gains the proxy atomic.Pointer. Outside dev mode, before either public listener binds and before the ready hook hands the Edge to the agent, calls e.loadProxyIngress(os.Getenv, dataDir): CARLOS_INGRESS_PROXY_SOURCES from the edge's own environment (carlos-edge.service loads the root-owned 0600 host.env) through hostenv.ParseProxySources; blank leaves the edge unarmed with nothing read; a non-empty list arms it and Lstats <dataDir>/edge/trust-barrier (armProxyIngress); a value that does not parse is log.Fatal. After the hairpin configuration, wrapProxyIngress wraps both public listeners outermost (returns them untouched when unarmed); when armed it logs the armed line and starts runProxyJournal (counters to the journal, no reads). The existing 5 read sites are unchanged.;rev3=census-ruling-audit-request-path;basis=the dev-mode http.Server gains IdleTimeout: publicIdleTimeout (120 s) beside its ReadHeaderTimeout; comment updated. Same 5 read sites, no read added.;rev3=census-ruling-precert-dns01-1293;basis=the edge process (carlos-edge.service, user carlos), not root: after the cert warm starts, calls e.newPreIssuerFromEnv(certCache, mirror, wm) and, when it returns non-nil, starts its loop and logs one line. newPreIssuerFromEnv (precert.go) reads CARLOS_DNS01_ZONES and CARLOS_DNS01_ACCOUNTS from the edge environment (the root-owned host.env); either unset or invalid = nil, nothing else read. Only claims of the named accounts qualify. Armed, the loop runs only while this box holds the issuer gate: it lists domains/ claims in the deployment bucket through a ClaimCache, and for proven claims under the listed zones orders a certificate over DNS-01 through the existing DNS provider seam (dnsProviderFromEnv, same IAM-scoped _acme-challenge TXT writes the wildcard manager already makes), writing the result through the existing publishing cache (local acme dir + control/certs/<host>). No root read; the existing 5 read sites are unchanged.;rev3=census-ruling-alias-publish-precert-1293;basis=the edge process (carlos-edge.service, user carlos), not root: the pre-issuer start log now reads its zones from p.scope.Zones (the zones and accounts moved into the shared edge.DNS01Scope); no behaviour change, no read added, the existing 5 read sites unchanged.;rev3=census-ruling-cert-import-1429;basis=#1429: the edge process (carlos-edge.service, user carlos), not root: inserts mirror.wrapImported between perHostCert's capture and the wildcard wrap (a handshake for a name with a usable imported certificate in the mirror's memory, for a deployment host, returns chooseCert's answer over the wildcard covering the name, the <host> and <host>+rsa entries and the import: a supported CARLOS certificate first, else the import; every other name unchanged); the wildcard wrap becomes wrapGetCertificateImports, which passes exactly those imported names down instead of answering with the wildcard (in-memory predicates only: deploymentHost and the mirror snapshot); and starts the issuer-only import reconcile beside the pre-issuer (a ClaimCache.ListWithUnread prefilter rotated by a cursor across passes, then domains.ReconcileImport per host: entry revision, then claim, then DeleteIfMatch on control/certs/<host>+import only, at most 5 a pass, nothing on a failed listing). No root read; the existing 5 read sites unchanged.;rev3=census-ruling-sec-h5-edge-availability;basis=hunt H5-M5: the dev-mode server gains IdleTimeout publicIdleTimeout (120 s) beside its ReadHeaderTimeout (main since added the same value; merged, comments only); same listener, handler and addresses. No read added, same 5 sites.;rev3=census-ruling-backhaul-streams-1535;basis=#1535: the edge process (carlos-edge.service, user carlos), not root: also reads CARLOS_BACKHAUL_MAX_STREAMS from the edge's own environment (root-owned host.env) through backhaulCapFromEnv (unset, unparseable or <= 0 means the default 128) into backhaulMaxStreams beside the existing CARLOS_BACKHAUL_MAX_INFLIGHT read (default unchanged, 64). Numbers only; no file, path or bucket read added; the existing 5 read sites unchanged. data-literal@129,data-literal@148,data-literal@284,data-literal@417,file:Open@1013 978f27e97e05d54b748d0255de28af3316366c5bdf9b8dbdd91991daf0767cca |
| +@legacy cc2fab3ec92a5b560ae5eed06793ca8fa134ff818aa04649c13b227215193c07 internal/host/metrics_loop.go sampler.tick legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-remote-instance-metrics;basis=calls the owners probe before and after the unit read and tags readings with metrics.TagUnits and metrics.CarryTags; no read added;rev3=census-ruling-remote-metrics-nested;basis=clears the tenant tag of a reading marked leftover (a nested unit present at agent start) before CarryTags, and takes no CPU delta when a nested reading's set of cgroups changed since the previous tick; no read added;rev3=census-ruling-region-ha-p1b3b-t;basis=B5: Add one optional aggregate departure sample to the existing buffered sample; no per-host labels or separate writer.;rev3=census-ruling-backhaul-streams-1535;basis=#1535: the agent's metrics sampler adds the in-memory backhaul shed counters (sampleBackhaulSheds, from backhaulShedSource; nil before the edge is ready and while every counter is zero) to each sample as backhaul_sheds; the samples go to the existing raw-chunk flush; no read added, same 1 read site. file:ReadBytes@1093 5bcc277c64eaab72e3a6d4a7621acd205e10b07b41bc138dc0db7d7da3e730ec |
| +internal/edge/edge.go RunWithActivatorReady legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-certwarm-wake;basis=registers the cert warm's nudge on OnReload and on the home map's new served-hosts wake (#386); nudge only sends on a buffered channel; no read added, same 5 sites;rev3=census-ruling-edge-roll-blip;basis=the :80/:443 (and dev) listeners are bound on the calling goroutine with net.Listen via listen()/listenAddr (same empty-address defaults as ListenAndServe) before the serve goroutines, which now call Serve/ServeTLS on them, and one log line names the bound addresses; no read added, same 5 sites;rev3=census-ruling-edge-held-streams;basis=the edge in the agent (carlos-edge.service, user carlos): the inline home-map arming (newHomeMap, one boot Refresh, Store, run) moves unchanged into the new Edge.ArmHomeMap and is called here as e.ArmHomeMap(); same refresh, same timeout, same order. The reads are moved, none added.;rev3=census-ruling-agent-start-demo-1;basis=Logs the combined explicit wildcard parents through demoWildcardDomains; no new watcher or read loop.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: invoke the local admission Close before HTTP/HTTPS draining and door shutdown in both dev and normal listeners. Preserve merged main's startup behavior and its census basis; the same five read sites, no new reads.;rev3=census-ruling-stateless-replicas-3;basis=Task 1b: defer stopping and joining the edge's replica jobs at shutdown. Existing five direct read sites unchanged; no new reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Wrap dev, HTTP and HTTPS listeners through ConfigureGroupHairpin before serving. Indirectly read protected root boot identity and group-ingress.json; kernel local/peer addresses mark local ingress, never HTTP headers. Agent edge uses verified public source for accounting; direct read sites unchanged and absent marker keeps original listeners. CI fix removes interface enumeration: local peer must match snapshot primary IPv4, an ingress IPv4 installed locally by root, or loopback; kernel destination must still be an ingress EIP on port 80/443. Merge 45cebde4 retains deferred stopReplicaProbes alongside group listener wrapping and shutdown admission closure.;rev3=census-ruling-demo-api-site-route;basis=Change the startup failure context from load routes to initialize because origin validation now runs during construction. Existing five read sites unchanged; no new read or runtime authority.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Invoke the agent shutdown timestamp hook synchronously at SIGTERM/SIGINT receipt before closing admission in dev and TLS paths. No read added.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 5: registers the https and http servers with the connection drain (conns.serve) so a drain can close idle keep-alive connections; no read added;rev3=census-ruling-warm-set-published-724;basis=#724: the inline cert warm construction (newCertWarm over warmSet and dnsGate, then OnReload and setServedWake registering warm.nudge) moves unchanged into the new Edge.newIssuerWarm in certwarm.go and is called here with the same apps domain, parents, perHostCert, warmResolver, edgeIPs and store; the loop still starts here. The warm set it wires now reads the published edges files through the home map (OwnServedHosts and ServedHosts, both already polled) instead of the local route table, regional names aside. It is a different source, not a subset: an attached name not yet published as pointing is no longer listed, while a name the route table has already dropped stays listed until this box's next edges file write and the home map's next poll catch up (HostPolicy still refuses an order for a name the registry no longer holds). A name published not pointing is not a warm candidate at all, whether or not its certificate is cached: the warm neither looks it up, orders it nor re-arms its renewal until its home box publishes it pointing again (a cached certificate keeps serving and re-arms on a handshake at the issuer). The warm reads the set only after the issuer gate, and the read is in memory (route table and the home map's last snapshot); it also drops a DNS-miss entry for a name that has left the set before probing it. It keeps a failure record while any box publishes the exact name (the home map DeployedHosts: every box's file, own included, pointing or not, the same in-memory snapshot) or the name is a regional route-table name, and prunes it only once no box publishes it. That retention set has no apps-domain or wildcard filter (those stay on candidacy only), so a name published not pointing, or one a wildcard parent starts covering, keeps the record that explains its backoff; the set is never a source of candidates. No read site added in this unit, same 5 sites.;rev3=census-ruling-w6-ingress-drain;basis=the two public servers are built by e.publicServers (internal/edge/ingressdrain.go): :443 as before (same handler, TLS config and ReadHeaderTimeout 10 s), :80 now wrapped by plainTracked so the ingress drain can count and close its requests (its barrier is never §25's); Serve's error test is listenerFailed(err) = err != nil && !errors.Is(err, http.ErrServerClosed) (was err != ErrServerClosed), so a graceful Shutdown by the drain is not fatal. New Edge.plain connDrain field. Same flags, addresses and listeners; read sites unchanged (5); no read added.;rev3=census-ruling-edge-ppv2;basis=Edge process (uid carlos), not root. Edge gains the proxy atomic.Pointer. Outside dev mode, before either public listener binds and before the ready hook hands the Edge to the agent, calls e.loadProxyIngress(os.Getenv, dataDir): CARLOS_INGRESS_PROXY_SOURCES from the edge's own environment (carlos-edge.service loads the root-owned 0600 host.env) through hostenv.ParseProxySources; blank leaves the edge unarmed with nothing read; a non-empty list arms it and Lstats <dataDir>/edge/trust-barrier (armProxyIngress); a value that does not parse is log.Fatal. After the hairpin configuration, wrapProxyIngress wraps both public listeners outermost (returns them untouched when unarmed); when armed it logs the armed line and starts runProxyJournal (counters to the journal, no reads). The existing 5 read sites are unchanged.;rev3=census-ruling-audit-request-path;basis=the dev-mode http.Server gains IdleTimeout: publicIdleTimeout (120 s) beside its ReadHeaderTimeout; comment updated. Same 5 read sites, no read added.;rev3=census-ruling-precert-dns01-1293;basis=the edge process (carlos-edge.service, user carlos), not root: after the cert warm starts, calls e.newPreIssuerFromEnv(certCache, mirror, wm) and, when it returns non-nil, starts its loop and logs one line. newPreIssuerFromEnv (precert.go) reads CARLOS_DNS01_ZONES and CARLOS_DNS01_ACCOUNTS from the edge environment (the root-owned host.env); either unset or invalid = nil, nothing else read. Only claims of the named accounts qualify. Armed, the loop runs only while this box holds the issuer gate: it lists domains/ claims in the deployment bucket through a ClaimCache, and for proven claims under the listed zones orders a certificate over DNS-01 through the existing DNS provider seam (dnsProviderFromEnv, same IAM-scoped _acme-challenge TXT writes the wildcard manager already makes), writing the result through the existing publishing cache (local acme dir + control/certs/<host>). No root read; the existing 5 read sites are unchanged.;rev3=census-ruling-alias-publish-precert-1293;basis=the edge process (carlos-edge.service, user carlos), not root: the pre-issuer start log now reads its zones from p.scope.Zones (the zones and accounts moved into the shared edge.DNS01Scope); no behaviour change, no read added, the existing 5 read sites unchanged.;rev3=census-ruling-cert-import-1429;basis=#1429: the edge process (carlos-edge.service, user carlos), not root: inserts mirror.wrapImported between perHostCert's capture and the wildcard wrap (a handshake for a name with a usable imported certificate in the mirror's memory, for a deployment host, returns chooseCert's answer over the wildcard covering the name, the <host> and <host>+rsa entries and the import: a supported CARLOS certificate first, else the import; every other name unchanged); the wildcard wrap becomes wrapGetCertificateImports, which passes exactly those imported names down instead of answering with the wildcard (in-memory predicates only: deploymentHost and the mirror snapshot); and starts the issuer-only import reconcile beside the pre-issuer (a ClaimCache.ListWithUnread prefilter rotated by a cursor across passes, then domains.ReconcileImport per host: entry revision, then claim, then DeleteIfMatch on control/certs/<host>+import only, at most 5 a pass, nothing on a failed listing). No root read; the existing 5 read sites unchanged.;rev3=census-ruling-sec-h5-edge-availability;basis=hunt H5-M5: the dev-mode server gains IdleTimeout publicIdleTimeout (120 s) beside its ReadHeaderTimeout (main since added the same value; merged, comments only); same listener, handler and addresses. No read added, same 5 sites.;rev3=census-ruling-backhaul-streams-1535;basis=#1535: the edge process (carlos-edge.service, user carlos), not root: also reads CARLOS_BACKHAUL_MAX_STREAMS from the edge's own environment (root-owned host.env) through backhaulCapFromEnv (unset, unparseable or <= 0 means the default 128) into backhaulMaxStreams beside the existing CARLOS_BACKHAUL_MAX_INFLIGHT read (default unchanged, 64). Numbers only; no file, path or bucket read added; the existing 5 read sites unchanged. data-literal@129,data-literal@148,data-literal@284,data-literal@417,file:Open@1013 978f27e97e05d54b748d0255de28af3316366c5bdf9b8dbdd91991daf0767cca |
| +internal/host/agent.go runAgent authority B,C,D,F rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 7: the startup Sweep literal hands its answer to startupSwept, which logs as before and, only on a clean sweep, marks rootfs admission swept (MarkRootfsSwept); same Sweep call, no read added;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): sets svc.Fleet = fleetWakeFor(os.Getenv, identity, identErr, fleetStore) from the identity it already resolves once and the deployment store the fleet loops already opened, and logs an ERROR naming the identity error when the box is on a fleet with an invalid identity. fleetWakeFor reads CARLOS_REGION and CARLOS_FLEET from the same environment. Read sites unchanged (6). Agent, not root; a platform box is unchanged.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: one call more beside armRunsPass, armInteractivePass(svc, reg, rolloutSink, boxJudge), in the same activator Configure hook, handing it the same box judge; fix round 1 (Astra P2, shutdown): after svc.Shutdown(ctx), shutdownInteractive(ctx) ends and joins every interactive session under the same shutdown budget; the worker's own reads are its units' (interactive.go); this body reads nothing new, the same six sites; merge of origin/main 6f1f6ca6: main's svc.Fleet = fleetWakeFor(...) and its invalid-identity ERROR line are kept as main has them (census-ruling-managed-fleets-1b); this branch's change is the same as above; read sites unchanged (6);rev3=census-ruling-fix-set-aside-exdev;basis=set-aside EXDEV fix: one field more on the agent ExecBackend literal, RawInstanceDir: layout.RawInstanceDir (a pure path join: <dataDir>/.instances/<InstanceID(host)>), so the start rule set-aside moves a copy out through the raw directory instead of through the nosymfollow bind; this body reads nothing new, the same six sites;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: one more assignment beside eb.FilesStore: eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), the agent's own environment parsed by appconfig.ParsePrivateKey as the moves pass parses it (unset or unparseable: a log line and nil, and HA publication refuses on the box). No path is opened or read, no read site added; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 4: one more goroutine beside configSyncLoop: go escrowLoop(agentCtx, reg, svc), the escrow sweep every 30 s over the same registry and Service. This body reads nothing new itself; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 5: one more call beside eb.EscrowKey: wireRawSecretPages(eb, PageOperator, metricsBoxLabel(os.Getenv, readMachineID())), which sets eb.OnRawSecret to page an operator (alerting.Page through PageOperator, LevelIncident) on its own goroutine with a 20 s timeout; metricsBoxLabel and readMachineID are the reads this body already makes for the moves refusal log; no new read site; the same six sites, offsets moved; B,C,D,F authority retained. Merge of origin/main 90c4d3aa: main's own later changes to this body are kept as main has them, under main's rulings; this branch's change is the same as above. Merge of origin/main 00bf5b8c (fleet set-aside EXDEV fix): main's change to this body is kept as main has it, under its own census ruling; this branch's change is unchanged.;rev3=census-ruling-probe-burst-limit;basis=two more sink wirings beside setAnalyticsSink: setProtectionSink(e.SetProtectionRecordOnly) and setAssetOwnersSource(e.AssetOwners), function values the telemetry pass calls; this body reads nothing new, the same six sites; authority B,C,D,F retained; no new root read or write kind;rev3=census-ruling-region-ha-p1b3a;basis=Arm HA placement exactly once on the existing Service before activatorStart and edges publication, wiring AwakeApps and the PageOperator callback; existing six read sites unchanged, no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Final review I3: start the concrete coordinator's renewal worker with agent setup; existing closeReplicaCoordinator shutdown cancels and joins it before release. No new read sites or credentials. Merge origin/main c59715e7: retain main's armHAPlacement(svc, PageOperator) wiring beside the existing activator setup; stateless coordinator and shutdown wiring remain. Same read sites; no new root read or credential.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): in the edge-ready callback, calls act.SetHeldWakeHook(e.HeldWake) when act is non-nil (installing the non-blocking wake callback) and stores e.HeldStreamsForStatus in heldStreamsSource. Wiring of in-memory callbacks only; no read added.;rev3=census-ruling-region-ha-p1b3b-t;basis=Wire Service.SetDutyView to the live edge DutySnapshot in the ready callback. No new read; no new loop or cloud operation. B2 wires the registry as the persistent DutyStore before service startup; no new cloud or filesystem path. B3b: arm one journal-backed termination consumer before service startup using agentCtx and the shared confirmer; expose edge tick and join at edge shutdown. No new direct read sites.;rev3=census-ruling-agent-start-demo-1;basis=Passes the existing registry, data store and hibernation prefix into the demo worker, and the existing instance-control client into the demo before-exec hook. No alternate data store or polling loop. Merge resolution against origin/main 9bd45488 retains main's HA departure controller, lifecycle and duty wiring alongside the demo data store and worker; no read site added by the resolution.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: install closed fixed admission before every launch source, bind activator/backend and edge, wire the real termination Started lifecycle and role reader after the change index; close before cancellation/child shutdown. No new external reads or cloud authority. Fix R1: move bind/lifecycle/edge-option wiring into wireAgentAdmission and worker listing into runWorkerBootPassAfterAdmission. Worker boot waits for admission before listing then uses unchanged bounded wakes and per-host serialization; whole Route read moves to the helper. No new storage, cloud, or root execution authority. Preserve merged main's agent wiring and census basis; the branch removes one whole Route use by moving worker iteration to the helper, with no added read kind.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: arms a fleet-only worker using the existing registry, activator, backend and authenticated console transport. Owned worker stops and joins at shutdown. No new bucket reader. merge of origin/main 9b8b2c50: retain HA duty/departure lifecycle, wake-slot and existing agent wiring alongside the replica placement worker; no new read introduced by resolution. merge of origin/main 6be08467: Retain main demo configuration, admission, build and expiry wiring alongside the replica worker; merge-only body change, no additional read. merge of origin/main 7920cccf: Retain main box-role/group admission wiring and boot publication beside the owned replica worker and shutdown; main moves the boot registry List into runWorkerBootPassAfterAdmission, removing its inline whole Route site. No new read introduced by conflict resolution.;rev3=census-ruling-stateless-replicas-3;basis=Task 1 fix round 1 M3: retain the private snapshot source and cancel/join ownership, but use the replica-health-specific retry loop. It logs its first failure only and retains the existing exponential backoff capped at 30 seconds; unsupported builds return nil. Existing five direct read sites unchanged; no new credentials, bucket reader or app lifecycle action. Fix round 1 Q20: publish Edge.ReplicaSnapshots as a separate in-memory status source, leaving the tenant-visible Upstreams source unchanged. No new external reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Load root-written group marker/configuration, configure signed boot binding and agent receipt completer, wire cancellable admission into departure work and expose cached GroupReaderSnapshot. New indirect boot reads use protected root files; agent-owned receipt controls duplicate initial completion only, never root restart permission. Same five direct sites. Merge 45cebde4 retains the replica health socket lifecycle and setReplicaSource beside GroupReaderSnapshot; no extra read beyond main.;rev3=census-ruling-agent-start-demo-2;basis=agent.go:309-329 opens demo-traffic.db beside the operator-configured registry when a demo domain exists, closes it at shutdown and wires drain-before-purge; :1010-1019 shares the worker and write gate; :1164-1177 installs the fleet identity and closed-until-worker serving callback. One added whole Route pass; the new indirect filesystem/SQL reads are claimed in openDemoTraffic and worker/store units. No request chooses the database pathname.;rev3=census-ruling-region-ha-p1b3b-s;basis=Wire the service duty view to authoritative cached sidecar manifest placement in LifetimeIndex and the edge sidecar projection; missing policy denies duty. Existing instance duty wiring remains.;rev3=census-ruling-region-ha-g2-t3;basis=T3a: wire eb.Page = PageOperator beside OwnerTerminated before departures arm, so suspect-holder pages work if departure setup fails; no new read; existing nine sites and authority unchanged; pages through the existing sink. T3b: publish the same backend through an atomic pointer for the metrics observer, and clear it on return; no new external read or authority.;rev3=census-ruling-agent-start-demo-3;basis=Wire the claim activator and root snapshot client into the demo worker; pass moved readiness to status reporting. Census read-site delta: unchanged (9).;rev3=census-ruling-region-ha-g2-fixes;basis=Wire local pool evidence, live withdrawal activator, startup ingress scan and alias publication, and edge lookup; no new direct sites; new indirect record/claim reads use existing store/judge paths described in ingress helpers.;rev3=census-ruling-region-ha-g2r-fixes;basis=W3: starts the existing record-view backstop loop with a departure-inventory listener (non-blocking, coalesced signal) even without an armed RecordView; it requests the existing full pass (backstopFullDue) there. Same nine read sites; no new read or authority.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Derive one signal-time deadline with a 90-second budget; cap departure stop and startup/seed/service shutdown joins by it. No read added.;rev3=census-ruling-static-sweep-periodic;basis=in the edge-ready callback, publishes e.LargestStaticTree in staticTreeSource for the disk alert line (diskAlertFrac in the metrics loop); in-memory wiring only, no read added; read sites unchanged (9);rev3=census-ruling-edge-page-cache-1;basis=wires the exec backend's CurrentInputs into the edge cache (wireCurrentInputs) and, in the ready hook after armEdgeAssetCache (whose returned store it now keeps), calls armEdgePageCache, which does nothing unless CARLOS_PAGE_CACHE=1; read sites unchanged (9); no read added;rev3=census-ruling-gvisor-demos;basis=Capture sandbox resolution and refusal once; log errors once; gate route admission and BeforeExec before process launch. No new root read. Task 5: pass the once-captured sandbox effective mode/config error into ExecBackend, UnitBackend and the immutable Client expectation. Same startup environment/registry reads; swapArming declines gVisor before placement. Task 8: arm read-only status projection with the existing Client.SandboxStatus callback. Agent status now queries the existing root /ready endpoint; no new root authority or guest-file input. Merge2 e8a1ddde: retain main wireCurrentInputs and armEdgePageCache through the existing asset-store ready hook alongside branch once-captured sandbox mode, wake gates and root status wiring. No new direct read; main page-cache helpers retain their own census overlays.;rev3=census-ruling-region-ha-held-build;basis=wires the drain state: svc.SetDrainingSource(boxDrain.IsDraining), svc.SetPeerDrainView(e.PeerDraining), e.SetPeerDrainedHook(svc.DropHoldersNaming); in-memory only; no read added; region HA held-requests Task 5: on group members, starts the drain driver over the activator, the edge and boxDrain, and serves its root-only drain socket; no read added beyond the socket's own Branch review r1: the drain state follows the root start fence on group members (the fence reader is the existing fenceLocation.read, a root-owned fixed path); e.SetPeerUndrainedHook(svc.AllowHoldersNaming) beside the drained hook (memory only); the drain socket serves only the agent's own user. No read added.;rev3=census-ruling-security-review-mitigations;basis=Wire the cached operator flat-layout choice into the exec backend's new-resident refusal; no read source added, existing authority retained.;rev3=census-ruling-w6-ingress-drain;basis=agent (user carlos), not root. Builds the ingress drain (newIngressDrain) with arming read at ask time from os.Getenv (CARLOS_REGION_HA, CARLOS_INGRESS_TARGET_GROUPS, both from the root-owned host.env), the fixed admission and lease.CurrentSelf (existing IMDS identity); its reader is awstg.Load, the box role's credentials calling ELB DescribeTargetHealth/DescribeTargetGroupAttributes (new AWS reads, by the agent). Wires admission.closeStartsForIngressDrain, the lbhealth drain condition, ingress.setEdge, and ingress.shutdownStarted in WithShutdownStarted. The drain socket (/run/carlos/.ha-drain/drain.sock, agent-user only, existing) is now also served on a fixed box with the drain configured (was group members only), routing /v1/ingress/* to the ingress drain and the group drain verbs to 404 there. armHADepartures now takes fixtureDepartureGetenv() and MakeQueue fixtureDepartureQueue(), which in a production (non-rootrunner) build are os.Getenv and nil, as before. Read sites unchanged (9).;rev3=census-ruling-stateless-replicas-4-task1;basis=Arms the fleet-only replica swap worker next to the placement worker: same console URL and fleet token as the existing replicaCoordinatorAPI, the existing activator Service; stops and joins at shutdown. No new read site, credential or bucket reader.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: sets deployWorker.step to the rollout scheduler answer for the record permit (replicaStepOf over armedRollout), an in-memory callback; no read site, credential or bucket reader added.;rev3=census-ruling-stateless-replicas-4-task2-fix2;basis=Task 2 fix round 2: the swap worker step is armedReplicaStep, the same lazy scheduler lookup as before as a named function; no read site added.;rev3=census-ruling-stateless-replicas-4-merge-main;basis=Merge of main 5fac2ff1: both sides changed it. Main (01d6ca78, linked-deployments-slice1) starts linkLoop beside tunnelLoop; this branch keeps its replica coordinator wiring. Both kept as-is; no read added.;rev3=census-ruling-stateless-replicas-4-final;basis=#511 final wave item 2: wires the swap worker's drive (armedReplicaDrive, the armed rollout manager's DriveReplicaRelease); no read added;rev3=census-ruling-stateless-replicas-4-merge-main2;basis=Merge of main af871da0 (v0.34.49): both sides changed it. Main (178dcfe5, member-backups-2a) moves the inline duty-view closure into armDutyView/dutyView and starts verifyAssignLoop; its sites drop by registry:Host and whole:Route x2 as main recorded them. This branch keeps its replica coordinator, swap worker and drive wiring. Both kept as-is; no read added.;rev3=census-ruling-stateless-replicas-4-drill3;basis=drill 3 R24: makes one in-memory channel, closes it (once) inside the edge's existing shutdown-started callback after ingress.shutdownStarted, and passes it to tunnelLoop, which drains only a fleet channel name; no read added, same six sites; touches no admission, lease, ingress drain, listener or file; the agent process, no root decision;rev3=census-ruling-edge-ppv2;basis=Agent (uid carlos), not root. memwatchLoop now gets edgeProxyCounters(&demoEdge) (in-process counters, no read). The drain socket's driver is newAgentDrainSocket(ingress, e, os.Getenv), which attaches the edge trust handler only when CARLOS_INGRESS_PROXY_SOURCES in the agent's environment (from the root-owned host.env) parses to a non-empty list; the socket is served when drainSocketServed: a group member or a configured ingress drain (both as before), or a box armed for PROXY protocol (new). The socket's path and agent-user-only permissions are unchanged. Read sites unchanged (6).;rev3=census-ruling-same-box-edge-fence;basis=Agent (uid carlos), not root. One added line: armEdgeFenceStatus(ctl.EdgeFence), beside the existing armExecSandboxStatus, so the layout report can ask root's /ready for the edge fence state over the control socket client the agent already holds. No read added.;rev3=census-ruling-platform-mail-submission;basis=Task 4: sets eb.Mail = mailsubmit.SocketForwarder{} on every box, and eb.MailSwitch to a mailSwitchCache's On that opens the deploy store itself through openDeployStore, retried at most once a minute with an error line until it opens (review round 1, Task 4 P3), armed for the serial-move refresh (armedMailSwitch). Task 6: also sets the ExecBackend's ManifestOf, the same staged-manifest read as TierOf (rt.App and RouteAccount(rt), hence +registry:App and +whole:Route), for the spawn-time check of decision 10, which logs and emits an event and never refuses. Agent, not root. Fable final P2-2: eb.MailSwitch is the cache's State (three-valued: on, off, unknown) in place of On; an unreadable switch is unknown, never off. No read added.;rev3=census-ruling-fleet-drain-followups;basis=P3 (#1008 T9): one call after armChangeIndex, requestBootFullPass(v, &backstopFullDue), which stores true in the existing in-memory backstopFullDue flag only when no record view is armed, so the fast loop runs its existing full pass on its first tick instead of instancesLoop a minute later; armed boxes unchanged. No read added; read sites unchanged (8); agent, not root.;rev3=census-ruling-fleet-first-reconcile-speed;basis=Startup timing log lines only: runDuties builds a step logger (newStartupLog, which reads the in-memory agent start time) and logs one line after the wait on the activator startup latch and after each existing duty before go fastConvergeLoop. One newStartupLog().at line in the edge ready hook before go tunnelLoop. No read added; read sites unchanged (8). Agent, not root.;rev3=census-ruling-ha-1192;basis=sets the group drain driver's departed hook to armedPeerDeparted (the armed departure controller's PeerDeparted: local registry identity + departure journal); no new read;rev3=census-ruling-replica-wake-gap-r3;basis=Calls lease.SetContinuityDir(<data dir>/.continuity) beside the existing obligation store: the agent's own 0700 directory for clean records, outside every instance tree (#1290 round 3). No new read; failure is logged and every start then takes a full image.;rev3=census-ruling-fleet-restart-wake;basis=Fleet restart wake Task 2: cfg.ReplicaRecord = replicaRecordFacts(boxLifetimes, cfg.Record): hands the existing judged record read (haRecordFacts over openDeployStore and boxJudge) as the live read on a lifetime index miss. No read site added here; agent, not root.;rev3=census-ruling-alias-publish-precert-1293;basis=starts edgesFileLoop with one more argument, edgeAcmeDir(os.Getenv, peekAcmeCache(args)): the agent's own -acme-cache flag (already parsed for domainsLoop) or $CARLOS_DATA_DIR/acme; a string computed from the operator's command line and environment, no read. Same 8 read sites.;rev3=census-ruling-console-addr-from-install;basis=publishes the running edge to consoleFleetEdgeSource for the heartbeat; no read added;rev3=census-ruling-instance-ready-before-wake;basis=the agent as carlos: sets svc.ConfigBeforeWake = configBeforeWake(reg, dd, claims.Writes) beside BeforeExec, before Start. Read sites unchanged, offsets moved.;rev3=census-ruling-managed-fleets-2b2;basis=takes RunAgent's one managed/BYO startup decision (decideAgentStartup, made before any fatal group preflight): a managed box gets its join (refused on an identity error or any group configuration: every admission predicate closed, edge/status/probes running, no Fatalf), never reads group configuration and never builds fixedAdmission; a BYO box reads and validates group configuration exactly as on main; binds the join as activator/exec/edge admission; ReconcileConfig.Joining on both provisioning loops; the worker boot pass runs once, at admission; Task 5: appends managedProbeOption(join) to the edge options when it is non-nil (a managed box with a valid root identity); BYO boxes unchanged; no read added; final wave: when runAgent makes the startup decision itself it also arms it (armedAgentStartup), as RunAgent does, so later group-configuration consumers follow it; no read added; merge of origin/main 173c7033: main's edge page cache arming, gVisor demos sandbox capture, region HA drain wiring and the flat-layout refusal wiring, not this branch; merge of origin/main 65951fbb: main's W6 ingress drain, linkLoop, duty view (armDutyView), replica swap worker, PPv2 drain socket, edge fence status, mail forwarder and switch, boot full pass, startup timing, peer departed hook, continuity dir, replica record facts, edges file ACME dir, console fleet edge source and ConfigBeforeWake, not this branch; code-health split: the startup decision fallback, BYO group configuration read and fixed admission build moved to agentAdmissionAtStart, the join binding to managedAdmissionOr, the boot pass branch to agentBootPass and the probe option to appendManagedProbe (managedagent.go), same calls in the same order, no read added;rev3=census-ruling-s3-polling-3;basis=The log and error shipping goroutines move unchanged into startLogLoops (internal/host/logloops.go), which also starts s3meter.LogEvery on the agent's context: an hourly log line of the process's in-memory S3 request counts. Same sinks, same label; adds no read.;rev3=census-ruling-instance-usage;basis=builds the usage meter through newUsageMeter(os.Getenv) (internal/host/instance_usage.go), which reads the env var CARLOS_INSTANCE_USAGE once (the same host.env the agent already reads) and, when it is off, calls m.DisableInstances and logs; runAgent then starts usageLoop with instances=!off so the usage loop arms the per-instance flusher (internal/host/instance_usage.go). The flusher adds one store read (spec section 12): (1) what is read: the box's own count objects usage/instances/<box>/<date>/<account>/<app>.json in the deployment bucket (or a fleet's rebased prefix), by the agent's usage flush, before each conditional write; (2) who writes them: the agent processes of the same box label through this flush; the bucket's * grant lets any platform box write any key, the same exposure as usage/edge/; tenants, apps and their credentials cannot write there, and a fleet box's store door confines it to its fleet's prefix; (3) what is checked: the body parses as v1 and its box, date, account and app match the key (usage.DecodeInstanceDay); anything else stops that object's write, is logged, and leaves the batch queued until the 24h drop horizon; (4) what it decides: only whether a batch is already merged (applied[writer]) and the totals the merge adds to; a forged object can cause an undercount or false totals, and can open, run or follow nothing;rev3=census-ruling-stage-spool-1582;basis=#1582: the agent (uid carlos, carlos-edge.service) arms through armRolloutAndStageRelay (stagerelay.go): armRolloutAndRelay, which no longer arms the relay, then the stage relay on every box; root never runs this; read sites unchanged;rev3=census-ruling-backhaul-streams-1535;basis=#1535: the agent: in the existing edge-ready callback (beside geoIPAlertSource and staticTreeSource) also stores the edge's in-memory backhaul shed counters getter into backhaulShedSource; an in-process function value, no read, no new authority; same 8 read sites. file:Exec@22105,file:Open@2294,file:Statfs@59460,registry:App@13402,registry:App@13780,whole:Route@13394,whole:Route@13772,whole:Route@52360 ef7cfb4d0a9758a95337d02dc1bd6b3ececcf83713a7ab5f4d98f15b74651441 |
| +internal/host/metrics_loop.go sampler.tick legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-remote-instance-metrics;basis=calls the owners probe before and after the unit read and tags readings with metrics.TagUnits and metrics.CarryTags; no read added;rev3=census-ruling-remote-metrics-nested;basis=clears the tenant tag of a reading marked leftover (a nested unit present at agent start) before CarryTags, and takes no CPU delta when a nested reading's set of cgroups changed since the previous tick; no read added;rev3=census-ruling-region-ha-p1b3b-t;basis=B5: Add one optional aggregate departure sample to the existing buffered sample; no per-host labels or separate writer.;rev3=census-ruling-backhaul-streams-1535;basis=#1535: the agent's metrics sampler adds the in-memory backhaul shed counters (sampleBackhaulSheds, from backhaulShedSource; nil before the edge is ready and while every counter is zero) to each sample as backhaul_sheds; the samples go to the existing raw-chunk flush; no read added, same 1 read site. file:ReadBytes@1093 5bcc277c64eaab72e3a6d4a7621acd205e10b07b41bc138dc0db7d7da3e730ec |
| +@coverage internal/alerting 7a5d9fd25d91023fca4ed31fba11b1b5e310359bafda8fb320c30d1df5b20545 |
| +@coverage internal/edge b1438aaaa984e730327350a0a3ae7b3cd87e05eeaff9fa89bb0f5cd346e8ba18 |
| +@coverage internal/host 28f2c15f7bbf542ba18e3de395943d73281ca207509ede15e705173605d610c9 |
| +@coverage internal/hostenv 200f3ec4cba578360c412994a10d8ac3f10a7ff8bf3ec5d5332dc2023d80b8f7 |
| +@coverage internal/metrics 36515a247ca5f233af7cb37bbd1e7d31b5d8edecbfaf700df372fa6e6a648cb3 |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index dcf23b42c..279531f3c 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -333,3 +333,4 @@ plan14-root-reads-config-new-first-1653.tsv af91f62a3bddb72188801f27302643b160b6 |
| plan14-root-reads-alias-with-mint-1653.tsv ce9536904e10de3f5e5c582061f130f870515ae0999de2946658ea49e4a17bf8 |
| plan14-root-reads-private-store-scan-1653.tsv ce9536904e10de3f5e5c582061f130f870515ae0999de2946658ea49e4a17bf8 |
| plan14-root-reads-canary-retire-orphan-1634.tsv 83cd5238dcd073e8fc89934a72f9c60b96081f15054f32a168f6cd594c88f49c |
| +plan14-root-reads-backhaul-streams-1535.tsv dc00dc6bab094e8c81ab4e083a0b6a122ea886a70f8dca4885b5cf8a2bc3b177 |