edge: sweep the static cache while running; alert before the disk floor
The 2026-11-08 annie outage (cold wakes refused at 5.4 GiB free, below the 5.9 GiB floor): eight extracted 2.6 GB apt versions piled up because the static sweep ran only at edge start. - The edge sweeps its static cache after every handler swap (30 s settle) and hourly. It keeps current, previous, trees live handlers serve and trees in-flight requests hold. Running sweeps take an exclusive Linux OFD record lock, which a refused conversion leaves shared. - The box disk rule's line drops to leave DiskFloor plus two of the largest kept static trees free, so it fires before the cold-wake floor (annie: at 11.1 GiB free instead of 5.9). Astra review: R1 2xP1+P2 fixed; R2 no P1. Census approved (#280). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from fix/static-sweep-periodic into main.
15 files changed,
+1,032
−107
docs/superpowers/notes/census-proposal-static-sweep-periodic.md+30 −0internal/edge/edge.go+15 −3internal/edge/static.go+41 −0internal/edge/static_periodic_sweep_test.go+303 −0internal/edge/static_recordlock_linux.go+26 −0internal/edge/static_recordlock_other.go+13 −0internal/edge/static_sweep_other.go+9 −7internal/edge/static_sweep_test.go+33 −13internal/edge/static_sweep_unix.go+155 −84internal/edge/static_trees.go+274 −0internal/host/agent.go+14 −0internal/host/diskalertline_test.go+74 −0internal/host/metrics_loop.go+28 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-static-sweep-periodic.tsv+16 −0
CI passed — run details
diff --git a/docs/superpowers/notes/census-proposal-static-sweep-periodic.md b/docs/superpowers/notes/census-proposal-static-sweep-periodic.md| new file mode 100644 |
| index 000000000..ded8da6e0 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-static-sweep-periodic.md |
| @@ -0,0 +1,30 @@ |
| +# Census approval: static-sweep-periodic |
| + |
| +Ruling `census-ruling-static-sweep-periodic`. The independent reviewer approves or rejects every change below, 2 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` `Edge.staticHandlerFor` | body | unchanged (3) | hands each static handler the process staticTrees record (ss.trees) and registers it there (weak pointer); in-memory wiring only, no read added; read sites unchanged (3) | |
| +| `internal/edge/static_sweep_unix.go` `setAside` | body | unchanged (5) | same walk of <cacheDir>/<acct>/<app> with valid account and app names, same current-link read, lstat and recognised names (release trees, .extract-, .sweep- debris; never files, links, bare or unknown names); now under the process tracker mutex per app dir, skipping a dir a handler is choosing a tree in, and keeping the previous tree (newest other by mtime), trees live handlers serve and trees requests hold, besides current; run at startup (exclusive flock) and by a running sweep (exclusive record lock); the agent, not root | |
| +| `internal/edge/static_sweep_unix.go` `sweepStaticCache` | body | unchanged (2) | same startup flock protocol on <cacheDir>/.edge.lock (the same two OpenFile calls); now also takes a shared OFD record lock on byte 0 of that file before the startup check, returns the process staticTrees record (lock, periodic flag) and measures the kept trees after the startup removal; a running edge sweeps later through the same setAside under an exclusive record lock; the agent (carlos-edge.service, user carlos), not root; its own static cache only | |
| +| `internal/host/agent.go` `runAgent` | body | unchanged (9) | 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) | |
| + |
| +Envelopes re-pinned: `internal/edge`, `internal/host`. |
| + |
| +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` `Edge.staticHandlerFor`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-devbox-mode;basis=devbox mode (#474): when WithLocalStatic set localStaticRoot (only edge.ServeDevbox sets it, run by carlos devbox serve as the unprivileged carlos-devbox user), a static route is handed to newLocalStaticHandler instead of the release store. Reads the same Route (its App) as before; with the root unset the store path is byte-for-byte unchanged. No new read |
| +- `internal/edge/static_sweep_unix.go` `setAside`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-static-sweep;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=root-input; once at startup, before any static handler exists, only under an exclusive flock (sweepStaticCache), reads its own static cache (<cacheDir>/<acct>/<app> with valid account and app names: entries, each current link, each entry lstat) and renames each release tree (<version>@<64-hex digest>) the current link does not name to a .sweep- name for removal, with its own debris (.extract-<n>, .sweep-<name>-<n>); never touches files, links, bare names, or names it does not recognise; every tree is a cache of a signed release that ensureExtracted re-verifies before extracting it again; no root decision |
| +- `internal/edge/static_sweep_unix.go` `sweepStaticCache`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-static-sweep;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=root-input; opens or creates <cacheDir>/.edge.lock and flocks it: a start that creates it sweeps nothing (an older edge may not lock; systemd stops an edge before it starts the next, Paul 2026-10-25), otherwise exclusive non-blocking to sweep, then shared for the process life; a lock it cannot hold is an ALERT and the edge still serves (Paul 2026-10-25); the lock decides only whether this start sweeps; no root decision |
| +- `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. |
| + |
| +New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff: |
| + |
| +- new `internal/edge/static_trees.go:staticTrees.measure`: reads +file:ReadDir ×3; written legacy, accepted-legacy, frozen |
| +- new `internal/edge/static_trees.go:treeBytes`: reads +file:WalkDir; written legacy, accepted-legacy, frozen |
| + |
| +Seal: `687cf7744aecdf8a238dcdb80562b0ef191b3e247c28851de44c01866dbeca13` → `3dc3f6657527133a251c028772315bdd333b04c318fbbc6d90ef5047f15408ed`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-static-sweep-periodic.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index d1841571e..7ef38b291 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -207,8 +207,10 @@ type Edge struct { |
| // routes are served from instead of staticStore. See localstatic.go. |
| localStaticRoot string |
| // staticLock is this process's shared hold on the static cache |
| - // (sweepStaticCache): a starting edge sweeps only when it is alone. |
| + // (sweepStaticCache): an edge sweeps only when it is alone. staticTrees |
| + // is the process's record of that cache (static_trees.go). |
| staticLock *os.File |
| + staticTrees *staticTrees |
| staticRecheck time.Duration |
| // staticRatchet is #253's ratchet for static pointer reads: marks under |
| // <dataDir>/pointer-digests, root's under /opt read too. |
| @@ -625,8 +627,11 @@ func (e *Edge) EnableStatic(store release.Store, pub ed25519.PublicKey, cacheDir |
| // Before any static handler exists: old extracted trees go if this is |
| // the only edge using the cache (static_sweep_unix.go). The lock is |
| // held, shared, for the process's life. |
| - if cacheDir != "" && e.staticLock == nil { |
| - e.staticLock, _ = sweepStaticCache(cacheDir) |
| + if cacheDir != "" && e.staticTrees == nil { |
| + e.staticTrees, _ = sweepStaticCache(cacheDir) |
| + e.staticLock = e.staticTrees.lock |
| + // Then again after every swap and every hour, for the process's life. |
| + go e.staticTrees.run(staticSweepEvery, staticSweepSettle) |
| } |
| e.armStoreDoor() |
| } |
| @@ -807,6 +812,11 @@ func (e *Edge) fleetAccount(fleet string) (string, bool) { |
| // EnableStatic and before Reload; handlers built on the next reload use it. |
| func (e *Edge) SetStaticRecheck(d time.Duration) { e.staticRecheck = d } |
| +// LargestStaticTree is the byte count of the largest extracted static tree |
| +// this edge keeps on disk, 0 when it serves none. The disk alert leaves |
| +// room for two more above the cold-wake floor (internal/host). |
| +func (e *Edge) LargestStaticTree() int64 { return e.staticTrees.Largest() } |
| + |
| // staticHandlerFor builds the handler for one static route: the real serving |
| // class when EnableStatic has configured it, else the pre-config 404 (the |
| // route exists — and its cert can be minted — before the bytes can flow). |
| @@ -825,6 +835,8 @@ func (e *Edge) staticHandlerFor(rt registry.Route) http.Handler { |
| if ss, ok := h.(*staticSite); ok { |
| ss.recheck = e.staticRecheck |
| ss.ratchet = e.staticRatchet |
| + ss.trees = e.staticTrees |
| + e.staticTrees.register(ss) |
| } |
| return h |
| } |
diff --git a/internal/edge/static.go b/internal/edge/static.go| index 13ff63fbf..997e835ca 100644 |
| --- a/internal/edge/static.go |
| +++ b/internal/edge/static.go |
| @@ -153,6 +153,12 @@ type staticSite struct { |
| // ratchet is #253's per-box ratchet for this process's pointer reads |
| // (Edge.staticRatchet); nil admits every verified pointer. |
| ratchet *release.DigestRatchet |
| + |
| + // trees is the edge's record of the static cache (static_trees.go): a |
| + // sweep keeps the tree serving names, and leaves the app directory alone |
| + // while this handler chooses a tree there. nil records nothing. |
| + trees *staticTrees |
| + serving atomic.Pointer[string] |
| } |
| // newStaticHandler builds the serving handler for one static route. The |
| @@ -175,6 +181,7 @@ func newStaticHandler(rt registry.Route, store release.Store, pub ed25519.Public |
| func (s *staticSite) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| tree, err := s.currentDir(r.Context()) |
| + defer tree.release() |
| if err != nil { |
| // Nothing has ever resolved here, so there is no version to name: |
| // this 502 stays unstamped rather than claiming a build it isn't |
| @@ -219,6 +226,15 @@ type servedTree struct { |
| dir, version string |
| redirects *redirectRules |
| headers *headerRules |
| + // unpin ends the tree's hold against the sweep (staticTrees.pin). |
| + unpin func() |
| +} |
| + |
| +// release ends the tree's hold against the sweep, once the request is done. |
| +func (t servedTree) release() { |
| + if t.unpin != nil { |
| + t.unpin() |
| + } |
| } |
| // dir is where the tree named name lives once extracted. |
| @@ -250,9 +266,21 @@ func (s *staticSite) appDir() string { |
| // without the window in between, where a concurrent resolve could swap |
| // s.version and make the header describe a different tree than the one served). |
| // The tree's redirect rules come back with it for the same reason. |
| +// |
| +// The tree comes back pinned against the sweep, taken while mu is held so |
| +// it is one this handler still names; the caller releases it when done. |
| func (s *staticSite) currentDir(ctx context.Context) (servedTree, error) { |
| s.mu.Lock() |
| defer s.mu.Unlock() |
| + tree, err := s.resolveLocked(ctx) |
| + if err == nil { |
| + tree.unpin = s.trees.pin(tree.dir) |
| + } |
| + return tree, err |
| +} |
| + |
| +// resolveLocked is currentDir's work. The caller holds mu. |
| +func (s *staticSite) resolveLocked(ctx context.Context) (servedTree, error) { |
| if s.version != "" && s.recheck > 0 && time.Since(s.checkedAt) < s.recheck { |
| // Inside the trust window: this request is answered from the cached |
| // version, and stamping that version is honest by construction — the |
| @@ -268,14 +296,22 @@ func (s *staticSite) currentDir(ctx context.Context) (servedTree, error) { |
| return s.stale(err) |
| } |
| if want := cp.Digest; cp.Version != s.version || (want != "" && want != s.digest) { |
| + // From the check of what is on disk to the record of what is served, |
| + // no sweep touches this app's directory. |
| + done := s.trees.begin(s.appDir()) |
| name, digest, err := s.ensureExtracted(ctx, cp.Version, want) |
| if err != nil { |
| + done() |
| return s.stale(fmt.Errorf("stage %s: %w", cp.Version, err)) |
| } |
| if err := s.pointCurrent(name); err != nil { |
| + done() |
| return s.stale(fmt.Errorf("swap current -> %s: %w", name, err)) |
| } |
| s.version, s.digest, s.name = cp.Version, digest, name |
| + s.serving.Store(&name) |
| + done() |
| + s.trees.swapped() |
| s.redirects = s.loadRedirects(s.dir(name), cp.Version) |
| s.headers = s.loadHeaders(s.dir(name), cp.Version) |
| } |
| @@ -485,7 +521,12 @@ func (s *staticSite) ensureExtracted(ctx context.Context, version, want string) |
| // pointCurrent atomically swaps the app's `current` symlink to the tree named name |
| // (temp symlink + rename — the same swap versions.go's PointLive uses), so |
| // anything looking at the cache dir sees the version flip as one atomic step. |
| +// |
| +// The tree's mtime is set to now first: it records when the tree last |
| +// became current, which is how the sweep tells the previous tree. |
| func (s *staticSite) pointCurrent(name string) error { |
| + now := time.Now() |
| + _ = os.Chtimes(s.dir(name), now, now) |
| link := filepath.Join(s.appDir(), "current") |
| tmp := link + ".tmp" |
| _ = os.Remove(tmp) // a leftover from a crashed swap |
diff --git a/internal/edge/static_periodic_sweep_test.go b/internal/edge/static_periodic_sweep_test.go| new file mode 100644 |
| index 000000000..76a573859 |
| --- /dev/null |
| +++ b/internal/edge/static_periodic_sweep_test.go |
| @@ -0,0 +1,303 @@ |
| +//go:build linux |
| + |
| +// Running sweeps need the record lock, which only Linux has |
| +// (static_recordlock_linux.go). |
| + |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "runtime" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// openTrees is a started edge's view of cache: the startup sweep has run |
| +// (the lock file existed, so this start was allowed to sweep). |
| +func openTrees(t *testing.T, cache string) *staticTrees { |
| + t.Helper() |
| + seenLock(t, cache) |
| + tr, done := sweepStaticCache(cache) |
| + <-done |
| + if tr.lock == nil { |
| + t.Fatal("no serving lock") |
| + } |
| + t.Cleanup(func() { tr.lock.Close() }) |
| + return tr |
| +} |
| + |
| +// The 2026-11-08 annie outage: the edge ran for a day while eight apt |
| +// releases shipped, and only a restart swept. A running edge now sweeps by |
| +// itself, keeping each app's current tree, the one current before it, and |
| +// any tree a live handler still serves (another channel of the same app |
| +// shares the app directory and its one current link). |
| +func TestStaticPeriodicSweepKeepsCurrentPreviousAndServed(t *testing.T) { |
| + cache := t.TempDir() |
| + tr := openTrees(t, cache) |
| + base := time.Now().Add(-time.Hour) |
| + for i, v := range []string{"v1", "v2", "v3", "v4", "v5"} { |
| + cacheTree(t, cache, "bab", "apt", tree(v)) |
| + madeCurrentAt(t, cache, "bab", "apt", tree(v), base.Add(time.Duration(i)*time.Minute)) |
| + } |
| + pointAt(t, cache, "bab", "apt", tree("v5")) |
| + beta := &staticSite{acct: "bab", app: "apt", cacheDir: cache} |
| + beta.serving.Store(new(tree("v2"))) |
| + tr.register(beta) |
| + |
| + tr.sweepOnce() |
| + |
| + if got, want := joined(t, filepath.Join(cache, "bab", "apt")), strings.Join([]string{"current", tree("v2"), tree("v4"), tree("v5")}, "|"); got != want { |
| + t.Errorf("bab/apt = %v, want %v (current, previous, and the tree a live handler serves)", got, want) |
| + } |
| + runtime.KeepAlive(beta) |
| +} |
| + |
| +// A handler choosing a tree (resolving, extracting, swapping current) holds |
| +// its app directory out of the sweep, so a tree it found on disk cannot be |
| +// set aside between its check and its swap, and its temp extraction is not |
| +// taken for debris. |
| +func TestStaticPeriodicSweepSkipsAnAppMidResolve(t *testing.T) { |
| + cache := t.TempDir() |
| + tr := openTrees(t, cache) |
| + for _, v := range []string{"v1", "v2", "v3"} { |
| + cacheTree(t, cache, "bab", "apt", tree(v)) |
| + } |
| + cacheTree(t, cache, "bab", "apt", ".extract-42") |
| + pointAt(t, cache, "bab", "apt", tree("v3")) |
| + appDir := filepath.Join(cache, "bab", "apt") |
| + |
| + done := tr.begin(appDir) |
| + tr.sweepOnce() |
| + if got := entries(t, appDir); len(got) != 5 { |
| + t.Errorf("bab/apt = %v, want nothing swept while a handler resolves there", got) |
| + } |
| + done() |
| + tr.sweepOnce() |
| + if got := entries(t, appDir); len(got) != 3 { |
| + t.Errorf("bab/apt = %v, want current + previous once the resolve is done", got) |
| + } |
| +} |
| + |
| +// Another edge using the cache (one that started beside this one) makes |
| +// the running edge sweep nothing. The refused attempt drops nothing either: |
| +// once the other edge has gone, no third may take the cache exclusively, |
| +// at start (flock) or for a running sweep (the record lock). |
| +func TestStaticPeriodicSweepSkipsWhileAnotherEdgeServesAndKeepsItsLocks(t *testing.T) { |
| + cache := t.TempDir() |
| + tr := openTrees(t, cache) |
| + for _, v := range []string{"v1", "v2", "v3"} { |
| + cacheTree(t, cache, "bab", "apt", tree(v)) |
| + } |
| + pointAt(t, cache, "bab", "apt", tree("v3")) |
| + other, done := sweepStaticCache(cache) |
| + <-done |
| + if other.periodic { |
| + t.Fatal("an edge that started beside another may sweep while running") |
| + } |
| + |
| + tr.sweepOnce() |
| + |
| + if got := entries(t, filepath.Join(cache, "bab", "apt")); len(got) != 4 { |
| + t.Errorf("bab/apt = %v, want everything kept while another edge serves", got) |
| + } |
| + other.lock.Close() |
| + probe, err := os.OpenFile(filepath.Join(cache, staticLockName), os.O_RDWR, 0o600) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer probe.Close() |
| + if err := syscall.Flock(int(probe.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err == nil { |
| + t.Fatal("the running edge lost its shared flock after a refused sweep") |
| + } |
| + if err := recordLock(probe, false, false); err == nil { |
| + t.Fatal("the running edge lost its shared record lock after a refused sweep") |
| + } |
| + // With the other edge gone, the running one sweeps again. |
| + tr.sweepOnce() |
| + if got := entries(t, filepath.Join(cache, "bab", "apt")); len(got) != 3 { |
| + t.Errorf("bab/apt = %v, want current + previous once the other edge has gone", got) |
| + } |
| +} |
| + |
| +// A request holds the tree it was given until it is done: a handler that |
| +// swaps twice meanwhile no longer names it, and it is neither current nor |
| +// previous, but a sweep leaves it. |
| +func TestStaticPeriodicSweepKeepsATreeARequestHolds(t *testing.T) { |
| + cache := t.TempDir() |
| + tr := openTrees(t, cache) |
| + for i, v := range []string{"v1", "v2", "v3"} { |
| + cacheTree(t, cache, "bab", "apt", tree(v)) |
| + madeCurrentAt(t, cache, "bab", "apt", tree(v), time.Now().Add(time.Duration(i-10)*time.Minute)) |
| + } |
| + pointAt(t, cache, "bab", "apt", tree("v3")) |
| + release := tr.pin(filepath.Join(cache, "bab", "apt", tree("v1"))) |
| + |
| + tr.sweepOnce() |
| + if got := entries(t, filepath.Join(cache, "bab", "apt")); len(got) != 4 { |
| + t.Errorf("bab/apt = %v, want the held tree kept", got) |
| + } |
| + release() |
| + tr.sweepOnce() |
| + if got := joined(t, filepath.Join(cache, "bab", "apt")); got != "current|"+tree("v2")+"|"+tree("v3") { |
| + t.Errorf("bab/apt = %v, want the tree swept once the request is done", got) |
| + } |
| +} |
| + |
| +// The previous tree is chosen before the trees handlers serve are set |
| +// apart: a handler serving the previous tree keeps no third one. |
| +func TestStaticPeriodicSweepPreviousIsChosenFromEveryTree(t *testing.T) { |
| + cache := t.TempDir() |
| + tr := openTrees(t, cache) |
| + for i, v := range []string{"v1", "v2", "v3"} { |
| + cacheTree(t, cache, "bab", "apt", tree(v)) |
| + madeCurrentAt(t, cache, "bab", "apt", tree(v), time.Now().Add(time.Duration(i-10)*time.Minute)) |
| + } |
| + pointAt(t, cache, "bab", "apt", tree("v3")) |
| + beta := &staticSite{acct: "bab", app: "apt", cacheDir: cache} |
| + beta.serving.Store(new(tree("v2"))) |
| + tr.register(beta) |
| + |
| + tr.sweepOnce() |
| + |
| + if got := joined(t, filepath.Join(cache, "bab", "apt")); got != "current|"+tree("v2")+"|"+tree("v3") { |
| + t.Errorf("bab/apt = %v, want v1 swept", got) |
| + } |
| + runtime.KeepAlive(beta) |
| +} |
| + |
| +// The first lock-aware start may share the cache with an edge that takes no |
| +// lock, for the whole of its life: it never sweeps, at start or later. |
| +func TestStaticPeriodicSweepNeverOnTheFirstLockAwareStart(t *testing.T) { |
| + cache := t.TempDir() |
| + tr, done := sweepStaticCache(cache) |
| + <-done |
| + defer tr.lock.Close() |
| + for _, v := range []string{"v1", "v2", "v3"} { |
| + cacheTree(t, cache, "bab", "apt", tree(v)) |
| + } |
| + pointAt(t, cache, "bab", "apt", tree("v3")) |
| + tr.sweepOnce() |
| + if got := entries(t, filepath.Join(cache, "bab", "apt")); len(got) != 4 { |
| + t.Errorf("bab/apt = %v, want nothing swept by the first lock-aware edge", got) |
| + } |
| +} |
| + |
| +// The edge knows the size of the largest tree it keeps: the disk alert |
| +// leaves room for two of them above the cold-wake floor. |
| +func TestStaticTreesMeasureTheLargestKeptTree(t *testing.T) { |
| + cache := t.TempDir() |
| + tr := openTrees(t, cache) |
| + if got := tr.Largest(); got != 0 { |
| + t.Fatalf("empty cache: largest = %d", got) |
| + } |
| + for _, v := range []string{"v1", "v2"} { |
| + cacheTree(t, cache, "bab", "apt", tree(v)) |
| + } |
| + big := filepath.Join(cache, "bab", "apt", tree("v1"), "pool.deb") |
| + if err := os.WriteFile(big, make([]byte, 5000), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + pointAt(t, cache, "bab", "apt", tree("v2")) |
| + cacheTree(t, cache, "bac", "docs", tree("v9")) |
| + pointAt(t, cache, "bac", "docs", tree("v9")) |
| + |
| + tr.sweepOnce() |
| + |
| + // v1 = index.html (its own name, 66 bytes) + 5000. |
| + if got, want := tr.Largest(), int64(len(tree("v1"))+5000); got != want { |
| + t.Errorf("largest = %d, want %d", got, want) |
| + } |
| +} |
| + |
| +// End to end through the serving handler: releases promoted one after |
| +// another leave the two newest on disk after a sweep, the site keeps |
| +// serving, every swap asks for a sweep, a request's tree outlives swaps |
| +// while it is answered, and a rollback to a swept release extracts it |
| +// again. |
| +func TestStaticPeriodicSweepThroughTheHandler(t *testing.T) { |
| + storeRoot := filepath.Join(t.TempDir(), "store") |
| + store := release.NewDirStore(storeRoot) |
| + priv, pub := testKeys(t) |
| + cache := filepath.Join(t.TempDir(), "cache") |
| + if err := os.MkdirAll(cache, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + tr := openTrees(t, cache) |
| + |
| + rt := registry.Route{Host: "site.example.com", Kind: "static", App: "site", Channel: "stable", Status: "ready"} |
| + h := newStaticHandler(rt, store, pub, cache).(*staticSite) |
| + h.recheck = 0 |
| + h.trees = tr |
| + tr.register(h) |
| + srv := httptest.NewServer(h) |
| + defer srv.Close() |
| + |
| + for _, v := range []string{"v1", "v2", "v3", "v4"} { |
| + shipSite(t, store, "site", v, map[string]string{"index.html": "home " + v}) |
| + if err := release.Promote(context.Background(), store, priv, release.OpsAccount, "site", "stable", v); err != nil { |
| + t.Fatalf("Promote %s: %v", v, err) |
| + } |
| + if code, body := getPath(t, srv.URL, "site.example.com", "/"); code != http.StatusOK || body != "home "+v { |
| + t.Fatalf("GET / after %s = %d %q", v, code, body) |
| + } |
| + select { |
| + case <-tr.kick: |
| + default: |
| + t.Fatalf("the swap to %s asked for no sweep", v) |
| + } |
| + time.Sleep(20 * time.Millisecond) // mtimes order the trees |
| + } |
| + |
| + // A request that took v4's tree is still being answered while v5 and v6 |
| + // ship and a sweep runs: its tree stays until it is done. |
| + held, err := h.currentDir(context.Background()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, v := range []string{"v5", "v6"} { |
| + shipSite(t, store, "site", v, map[string]string{"index.html": "home " + v}) |
| + if err := release.Promote(context.Background(), store, priv, release.OpsAccount, "site", "stable", v); err != nil { |
| + t.Fatalf("Promote %s: %v", v, err) |
| + } |
| + if code, body := getPath(t, srv.URL, "site.example.com", "/"); code != http.StatusOK || body != "home "+v { |
| + t.Fatalf("GET / after %s = %d %q", v, code, body) |
| + } |
| + time.Sleep(20 * time.Millisecond) |
| + } |
| + tr.sweepOnce() |
| + if _, err := os.Stat(filepath.Join(held.dir, "index.html")); err != nil { |
| + t.Fatalf("a held tree was swept: %v", err) |
| + } |
| + held.release() |
| + |
| + tr.sweepOnce() |
| + |
| + appDir := filepath.Join(cache, h.acct, "site") |
| + var trees []string |
| + for _, n := range entries(t, appDir) { |
| + if m := siteTreeName.FindStringSubmatch(n); m != nil { |
| + trees = append(trees, m[1]) |
| + } |
| + } |
| + if got := strings.Join(trees, ","); got != "v5,v6" { |
| + t.Errorf("trees after the sweep = %s, want v5,v6", got) |
| + } |
| + if code, body := getPath(t, srv.URL, "site.example.com", "/"); code != http.StatusOK || body != "home v6" { |
| + t.Fatalf("GET / after the sweep = %d %q", code, body) |
| + } |
| + if err := release.Promote(context.Background(), store, priv, release.OpsAccount, "site", "stable", "v1"); err != nil { |
| + t.Fatalf("Promote v1 again: %v", err) |
| + } |
| + if code, body := getPath(t, srv.URL, "site.example.com", "/"); code != http.StatusOK || body != "home v1" { |
| + t.Fatalf("GET / after rolling back to a swept release = %d %q", code, body) |
| + } |
| +} |
diff --git a/internal/edge/static_recordlock_linux.go b/internal/edge/static_recordlock_linux.go| new file mode 100644 |
| index 000000000..7007114dc |
| --- /dev/null |
| +++ b/internal/edge/static_recordlock_linux.go |
| @@ -0,0 +1,26 @@ |
| +//go:build linux |
| + |
| +package edge |
| + |
| +import ( |
| + "os" |
| + |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// recordLock sets this open file's record lock on the lock file's first |
| +// byte: shared or exclusive, waiting for it or not. An open-file-description |
| +// lock, unlike flock(2), changes mode in one step: a refused change leaves |
| +// the lock already held exactly as it was, so a running edge can ask |
| +// whether it is alone without ever letting go (staticTrees.sweepCache). |
| +func recordLock(f *os.File, shared, wait bool) error { |
| + lk := unix.Flock_t{Type: unix.F_WRLCK, Whence: 0, Start: 0, Len: 1} |
| + if shared { |
| + lk.Type = unix.F_RDLCK |
| + } |
| + cmd := unix.F_OFD_SETLK |
| + if wait { |
| + cmd = unix.F_OFD_SETLKW |
| + } |
| + return unix.FcntlFlock(f.Fd(), cmd, &lk) |
| +} |
diff --git a/internal/edge/static_recordlock_other.go b/internal/edge/static_recordlock_other.go| new file mode 100644 |
| index 000000000..5dba378cc |
| --- /dev/null |
| +++ b/internal/edge/static_recordlock_other.go |
| @@ -0,0 +1,13 @@ |
| +//go:build unix && !linux |
| + |
| +package edge |
| + |
| +import ( |
| + "errors" |
| + "os" |
| +) |
| + |
| +// recordLock has no open-file-description locks to use here, so a running |
| +// edge never sweeps (static_recordlock_linux.go); the startup sweep still |
| +// runs. |
| +func recordLock(*os.File, bool, bool) error { return errors.ErrUnsupported } |
diff --git a/internal/edge/static_sweep_other.go b/internal/edge/static_sweep_other.go| index 2be635b30..71c3fcc81 100644 |
| --- a/internal/edge/static_sweep_other.go |
| +++ b/internal/edge/static_sweep_other.go |
| @@ -2,12 +2,14 @@ |
| package edge |
| -import "os" |
| - |
| -// sweepStaticCache needs flock to know no other edge serves the cache; with |
| -// none here, nothing is swept (static_sweep_unix.go). |
| -func sweepStaticCache(string) (*os.File, <-chan struct{}) { |
| +// sweepStaticCache holds no lock and sweeps nothing here: it needs flock to |
| +// know no other edge serves the cache (static_sweep_unix.go); it still measures |
| +// the trees for the disk alert. |
| +func sweepStaticCache(cacheDir string) (*staticTrees, <-chan struct{}) { |
| + t := newStaticTrees(cacheDir) |
| done := make(chan struct{}) |
| - close(done) |
| - return nil, done |
| + go func() { defer close(done); t.measure() }() |
| + return t, done |
| } |
| + |
| +func (t *staticTrees) sweepCache() int { return 0 } |
diff --git a/internal/edge/static_sweep_test.go b/internal/edge/static_sweep_test.go| index df7b1c712..cf4a7230e 100644 |
| --- a/internal/edge/static_sweep_test.go |
| +++ b/internal/edge/static_sweep_test.go |
| @@ -9,6 +9,7 @@ import ( |
| "strings" |
| "syscall" |
| "testing" |
| + "time" |
| ) |
| // tree is a cache entry name as ensureExtracted makes it. |
| @@ -42,6 +43,17 @@ func seenLock(t *testing.T, cache string) { |
| } |
| } |
| +// madeCurrentAt dates a tree the way pointCurrent does: its mtime is when it |
| +// last became an app's current tree. |
| +func madeCurrentAt(t *testing.T, cache, acct, app, name string, at time.Time) { |
| + t.Helper() |
| + if err := os.Chtimes(filepath.Join(cache, acct, app, name), at, at); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func joined(t *testing.T, dir string) string { return strings.Join(entries(t, dir), "|") } |
| + |
| func entries(t *testing.T, dir string) []string { |
| t.Helper() |
| es, err := os.ReadDir(dir) |
| @@ -58,7 +70,8 @@ func entries(t *testing.T, dir string) []string { |
| func sweep(t *testing.T, cache string) { |
| t.Helper() |
| - lock, done := sweepStaticCache(cache) |
| + tr, done := sweepStaticCache(cache) |
| + lock := tr.lock |
| if lock == nil { |
| t.Fatal("no serving lock") |
| } |
| @@ -67,15 +80,16 @@ func sweep(t *testing.T, cache string) { |
| } |
| // With no other edge holding the cache, every release tree but each app's |
| -// current one goes, and so does the edge's own debris (a temp extraction, |
| +// current one and the one current before it (the newest other by mtime) goes, and so does the edge's own debris (a temp extraction, |
| // an earlier sweep's leftovers) and pre-#253 bare-version trees. Anything |
| // the sweep does not recognise as its own (an operator's directory, a |
| // file, a link) is left alone. |
| -func TestStaticStartupSweepKeepsOnlyEachAppsCurrentTree(t *testing.T) { |
| +func TestStaticStartupSweepKeepsEachAppsCurrentAndPreviousTree(t *testing.T) { |
| cache := t.TempDir() |
| seenLock(t, cache) |
| - for _, v := range []string{"v1", "v2", "v3"} { |
| + for i, v := range []string{"v1", "v2", "v3"} { |
| cacheTree(t, cache, "bab", "apt", tree(v)) |
| + madeCurrentAt(t, cache, "bab", "apt", tree(v), time.Now().Add(time.Duration(i-10)*time.Minute)) |
| } |
| pointAt(t, cache, "bab", "apt", tree("v3")) |
| cacheTree(t, cache, "bab", "apt", ".extract-123") |
| @@ -88,18 +102,20 @@ func TestStaticStartupSweepKeepsOnlyEachAppsCurrentTree(t *testing.T) { |
| } |
| cacheTree(t, cache, "bac", "docs", tree("v7")) |
| pointAt(t, cache, "bac", "docs", tree("v7")) |
| - cacheTree(t, cache, "bac", "nolink", tree("v1")) // no current link: no tree is kept |
| + cacheTree(t, cache, "bac", "nolink", tree("v1")) // no current link: the newest tree is the previous one |
| + cacheTree(t, cache, "bac", "nolink", tree("v0")) |
| + madeCurrentAt(t, cache, "bac", "nolink", tree("v0"), time.Now().Add(-time.Hour)) |
| sweep(t, cache) |
| - if got, want := entries(t, filepath.Join(cache, "bab", "apt")), []string{"backup 2026", "current", "note.txt", "v0.5.0-1", tree("v3")}; strings.Join(got, "|") != strings.Join(want, "|") { |
| + if got, want := entries(t, filepath.Join(cache, "bab", "apt")), []string{"backup 2026", "current", "note.txt", "v0.5.0-1", tree("v2"), tree("v3")}; strings.Join(got, "|") != strings.Join(want, "|") { |
| t.Errorf("bab/apt = %v, want %v", got, want) |
| } |
| if got, want := entries(t, filepath.Join(cache, "bac", "docs")), []string{"current", tree("v7")}; strings.Join(got, "|") != strings.Join(want, "|") { |
| t.Errorf("bac/docs = %v, want %v", got, want) |
| } |
| - if got := entries(t, filepath.Join(cache, "bac", "nolink")); len(got) != 0 { |
| - t.Errorf("bac/nolink = %v, want empty", got) |
| + if got := joined(t, filepath.Join(cache, "bac", "nolink")); got != tree("v1") { |
| + t.Errorf("bac/nolink = %v, want only the newest tree", got) |
| } |
| if got := entries(t, filepath.Join(cache, "Not An Account", "apt")); len(got) != 1 { |
| t.Errorf("an invalid account's directory was entered: %v", got) |
| @@ -116,11 +132,13 @@ func TestStaticStartupSweepNeverTakesAReleaseForDebris(t *testing.T) { |
| cacheTree(t, cache, "bab", "a", tree(".sweep-x-1")) |
| pointAt(t, cache, "bab", "a", tree(".sweep-x-1")) |
| cacheTree(t, cache, "bab", "b", tree(".extract-9")) |
| + madeCurrentAt(t, cache, "bab", "b", tree(".extract-9"), time.Now().Add(-time.Hour)) |
| + cacheTree(t, cache, "bab", "b", tree("v1")) // the previous tree |
| cacheTree(t, cache, "bab", "b", tree("v2")) |
| pointAt(t, cache, "bab", "b", tree("v2")) |
| - lock, done := sweepStaticCache(cache) |
| - defer lock.Close() |
| + tr, done := sweepStaticCache(cache) |
| + defer tr.lock.Close() |
| // Before the background removal ends, the non-current release is |
| // already gone from its own name: nothing can select it. |
| if _, err := os.Stat(filepath.Join(cache, "bab", "b", tree(".extract-9"))); !os.IsNotExist(err) { |
| @@ -130,7 +148,7 @@ func TestStaticStartupSweepNeverTakesAReleaseForDebris(t *testing.T) { |
| if got := entries(t, filepath.Join(cache, "bab", "a")); strings.Join(got, "|") != tree(".sweep-x-1")+"|current" { |
| t.Errorf("bab/a = %v, want the current release kept", got) |
| } |
| - if got := entries(t, filepath.Join(cache, "bab", "b")); strings.Join(got, "|") != "current|"+tree("v2") { |
| + if got := entries(t, filepath.Join(cache, "bab", "b")); strings.Join(got, "|") != "current|"+tree("v1")+"|"+tree("v2") { |
| t.Errorf("bab/b = %v", got) |
| } |
| } |
| @@ -141,11 +159,12 @@ func TestStaticStartupSweepNeverTakesAReleaseForDebris(t *testing.T) { |
| // cache is known to take it. |
| func TestStaticStartupSweepFirstStartOnlyCreatesTheLock(t *testing.T) { |
| cache := t.TempDir() |
| + cacheTree(t, cache, "bab", "apt", tree("v0")) |
| cacheTree(t, cache, "bab", "apt", tree("v1")) |
| cacheTree(t, cache, "bab", "apt", tree("v2")) |
| pointAt(t, cache, "bab", "apt", tree("v2")) |
| sweep(t, cache) |
| - if got := entries(t, filepath.Join(cache, "bab", "apt")); len(got) != 3 { |
| + if got := entries(t, filepath.Join(cache, "bab", "apt")); len(got) != 4 { |
| t.Errorf("bab/apt = %v, want nothing swept on the first lock-aware start", got) |
| } |
| if _, err := os.Stat(filepath.Join(cache, staticLockName)); err != nil { |
| @@ -157,6 +176,7 @@ func TestStaticStartupSweepFirstStartOnlyCreatesTheLock(t *testing.T) { |
| // sweep does nothing, and still returns a shared lock for this process. |
| func TestStaticStartupSweepSkipsWhileAnotherEdgeServes(t *testing.T) { |
| cache := t.TempDir() |
| + cacheTree(t, cache, "bab", "apt", tree("v0")) |
| cacheTree(t, cache, "bab", "apt", tree("v1")) |
| cacheTree(t, cache, "bab", "apt", tree("v2")) |
| pointAt(t, cache, "bab", "apt", tree("v2")) |
| @@ -170,7 +190,7 @@ func TestStaticStartupSweepSkipsWhileAnotherEdgeServes(t *testing.T) { |
| t.Fatal(err) |
| } |
| sweep(t, cache) |
| - if got := entries(t, filepath.Join(cache, "bab", "apt")); len(got) != 3 { |
| + if got := entries(t, filepath.Join(cache, "bab", "apt")); len(got) != 4 { |
| t.Errorf("bab/apt = %v, want everything kept while another edge serves", got) |
| } |
| } |
diff --git a/internal/edge/static_sweep_unix.go b/internal/edge/static_sweep_unix.go| index fbf15e743..5a4f59e32 100644 |
| --- a/internal/edge/static_sweep_unix.go |
| +++ b/internal/edge/static_sweep_unix.go |
| @@ -17,34 +17,48 @@ import ( |
| // Every version of a static site a box served stayed extracted under |
| // <cacheDir>/<acct>/<app>/ forever: annie-welding held 51 copies of the apt |
| -// site, 20 GB of 59 (2026-10-25). Sweeping on the serving path races the |
| -// handlers that pick trees (Astra review of static-sweep), so the sweep |
| -// runs once, at startup, before any handler exists, and only when no other |
| -// edge process can be serving from this cache: |
| +// site, 20 GB of 59 (2026-10-25). The sweep that fixed that ran only at |
| +// startup, before any handler existed, and annie filled to the cold-wake |
| +// floor again on 2026-11-08 between two restarts. A running edge now sweeps |
| +// too (staticTrees.run). Who may sweep is decided across processes by a |
| +// lock: |
| // - Every running edge holds a shared flock on staticLockName for its |
| // life. A starting edge sweeps only if it can take it exclusively. |
| -// - An edge from before this change takes no lock, so the first edge to |
| -// create the lock file sweeps nothing: from its next start on, every |
| -// edge using the cache is known to take the lock. That rests on the |
| +// - A running edge cannot ask that again without letting go of its own |
| +// hold, which flock(2) does on a refused conversion (Astra review of |
| +// this change). So every edge also holds a shared record lock on the |
| +// file's first byte (recordLock, Linux only), taken before its startup |
| +// check, and a running sweep converts that one to exclusive, which |
| +// either succeeds or leaves the shared lock as it was. Only an edge |
| +// whose startup check found it alone sweeps while running: an edge from |
| +// before the record lock holds only the flock. |
| +// - An edge from before the lock takes none, so the first edge to create |
| +// the lock file never sweeps, at start or later: from the next start on, |
| +// every edge using the cache is known to take the lock. That rests on the |
| // edge only running as carlos-edge.service, which systemd stops before |
| // it starts the next (Paul's ruling, 2026-10-25, on Astra round 3). |
| // - An edge that cannot hold the lock serves anyway and raises an ALERT |
| // (Paul's ruling, same day): a lock-file fault must not take static |
| // sites down, and the exposure needs a second edge starting beside it. |
| // |
| +// Inside the process, staticTrees says what the handlers need: a sweep |
| +// keeps every tree a live handler serves and leaves alone an app directory |
| +// a handler is choosing a tree in (begin). In each app it also keeps the |
| +// tree current names and the previous one, the newest other tree by mtime, |
| +// which pointCurrent sets when a tree becomes current, and every tree a |
| +// request is still being answered from (staticTrees.pin). |
| +// |
| // Only entries the edge itself made are touched, recognised by name: |
| // release trees (<version>@<digest>, siteDirName), temp extractions |
| // (.extract-<n>, os.MkdirTemp's) and an earlier sweep's leftovers |
| // (.sweep-<name>-<n>), under account and app directories whose names are |
| -// valid ones. Each app keeps the tree |
| -// its current link names. Every other release tree is renamed to a .sweep- |
| -// name before the sweep returns, so no handler built after it can select |
| -// it (ensureExtracted then extracts a fresh, verified copy if a pointer |
| -// names that version), and is removed in the background with the debris. |
| +// valid ones. Every release tree the sweep does not keep is renamed to a |
| +// .sweep- name while the sweep holds the app directory, so no handler can |
| +// select it afterwards (ensureExtracted then extracts a fresh, verified copy |
| +// if a pointer names that version), and is removed with the debris. |
| const staticLockName = ".edge.lock" |
| var ( |
| - siteTreeName = regexp.MustCompile(`^(.+)@[0-9a-f]{64}$`) |
| extractTmpName = regexp.MustCompile(`^\.extract-[0-9]+$`) |
| sweptName = regexp.MustCompile(`^\.sweep-.+-[0-9]+$`) |
| ) |
| @@ -70,21 +84,23 @@ func classifyStaticEntry(name string) staticEntry { |
| return entryUnknown |
| } |
| -// sweepStaticCache sweeps cacheDir if no other edge can be using it, and |
| -// returns this process's lock on it, held shared until the process exits |
| -// (nil when no lock could be held), and a channel closed once the |
| -// background removal is done. A lock it cannot hold is an ALERT, not a |
| -// refusal to serve: static sites stay up, and the only exposure is a second |
| -// edge starting beside this one while it serves. |
| -func sweepStaticCache(cacheDir string) (*os.File, <-chan struct{}) { |
| +// sweepStaticCache takes this process's lock on cacheDir, sweeps it if no |
| +// other edge can be using it, and returns the process's staticTrees (its |
| +// lock held shared until the process exits, nil when none could be held) |
| +// and a channel closed once the startup removal is done and the trees left |
| +// are measured. A lock it cannot hold is an ALERT, not a refusal to serve: |
| +// static sites stay up, and the only exposure is a second edge starting |
| +// beside this one while it serves. |
| +func sweepStaticCache(cacheDir string) (*staticTrees, <-chan struct{}) { |
| + t := newStaticTrees(cacheDir) |
| done := make(chan struct{}) |
| - fail := func(f *os.File, err error) (*os.File, <-chan struct{}) { |
| + fail := func(f *os.File, err error) (*staticTrees, <-chan struct{}) { |
| log.Printf("ALERT: edge: static cache %s: no lock held (%v): not swept, and a second edge starting beside this one could sweep trees it serves", cacheDir, err) |
| if f != nil { |
| f.Close() |
| } |
| - close(done) |
| - return nil, done |
| + go func() { defer close(done); t.measure() }() |
| + return t, done |
| } |
| if err := os.MkdirAll(cacheDir, 0o755); err != nil { |
| return fail(nil, err) |
| @@ -100,69 +116,151 @@ func sweepStaticCache(cacheDir string) (*os.File, <-chan struct{}) { |
| if err != nil { |
| return fail(nil, err) |
| } |
| + // Before the startup check, so a running edge's sweep sees this one |
| + // from here on. It waits out a sweep in progress, which is brief. |
| + recorded := recordLock(lock, true, true) == nil |
| fd := int(lock.Fd()) |
| - shared := func() error { |
| - var err error |
| - for range 5 { |
| - if err = syscall.Flock(fd, syscall.LOCK_SH); err == nil { |
| - return nil |
| - } |
| - time.Sleep(200 * time.Millisecond) |
| - } |
| - return err |
| + measured := func() (*staticTrees, <-chan struct{}) { |
| + t.lock = lock |
| + go func() { defer close(done); t.measure() }() |
| + return t, done |
| } |
| if first { |
| log.Printf("edge: static cache %s: first start with the lock; sweeping from the next start", cacheDir) |
| - if err := shared(); err != nil { |
| + if err := reshare(fd); err != nil { |
| return fail(lock, err) |
| } |
| - close(done) |
| - return lock, done |
| + return measured() |
| } |
| if err := syscall.Flock(fd, syscall.LOCK_EX|syscall.LOCK_NB); err != nil { |
| log.Printf("edge: static cache %s: another edge process serves from it; not swept this start", cacheDir) |
| - if err := shared(); err != nil { |
| + if err := reshare(fd); err != nil { |
| return fail(lock, err) |
| } |
| - close(done) |
| - return lock, done |
| + return measured() |
| } |
| - doomed := setAside(cacheDir) |
| - if err := shared(); err != nil { |
| + t.periodic = recorded |
| + doomed := setAside(t) |
| + if err := reshare(fd); err != nil { |
| return fail(lock, err) |
| } |
| + t.lock = lock |
| go func() { |
| defer close(done) |
| - removed := 0 |
| - for _, p := range doomed { |
| - if err := os.RemoveAll(p); err != nil { |
| - log.Printf("edge: static cache: remove %s: %v", p, err) |
| - continue |
| - } |
| - removed++ |
| - } |
| - if removed > 0 { |
| - log.Printf("edge: static cache %s: swept %d entr(ies) no app's current link names", cacheDir, removed) |
| + if removed := removeAll(doomed); removed > 0 { |
| + log.Printf("edge: static cache %s: swept %d entr(ies) at start", cacheDir, removed) |
| } |
| + t.measure() |
| }() |
| - return lock, done |
| + return t, done |
| +} |
| + |
| +// reshare takes (or takes back) the process's shared hold on the lock. |
| +func reshare(fd int) error { |
| + var err error |
| + for range 5 { |
| + if err = syscall.Flock(fd, syscall.LOCK_SH); err == nil { |
| + return nil |
| + } |
| + time.Sleep(200 * time.Millisecond) |
| + } |
| + return err |
| +} |
| + |
| +func removeAll(doomed []string) int { |
| + removed := 0 |
| + for _, p := range doomed { |
| + if err := os.RemoveAll(p); err != nil { |
| + log.Printf("edge: static cache: remove %s: %v", p, err) |
| + continue |
| + } |
| + removed++ |
| + } |
| + return removed |
| +} |
| + |
| +// sweepCache is a running edge's sweep: only while no other edge holds the |
| +// record lock, and only if this edge's startup check found it alone. It |
| +// reports how many entries it removed. |
| +func (t *staticTrees) sweepCache() int { |
| + if t.lock == nil || !t.periodic { |
| + return 0 |
| + } |
| + if err := recordLock(t.lock, false, false); err != nil { |
| + log.Printf("edge: static cache %s: another edge process serves from it; not swept (%v)", t.cacheDir, err) |
| + return 0 |
| + } |
| + doomed := setAside(t) |
| + if err := recordLock(t.lock, true, false); err != nil { |
| + log.Printf("ALERT: edge: static cache %s: record lock not made shared again (%v): no other edge can start a sweep check until this one exits", t.cacheDir, err) |
| + } |
| + return removeAll(doomed) |
| } |
| // setAside renames, in every <acct>/<app> directory, each release tree the |
| -// current link does not name to a .sweep- name, and returns those paths and |
| -// the edge's debris for removal. It touches nothing it does not recognise. |
| -func setAside(cacheDir string) []string { |
| +// sweep does not keep to a .sweep- name, and returns those paths and the |
| +// edge's debris for removal. It holds t.mu for each app directory, so no |
| +// handler can begin choosing a tree there meanwhile, and skips a directory |
| +// a handler is already choosing in. It touches nothing it does not |
| +// recognise. |
| +func setAside(t *staticTrees) []string { |
| var doomed []string |
| - accts, err := os.ReadDir(cacheDir) |
| + accts, err := os.ReadDir(t.cacheDir) |
| if err != nil { |
| return nil |
| } |
| stamp := time.Now().UnixNano() |
| + app := func(appDir string) []string { |
| + t.mu.Lock() |
| + defer t.mu.Unlock() |
| + keep, busy := t.keepLocked(appDir) |
| + if busy { |
| + return nil |
| + } |
| + cur, _ := os.Readlink(filepath.Join(appDir, "current")) |
| + names, err := os.ReadDir(appDir) |
| + if err != nil { |
| + return nil |
| + } |
| + var trees, doomed []string |
| + var prev string |
| + var prevAt time.Time |
| + for _, n := range names { |
| + name := n.Name() |
| + path := filepath.Join(appDir, name) |
| + fi, err := os.Lstat(path) |
| + if err != nil || !fi.IsDir() || name == cur { |
| + continue |
| + } |
| + switch classifyStaticEntry(name) { |
| + case entryDebris: |
| + doomed = append(doomed, path) |
| + case entryTree: |
| + trees = append(trees, name) |
| + if prev == "" || fi.ModTime().After(prevAt) { |
| + prev, prevAt = name, fi.ModTime() |
| + } |
| + } |
| + } |
| + for _, name := range trees { |
| + if name == prev || keep[name] { |
| + continue |
| + } |
| + path := filepath.Join(appDir, name) |
| + to := filepath.Join(appDir, fmt.Sprintf(".sweep-%s-%d", name, stamp)) |
| + if err := os.Rename(path, to); err != nil { |
| + log.Printf("edge: static cache: set aside %s: %v", path, err) |
| + continue |
| + } |
| + doomed = append(doomed, to) |
| + } |
| + return doomed |
| + } |
| for _, a := range accts { |
| if !a.IsDir() || !release.ValidAccount(a.Name()) { |
| continue |
| } |
| - apps, err := os.ReadDir(filepath.Join(cacheDir, a.Name())) |
| + apps, err := os.ReadDir(filepath.Join(t.cacheDir, a.Name())) |
| if err != nil { |
| continue |
| } |
| @@ -170,34 +268,7 @@ func setAside(cacheDir string) []string { |
| if !ap.IsDir() || !release.ValidApp(ap.Name()) { |
| continue |
| } |
| - appDir := filepath.Join(cacheDir, a.Name(), ap.Name()) |
| - cur, _ := os.Readlink(filepath.Join(appDir, "current")) |
| - names, err := os.ReadDir(appDir) |
| - if err != nil { |
| - continue |
| - } |
| - for _, n := range names { |
| - name := n.Name() |
| - path := filepath.Join(appDir, name) |
| - if name == cur { |
| - continue |
| - } |
| - fi, err := os.Lstat(path) |
| - if err != nil || !fi.IsDir() { |
| - continue |
| - } |
| - switch classifyStaticEntry(name) { |
| - case entryDebris: |
| - doomed = append(doomed, path) |
| - case entryTree: |
| - to := filepath.Join(appDir, fmt.Sprintf(".sweep-%s-%d", name, stamp)) |
| - if err := os.Rename(path, to); err != nil { |
| - log.Printf("edge: static cache: set aside %s: %v", path, err) |
| - continue |
| - } |
| - doomed = append(doomed, to) |
| - } |
| - } |
| + doomed = append(doomed, app(filepath.Join(t.cacheDir, a.Name(), ap.Name()))...) |
| } |
| } |
| return doomed |
diff --git a/internal/edge/static_trees.go b/internal/edge/static_trees.go| new file mode 100644 |
| index 000000000..62da41eb3 |
| --- /dev/null |
| +++ b/internal/edge/static_trees.go |
| @@ -0,0 +1,274 @@ |
| +package edge |
| + |
| +import ( |
| + "io/fs" |
| + "log" |
| + "os" |
| + "path/filepath" |
| + "regexp" |
| + "sync" |
| + "sync/atomic" |
| + "time" |
| + "weak" |
| +) |
| + |
| +// siteTreeName is a release tree's directory name: siteDirName's |
| +// <version>@<digest>. |
| +var siteTreeName = regexp.MustCompile(`^(.+)@[0-9a-f]{64}$`) |
| + |
| +// staticTrees is one edge process's record of the extracted static trees |
| +// under its cache directory: which ones its handlers serve, which app |
| +// directories a handler is choosing a tree in right now, and how big the |
| +// trees it keeps are. The sweep (static_sweep_unix.go) reads it to know |
| +// what it must not touch; the disk alert reads Largest. |
| +// |
| +// The startup sweep alone let annie-welding fill to the cold-wake floor on |
| +// 2026-11-08: carlos-edge ran for a day while eight 2.6 GB apt releases |
| +// shipped. A running edge therefore sweeps again after every swap a handler |
| +// makes (a deploy or promote reaching this box) and every staticSweepEvery. |
| +type staticTrees struct { |
| + cacheDir string |
| + // lock is this process's shared hold on <cacheDir>/.edge.lock, nil when |
| + // none could be held. periodic is whether this process may sweep after |
| + // startup: only when the lock file was already there at start, so every |
| + // edge that can be using the cache is known to take the lock. |
| + lock *os.File |
| + periodic bool |
| + |
| + mu sync.Mutex |
| + // sites are the handlers this edge has built. Weak: a handler the route |
| + // table dropped, with no request still holding it, goes away by itself. |
| + sites []weak.Pointer[staticSite] |
| + // busy counts, per app directory, the handlers choosing a tree there |
| + // (begin). The sweep leaves such a directory alone. |
| + busy map[string]int |
| + // pins counts, per tree path, the requests being answered from it |
| + // (pin): a handler that has swapped since no longer names their tree. |
| + pins map[string]int |
| + // sizes caches each kept tree's byte count by path: a tree never changes |
| + // once extracted. |
| + sizes map[string]int64 |
| + largest atomic.Int64 |
| + |
| + kick chan struct{} |
| +} |
| + |
| +// staticSweepEvery is how often a running edge sweeps without a swap to |
| +// prompt it, and staticSweepSettle how long it waits after a swap, so a |
| +// burst of deploys costs one sweep. |
| +const ( |
| + staticSweepEvery = time.Hour |
| + staticSweepSettle = 30 * time.Second |
| +) |
| + |
| +func newStaticTrees(cacheDir string) *staticTrees { |
| + return &staticTrees{ |
| + cacheDir: cacheDir, |
| + busy: map[string]int{}, |
| + pins: map[string]int{}, |
| + sizes: map[string]int64{}, |
| + kick: make(chan struct{}, 1), |
| + } |
| +} |
| + |
| +// register records a handler this edge built. |
| +func (t *staticTrees) register(s *staticSite) { |
| + if t == nil { |
| + return |
| + } |
| + t.mu.Lock() |
| + defer t.mu.Unlock() |
| + if len(t.sites) >= 64 && len(t.sites)%64 == 0 { |
| + t.pruneLocked() |
| + } |
| + t.sites = append(t.sites, weak.Make(s)) |
| +} |
| + |
| +func (t *staticTrees) pruneLocked() { |
| + live := t.sites[:0] |
| + for _, w := range t.sites { |
| + if w.Value() != nil { |
| + live = append(live, w) |
| + } |
| + } |
| + clear(t.sites[len(live):]) |
| + t.sites = live |
| +} |
| + |
| +// begin marks a handler choosing a tree in appDir: from its check of what is |
| +// on disk to its swap of current and the record of what it serves. The |
| +// returned func ends it. |
| +func (t *staticTrees) begin(appDir string) func() { |
| + if t == nil { |
| + return func() {} |
| + } |
| + t.mu.Lock() |
| + t.busy[appDir]++ |
| + t.mu.Unlock() |
| + return func() { |
| + t.mu.Lock() |
| + if t.busy[appDir]--; t.busy[appDir] <= 0 { |
| + delete(t.busy, appDir) |
| + } |
| + t.mu.Unlock() |
| + } |
| +} |
| + |
| +// pin holds the tree at path out of every sweep until the returned func |
| +// is called. A handler pins while it holds its own lock, so the tree is |
| +// one it still names when the pin is taken. |
| +func (t *staticTrees) pin(path string) func() { |
| + if t == nil { |
| + return func() {} |
| + } |
| + t.mu.Lock() |
| + t.pins[path]++ |
| + t.mu.Unlock() |
| + var once sync.Once |
| + return func() { |
| + once.Do(func() { |
| + t.mu.Lock() |
| + if t.pins[path]--; t.pins[path] <= 0 { |
| + delete(t.pins, path) |
| + } |
| + t.mu.Unlock() |
| + }) |
| + } |
| +} |
| + |
| +// swapped asks for a sweep: a handler has just moved to another tree. |
| +func (t *staticTrees) swapped() { |
| + if t == nil { |
| + return |
| + } |
| + select { |
| + case t.kick <- struct{}{}: |
| + default: |
| + } |
| +} |
| + |
| +// keepLocked is what the sweep must leave in appDir besides current and |
| +// previous: every tree a live handler serves there and every tree a request |
| +// is being answered from. The caller holds mu, and a busy directory is not |
| +// swept at all. |
| +func (t *staticTrees) keepLocked(appDir string) (keep map[string]bool, busy bool) { |
| + if t.busy[appDir] > 0 { |
| + return nil, true |
| + } |
| + keep = map[string]bool{} |
| + for _, w := range t.sites { |
| + s := w.Value() |
| + if s == nil || s.appDir() != appDir { |
| + continue |
| + } |
| + if name := s.serving.Load(); name != nil { |
| + keep[*name] = true |
| + } |
| + } |
| + for p := range t.pins { |
| + if filepath.Dir(p) == appDir { |
| + keep[filepath.Base(p)] = true |
| + } |
| + } |
| + return keep, false |
| +} |
| + |
| +// Largest is the byte count of the largest tree the last sweep kept, 0 |
| +// before one has measured. |
| +func (t *staticTrees) Largest() int64 { |
| + if t == nil { |
| + return 0 |
| + } |
| + return t.largest.Load() |
| +} |
| + |
| +// measure sizes every release tree left in the cache, reusing the count of |
| +// a tree it has measured before. |
| +func (t *staticTrees) measure() { |
| + seen := map[string]bool{} |
| + var largest int64 |
| + accts, _ := os.ReadDir(t.cacheDir) |
| + for _, a := range accts { |
| + if !a.IsDir() { |
| + continue |
| + } |
| + apps, _ := os.ReadDir(filepath.Join(t.cacheDir, a.Name())) |
| + for _, ap := range apps { |
| + if !ap.IsDir() { |
| + continue |
| + } |
| + appDir := filepath.Join(t.cacheDir, a.Name(), ap.Name()) |
| + names, _ := os.ReadDir(appDir) |
| + for _, n := range names { |
| + if !n.IsDir() || !siteTreeName.MatchString(n.Name()) { |
| + continue |
| + } |
| + p := filepath.Join(appDir, n.Name()) |
| + seen[p] = true |
| + t.mu.Lock() |
| + size, ok := t.sizes[p] |
| + t.mu.Unlock() |
| + if !ok { |
| + size = treeBytes(p) |
| + t.mu.Lock() |
| + t.sizes[p] = size |
| + t.mu.Unlock() |
| + } |
| + largest = max(largest, size) |
| + } |
| + } |
| + } |
| + t.mu.Lock() |
| + for p := range t.sizes { |
| + if !seen[p] { |
| + delete(t.sizes, p) |
| + } |
| + } |
| + t.mu.Unlock() |
| + t.largest.Store(largest) |
| +} |
| + |
| +// treeBytes is the total size of the regular files under dir. |
| +func treeBytes(dir string) int64 { |
| + var n int64 |
| + _ = filepath.WalkDir(dir, func(_ string, d fs.DirEntry, err error) error { |
| + if err != nil { |
| + return nil |
| + } |
| + if d.Type().IsRegular() { |
| + if fi, err := d.Info(); err == nil { |
| + n += fi.Size() |
| + } |
| + } |
| + return nil |
| + }) |
| + return n |
| +} |
| + |
| +// run sweeps after each swap (once the burst settles) and every |
| +// staticSweepEvery, for the life of the process. |
| +func (t *staticTrees) run(every, settle time.Duration) { |
| + tick := time.NewTicker(every) |
| + defer tick.Stop() |
| + for { |
| + select { |
| + case <-t.kick: |
| + time.Sleep(settle) |
| + select { |
| + case <-t.kick: |
| + default: |
| + } |
| + case <-tick.C: |
| + } |
| + t.sweepOnce() |
| + } |
| +} |
| + |
| +// sweepOnce sets aside and removes what no handler needs (sweepCache, per |
| +// platform), then measures what is left. |
| +func (t *staticTrees) sweepOnce() { |
| + if removed := t.sweepCache(); removed > 0 { |
| + log.Printf("edge: static cache %s: swept %d entr(ies) no handler serves", t.cacheDir, removed) |
| + } |
| + t.measure() |
| +} |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 3af68c137..5dd252a99 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -1227,6 +1227,7 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| geoIPSource.Store(e.GeoIPState) |
| heldStreamsSource.Store(e.HeldStreamsForStatus) |
| geoIPAlertSource.Store(e.GeoIPAlertCode) |
| + staticTreeSource.Store(e.LargestStaticTree) |
| // 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() } |
| @@ -4601,6 +4602,19 @@ var geoIPAlertSource atomic.Value // func(time.Time) (float64, bool) |
| // geoIPAlertReading is the rule's reading, or nil before the edge is ready |
| // (no data never fires and never clears). |
| +// staticTreeSource is the edge's Edge.LargestStaticTree, published once the |
| +// edge exists, for the disk rule's line (diskAlertFrac). |
| +var staticTreeSource atomic.Value // func() int64 |
| + |
| +// largestStaticTree reads it, 0 before the edge is ready. |
| +func largestStaticTree() int64 { |
| + fn, _ := staticTreeSource.Load().(func() int64) |
| + if fn == nil { |
| + return 0 |
| + } |
| + return fn() |
| +} |
| + |
| func geoIPAlertReading(now time.Time) *float64 { |
| fn, _ := geoIPAlertSource.Load().(func(time.Time) (float64, bool)) |
| if fn == nil { |
diff --git a/internal/host/diskalertline_test.go b/internal/host/diskalertline_test.go| new file mode 100644 |
| index 000000000..0442ee836 |
| --- /dev/null |
| +++ b/internal/host/diskalertline_test.go |
| @@ -0,0 +1,74 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// The disk rule's default line, 90 percent, is the cold-wake floor itself |
| +// on any disk over 10 GiB (instancectl.DiskFloor), so on 2026-11-08 annie's |
| +// alert and its refused wakes began together. The line now leaves room |
| +// above the floor for two of the box's largest static trees: one being |
| +// extracted while the previous is still kept. |
| +func TestDiskAlertFracLeavesRoomForTwoStaticTrees(t *testing.T) { |
| + total := uint64(59 * gib) |
| + floor := instancectl.DiskFloor(total) |
| + tree := int64(26 * gib / 10) |
| + got := diskAlertFrac(0.90, total, tree) |
| + want := 1 - float64(floor+2*uint64(tree))/float64(total) |
| + if got != want { |
| + t.Fatalf("line = %v, want %v", got, want) |
| + } |
| + // annie at 02:31Z: 5.4 GiB free, already under the floor. The line |
| + // fires well before that: at 11 GiB free. |
| + if free := float64(total) * (1 - got) / float64(gib); free < 11 || free > 11.2 { |
| + t.Errorf("fires at %.1f GiB free, want about 11.1", free) |
| + } |
| + // A lower configured line stays. |
| + if got := diskAlertFrac(0.50, total, tree); got != 0.50 { |
| + t.Errorf("configured 0.50 became %v", got) |
| + } |
| + // On a small disk the 1 GiB floor is above 10 percent: the line moves |
| + // down to it, so the alert never comes after the refusals. |
| + if got, want := diskAlertFrac(0.90, 8*gib, 0), 1-float64(gib)/float64(8*gib); got != want { |
| + t.Errorf("8 GiB disk: line = %v, want %v", got, want) |
| + } |
| + // No reading of the disk's size leaves the configured line. |
| + if got := diskAlertFrac(0.90, 0, tree); got != 0.90 { |
| + t.Errorf("no total: line = %v", got) |
| + } |
| + // A disk that cannot hold the floor and two trees is always alerting. |
| + if got := diskAlertFrac(0.90, 10*gib, int64(5*gib)); got != 0 { |
| + t.Errorf("tiny disk: line = %v, want 0", got) |
| + } |
| +} |
| + |
| +// Through alertTick: annie's 2026-11-08 reading an hour before the |
| +// refusals, 82 percent used with 2.6 GiB apt trees, fires the disk rule; |
| +// with no static trees it does not. |
| +func TestAlertTickFiresDiskBeforeTheColdWakeFloor(t *testing.T) { |
| + ctx := context.Background() |
| + used := 0.82 |
| + at := time.Date(2026, 11, 8, 1, 30, 0, 0, time.UTC) |
| + latest := metrics.Sample{At: at, Host: metrics.HostSample{DiskFrac: &used}} |
| + for _, c := range []struct { |
| + tree int64 |
| + want bool |
| + }{{int64(26 * gib / 10), true}, {0, false}} { |
| + s := release.NewDirStore(t.TempDir()) |
| + st := &metrics.AlertState{V: 1, Box: "annie", Rules: map[string]metrics.RuleState{}} |
| + extra := alertReadings{diskTotal: 59 * gib, staticTree: c.tree} |
| + if err := alertTick(ctx, s, "annie", metrics.DefaultRules(), st, latest, extra, filepath.Join(t.TempDir(), "alerts.json"), nil, nil, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := st.Rules["disk"].Firing; got != c.want { |
| + t.Errorf("static tree %d bytes: disk firing = %v, want %v", c.tree, got, c.want) |
| + } |
| + } |
| +} |
diff --git a/internal/host/metrics_loop.go b/internal/host/metrics_loop.go| index 5ded8ff68..3023811df 100644 |
| --- a/internal/host/metrics_loop.go |
| +++ b/internal/host/metrics_loop.go |
| @@ -12,6 +12,7 @@ import ( |
| "context" |
| "encoding/json" |
| "errors" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| "log" |
| "os" |
| "path/filepath" |
| @@ -533,6 +534,7 @@ func alertTick(ctx context.Context, s release.Store, box string, rules metrics.R |
| st *metrics.AlertState, latest metrics.Sample, extra alertReadings, statePath string, |
| sinks *alertSinks, trend *diskTrend, beat *engineBeatWatch) error { |
| + rules.DiskFrac = diskAlertFrac(rules.DiskFrac, extra.diskTotal, extra.staticTree) |
| obs := metrics.Observation{ |
| At: latest.At, |
| CPUFrac: latest.Host.CPUFrac, |
| @@ -600,6 +602,29 @@ func alertTick(ctx context.Context, s release.Store, box string, rules metrics.R |
| // leaves every rule they feed exactly as it was. |
| type alertReadings struct { |
| restarts map[string]metrics.UnitRestarts // see restartWatch.tick |
| + // diskTotal is the data disk's size and staticTree the largest static |
| + // tree the edge keeps (Edge.LargestStaticTree): the disk rule's line is |
| + // lowered to leave room for two trees above the cold-wake floor |
| + // (diskAlertFrac). Zero total leaves the configured line. |
| + diskTotal uint64 |
| + staticTree int64 |
| +} |
| + |
| +// diskAlertFrac is the disk rule's line on a disk of total bytes: the |
| +// configured one, or lower, so the rule fires while the box still has |
| +// instancectl.DiskFloor free plus room for two of its largest static trees |
| +// (a release being extracted while the previous one is kept). The default |
| +// line, 90 percent, is the floor itself on any disk over 10 GiB, so on |
| +// 2026-11-08 annie's alert and its refused cold wakes began together. |
| +func diskAlertFrac(configured float64, total uint64, staticTree int64) float64 { |
| + if total == 0 { |
| + return configured |
| + } |
| + room := instancectl.DiskFloor(total) + 2*uint64(max(staticTree, 0)) |
| + if room >= total { |
| + return 0 |
| + } |
| + return min(configured, 1-float64(room)/float64(total)) |
| } |
| // persistAlertState writes st to path as indented JSON via the repo's |
| @@ -932,6 +957,9 @@ func metricsLoop(execRoot string, src unitSources, owners func() map[string]metr |
| restarts := watchFile.load() |
| restartTick := func(at time.Time) alertReadings { |
| extra := alertReadings{restarts: restarts.tick(at, probes.restarts())} |
| + if _, total, ok := probes.diskBytes(); ok { |
| + extra.diskTotal, extra.staticTree = total, largestStaticTree() |
| + } |
| if err := watchFile.save(restarts); err != nil { |
| log.Printf("agent: restart watch: save %s: %v", watchFile.path, err) |
| } |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index e036b3fc3..74904f782 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -122,3 +122,4 @@ plan14-root-reads-dr1-left-link.tsv 160744b3062d0ab9a0cb3c7be3a391ae38cf89ffe410 |
| plan14-root-reads-claim-source.tsv 9cdff432a5de2ffeaa147fdafd6a486c61c27a0c38f77466bddc86b149332c7d |
| plan14-root-reads-region-ha-graceful-terminate-t1.tsv 3273ecae03559a8d450027f4cdf4dff24af9c54705231bc4f7c77b72582b517c |
| plan14-root-reads-region-ha-graceful-terminate-t2.tsv 687cf7744aecdf8a238dcdb80562b0ef191b3e247c28851de44c01866dbeca13 |
| +plan14-root-reads-static-sweep-periodic.tsv 3dc3f6657527133a251c028772315bdd333b04c318fbbc6d90ef5047f15408ed |
diff --git a/internal/provision/testdata/plan14-root-reads-static-sweep-periodic.tsv b/internal/provision/testdata/plan14-root-reads-static-sweep-periodic.tsv| new file mode 100644 |
| index 000000000..a2f390281 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-static-sweep-periodic.tsv |
| @@ -0,0 +1,16 @@ |
| +# Census overlay static-sweep-periodic, written by census-propose (#369). census-ruling-static-sweep-periodic, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-static-sweep-periodic.md. |
| +# 4 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 2 new dispositions: 0 reads re-frozen at their disposition with the claim, 2 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| +@legacy 0d9c034567835848ee11da27eaa6b63532ceeb8a539c352aa210d434e255cade internal/edge/edge.go Edge.staticHandlerFor legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-devbox-mode;basis=devbox mode (#474): when WithLocalStatic set localStaticRoot (only edge.ServeDevbox sets it, run by carlos devbox serve as the unprivileged carlos-devbox user), a static route is handed to newLocalStaticHandler instead of the release store. Reads the same Route (its App) as before; with the root unset the store path is byte-for-byte unchanged. No new read;rev3=census-ruling-static-sweep-periodic;basis=hands each static handler the process staticTrees record (ss.trees) and registers it there (weak pointer); in-memory wiring only, no read added; read sites unchanged (3) registry:App@334,whole:Route@255,whole:Route@524 15d034f2a1a1b0d6c852dc2d95e236c6a1223da02b26e8a28aedac358ba880ad |
| +@legacy 6f88cc678942860fe509aa45f860e26c595fefbaa5c545ae5c288de714b447ab internal/edge/static_sweep_unix.go setAside legacy accepted-legacy accepted-legacy;rev3=census-ruling-static-sweep;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=root-input; once at startup, before any static handler exists, only under an exclusive flock (sweepStaticCache), reads its own static cache (<cacheDir>/<acct>/<app> with valid account and app names: entries, each current link, each entry lstat) and renames each release tree (<version>@<64-hex digest>) the current link does not name to a .sweep- name for removal, with its own debris (.extract-<n>, .sweep-<name>-<n>); never touches files, links, bare names, or names it does not recognise; every tree is a cache of a signed release that ensureExtracted re-verifies before extracting it again; no root decision;rev3=census-ruling-static-sweep-periodic;basis=same walk of <cacheDir>/<acct>/<app> with valid account and app names, same current-link read, lstat and recognised names (release trees, .extract-, .sweep- debris; never files, links, bare or unknown names); now under the process tracker mutex per app dir, skipping a dir a handler is choosing a tree in, and keeping the previous tree (newest other by mtime), trees live handlers serve and trees requests hold, besides current; run at startup (exclusive flock) and by a running sweep (exclusive record lock); the agent, not root file:Lstat@607,file:ReadDir@1429,file:ReadDir@381,file:ReadDir@77,file:Readlink@319 d97bbd3bd80cecbbf742ba69e918dc86b9e8dc2e92ca449f3ed8fd3aa71d43ce |
| +@legacy 959347925e5800cc5da3bc49b372da9ebc437202ae8f3d7c7660f674ea2875f9 internal/edge/static_sweep_unix.go sweepStaticCache legacy accepted-legacy accepted-legacy;rev3=census-ruling-static-sweep;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=root-input; opens or creates <cacheDir>/.edge.lock and flocks it: a start that creates it sweeps nothing (an older edge may not lock; systemd stops an edge before it starts the next, Paul 2026-10-25), otherwise exclusive non-blocking to sweep, then shared for the process life; a lock it cannot hold is an ALERT and the edge still serves (Paul 2026-10-25); the lock decides only whether this start sweeps; no root decision;rev3=census-ruling-static-sweep-periodic;basis=same startup flock protocol on <cacheDir>/.edge.lock (the same two OpenFile calls); now also takes a shared OFD record lock on byte 0 of that file before the startup check, returns the process staticTrees record (lock, periodic flag) and measures the kept trees after the startup removal; a running edge sweeps later through the same setAside under an exclusive record lock; the agent (carlos-edge.service, user carlos), not root; its own static cache only file:OpenFile@628,file:OpenFile@773 267bd955bcf877944008ee845e982639a5142e4ff68b8bc88ec551282b8cf46e |
| +@legacy eefa3bd21175177cce68b954a56f77a2e246085086a9f3282a2a5902b49a1d98 internal/edge/static_trees.go staticTrees.measure legacy accepted-legacy accepted-legacy;rev3=census-ruling-static-sweep-periodic;basis=new: lists the agent own static cache (<cacheDir>/<acct>/<app>/<version>@<digest>) to size the kept trees for the disk alert; reads only, removes nothing; the agent, not root file:ReadDir@190,file:ReadDir@379,file:ReadDir@93 a2b1b3094abf48221682fd9f0200c64cc19788beca4c59c03e2fad9504f84175 |
| +@legacy 3f1fce4b3f378bed81741c94e47eecd3aac3e882a26fedec3d387e3247776caa internal/edge/static_trees.go treeBytes legacy accepted-legacy accepted-legacy;rev3=census-ruling-static-sweep-periodic;basis=new: WalkDir of one extracted static tree summing regular-file sizes (no symlink follow, no file contents) for measure; reads only; the agent, not root file:WalkDir@53 1c1b3cbcc45822d6b0a60e82dcaa222b85cde71e7ad7ffe4b1cfb0e53685b800 |
| +internal/edge/edge.go Edge.staticHandlerFor legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-devbox-mode;basis=devbox mode (#474): when WithLocalStatic set localStaticRoot (only edge.ServeDevbox sets it, run by carlos devbox serve as the unprivileged carlos-devbox user), a static route is handed to newLocalStaticHandler instead of the release store. Reads the same Route (its App) as before; with the root unset the store path is byte-for-byte unchanged. No new read;rev3=census-ruling-static-sweep-periodic;basis=hands each static handler the process staticTrees record (ss.trees) and registers it there (weak pointer); in-memory wiring only, no read added; read sites unchanged (3) registry:App@334,whole:Route@255,whole:Route@524 15d034f2a1a1b0d6c852dc2d95e236c6a1223da02b26e8a28aedac358ba880ad |
| +internal/edge/static_sweep_unix.go setAside legacy accepted-legacy accepted-legacy;rev3=census-ruling-static-sweep;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=root-input; once at startup, before any static handler exists, only under an exclusive flock (sweepStaticCache), reads its own static cache (<cacheDir>/<acct>/<app> with valid account and app names: entries, each current link, each entry lstat) and renames each release tree (<version>@<64-hex digest>) the current link does not name to a .sweep- name for removal, with its own debris (.extract-<n>, .sweep-<name>-<n>); never touches files, links, bare names, or names it does not recognise; every tree is a cache of a signed release that ensureExtracted re-verifies before extracting it again; no root decision;rev3=census-ruling-static-sweep-periodic;basis=same walk of <cacheDir>/<acct>/<app> with valid account and app names, same current-link read, lstat and recognised names (release trees, .extract-, .sweep- debris; never files, links, bare or unknown names); now under the process tracker mutex per app dir, skipping a dir a handler is choosing a tree in, and keeping the previous tree (newest other by mtime), trees live handlers serve and trees requests hold, besides current; run at startup (exclusive flock) and by a running sweep (exclusive record lock); the agent, not root file:Lstat@607,file:ReadDir@1429,file:ReadDir@381,file:ReadDir@77,file:Readlink@319 d97bbd3bd80cecbbf742ba69e918dc86b9e8dc2e92ca449f3ed8fd3aa71d43ce |
| +internal/edge/static_sweep_unix.go sweepStaticCache legacy accepted-legacy accepted-legacy;rev3=census-ruling-static-sweep;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=root-input; opens or creates <cacheDir>/.edge.lock and flocks it: a start that creates it sweeps nothing (an older edge may not lock; systemd stops an edge before it starts the next, Paul 2026-10-25), otherwise exclusive non-blocking to sweep, then shared for the process life; a lock it cannot hold is an ALERT and the edge still serves (Paul 2026-10-25); the lock decides only whether this start sweeps; no root decision;rev3=census-ruling-static-sweep-periodic;basis=same startup flock protocol on <cacheDir>/.edge.lock (the same two OpenFile calls); now also takes a shared OFD record lock on byte 0 of that file before the startup check, returns the process staticTrees record (lock, periodic flag) and measures the kept trees after the startup removal; a running edge sweeps later through the same setAside under an exclusive record lock; the agent (carlos-edge.service, user carlos), not root; its own static cache only file:OpenFile@628,file:OpenFile@773 267bd955bcf877944008ee845e982639a5142e4ff68b8bc88ec551282b8cf46e |
| +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) file:Exec@19204,file:Open@1707,file:Statfs@50476,registry:App@12803,registry:Host@46512,whole:Route@12795,whole:Route@45670,whole:Route@46635,whole:Route@46697 25fc7ebec660b0041c86b9bcf2263f411d610480292bed81ba43ba4f7e143505 |
| +internal/edge/static_trees.go staticTrees.measure legacy accepted-legacy accepted-legacy;rev3=census-ruling-static-sweep-periodic;basis=new: lists the agent own static cache (<cacheDir>/<acct>/<app>/<version>@<digest>) to size the kept trees for the disk alert; reads only, removes nothing; the agent, not root file:ReadDir@190,file:ReadDir@379,file:ReadDir@93 a2b1b3094abf48221682fd9f0200c64cc19788beca4c59c03e2fad9504f84175 |
| +internal/edge/static_trees.go treeBytes legacy accepted-legacy accepted-legacy;rev3=census-ruling-static-sweep-periodic;basis=new: WalkDir of one extracted static tree summing regular-file sizes (no symlink follow, no file contents) for measure; reads only; the agent, not root file:WalkDir@53 1c1b3cbcc45822d6b0a60e82dcaa222b85cde71e7ad7ffe4b1cfb0e53685b800 |
| +@coverage internal/edge 305a4431c33e88a673306639121feee5413f9989426c1cd0b690c3ed687b523d |
| +@coverage internal/host 9e7626784f7b6d99980d4037f949e1fe8f999a51063a4779b2551051dcc43b7b |