From e01b93fc34735e6d0436bbf82dc19839aa53ab0f Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Tue, 24 Nov 2026 01:10:30 -0600 Subject: [PATCH 1/3] fix(pm-stack): cut over quota and feed timers --- doc/fleet-schedule-registry.md | 12 +- nixos/services/pm-stack/default.nix | 55 ++++---- pm-stack/aggregator/install.sh | 31 ++--- pm-stack/aggregator/scripts/age-feed-drill.sh | 29 +++-- .../scripts/kill-collector-drill.sh | 92 +++++++------ pm-stack/aggregator/src/pm-core-jobs.ts | 43 ------ pm-stack/aggregator/src/pm-core-scheduler.ts | 23 +++- pm-stack/aggregator/src/pm-core-wiring.ts | 26 +++- pm-stack/aggregator/src/server.ts | 21 +-- .../aggregator/systemd/quota-gatherer.timer | 11 -- .../aggregator/test/age-feed-drill.test.ts | 28 ++-- pm-stack/aggregator/test/install-rehearsal.sh | 6 + .../test/kill-collector-drill.test.ts | 104 ++++++++++----- .../aggregator/test/pm-core-scheduler.test.ts | 17 +++ .../aggregator/test/pm-core-wiring.test.ts | 122 +++++++++++++++++- pm-stack/scripts/deploy-install-smoke.test.sh | 1 - 16 files changed, 400 insertions(+), 221 deletions(-) delete mode 100644 pm-stack/aggregator/src/pm-core-jobs.ts delete mode 100644 pm-stack/aggregator/systemd/quota-gatherer.timer diff --git a/doc/fleet-schedule-registry.md b/doc/fleet-schedule-registry.md index 6da50e9932..29235d77cb 100644 --- a/doc/fleet-schedule-registry.md +++ b/doc/fleet-schedule-registry.md @@ -379,7 +379,7 @@ The OS-timer half of surface 2. Cadence is the unit's own `OnCalendar`/`OnUnitAc | `cold-store-drill.timer` | `OnCalendar=*-*-01 05:12:00` | `cold-store-drill.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `cold-store-nightly.timer` | `OnCalendar=*-*-* 03:12:00` | `cold-store-nightly.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `dashboard-backup.timer` | `OnCalendar=*-*-* 04:30:00` | `dashboard-backup.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | -| `fleet-feed-collector.timer` | `OnUnitActiveUSec=5min,OnBootUSec=2min` | `fleet-feed-collector.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | +| `fleet-feed-collector.timer` (retirement pending deployment) | `OnUnitActiveUSec=5min,OnBootUSec=2min` | `fleet-feed-collector.service` | laptop (user systemd; source retired by #8570, live disable not verified) | not recorded | not recorded | not recorded | 2026-11-24 | | `git-maintenance@daily.timer` | `OnCalendar=Tue..Sun *-*-* 00:56:00` | `git-maintenance@daily.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `git-maintenance@hourly.timer` | `OnCalendar=*-*-* 01..23:56:00` | `git-maintenance@hourly.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `git-maintenance@weekly.timer` | `OnCalendar=Mon *-*-* 00:56:00` | `git-maintenance@weekly.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | @@ -417,7 +417,7 @@ The OS-timer half of surface 2. Cadence is the unit's own `OnCalendar`/`OnUnitAc | `pm-kaneo-sync-guard.timer` | `OnCalendar=*-*-* *:00:00` | `pm-kaneo-sync-guard.service` | laptop (user systemd) | not recorded | not recorded | 2026-11-14 | 2026-11-15 | | `pm-projector-reconcile.timer` | `OnCalendar=*-*-* *:00/15:00` | `pm-projector-reconcile.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `pm-tunnel-watchdog.timer` (Nix-configured; not yet loaded) | `OnUnitActiveSec=2min,OnBootSec=2min` (not live-verified) | `pm-tunnel-watchdog.service` | laptop (user systemd) | not recorded | not recorded | 2026-11-11 | 2026-11-11 | -| `quota-gatherer.timer` | `OnCalendar=*-*-* *:00/15:00` | `quota-gatherer.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-22 | +| `quota-gatherer.timer` (retirement pending deployment) | `OnCalendar=*-*-* *:00/15:00` | `quota-gatherer.service` | laptop (user systemd; source retired by #8570, live disable not verified) | not recorded | not recorded | not recorded | 2026-11-24 | | `quota-weekly-review.timer` | `OnCalendar=Mon *-*-* 07:20:00` | `quota-weekly-review.service` | laptop (user systemd; code#12701; NixOS module `services.pm-stack`, package `pkgs/pm-aggregator` — Stage-3 S7 weekly forecast-accuracy review: posts the report to epic #12694, S6 proposal PRs only, never edits config; Nix-configured pending deployment) | not recorded | not recorded | 2026-11-23 | 2026-11-23 | | `repo-archive-backup.timer` | `OnCalendar=*-*-* 05:15:00` | `repo-archive-backup.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `repo-universe-issue-check.timer` | `OnCalendar=*-*-* 00:00:00` | `repo-universe-issue-check.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | @@ -445,6 +445,14 @@ it targeted the retired sandbox collector. The drill script is laptop-only sandbox's installed-unit state still requires the operator audit linked from issue #1319. +2026-11-24 #8570 timer cutover is prepared in source: pm-core retains the +quota (15m) and fleet-feed (5m) cadences in-process; the quota and collector +systemd timer declarations/installer activation are removed. The two rows +above remain until deployment verifies the laptop units are inactive and +disabled; this PR does not claim a live systemd cutover. The kill-collector +drill now pauses the in-process feed job through its state-file gate and +refuses to run while the legacy collector timer remains active. + ### 2c. Sandbox systemd system timers (1 listed) The sandbox's system-scope timers (the sandbox has no user bus). A listed diff --git a/nixos/services/pm-stack/default.nix b/nixos/services/pm-stack/default.nix index 2f2d6d9eb7..88b35da82a 100644 --- a/nixos/services/pm-stack/default.nix +++ b/nixos/services/pm-stack/default.nix @@ -274,8 +274,16 @@ in # signal delivered to this service is attributed in # ${aggState}/sigterm-witness.log before it is # forwarded to the app. + # Refresh the collector's local OpenCode password when possible; + # a missing/failing helper must not take the board offline. + ExecStartPre = "-${home}/.local/bin/fleet-feed-oc-password.sh"; ExecStart = "${sigtermWitness}/bin/sigterm-witness --log ${aggState}/sigterm-witness.log ${pmAggregator}/bin/pm-aggregator"; - EnvironmentFile = "${aggState}/.env"; + # The in-process quota job also needs the optional Antigravity + # credential file previously loaded by quota-gatherer.service. + EnvironmentFile = [ + "${aggState}/.env" + "-%h/.local/state/opencode/mistral-api-key.env" + ]; # The projector is a deployed service of this stack — never # render it off (see the header note). The coverage snapshot # is runtime state: keep it in the state dir, not the @@ -323,6 +331,30 @@ in # switching this back to "file" is the rollback. "PM_AGG_STORE_BACKEND=turso" "PM_AGG_STORE_WRITER=pm-aggregator.service" + # #8570: preserve the old quota-gatherer service's state paths + # when its main() runs inside pm-aggregator. + "QUOTA_CURRENT_PATH=${aggState}/quota-current.json" + "QUOTA_HEARTBEAT_PATH=${aggState}/quota-gatherer-heartbeat.json" + "QUOTA_GATHERER_STATE_PATH=${aggState}/quota-gatherer-state.json" + "QUOTA_SNAPSHOTS_DIR=${aggState}/snapshots" + "POOL_STATE_PATH=${home}/.local/state/opencode-claimant/pool-state.json" + # #8570: preserve the collector's source paths and runtime + # credentials when it runs inside pm-aggregator rather than its + # former oneshot unit. + "QUOTA_VIEW_PATH=${home}/hatch-personal/workspace/goals/stewardship-commission-recurring-review-and-dispatch/hidden_files/visibility/quota-view.md" + "QUOTA_REGISTRY_PATH=${home}/hatch-personal/workspace/goals/keep-the-four-repos-healthy/hidden_files/provider-quota-registry.md" + "ORCHESTRATION_PATH=${home}/hatch-personal/workspace/goals/keep-the-four-repos-healthy/hidden_files/orchestration.json" + "DNS_REGISTER_PATH=${home}/hatch-personal/workspace/goals/stand-up-lab-cluster-talm-talos-cozystack-postgres-rustfs/files/dns-domain-register.md" + "AA_OPENCODE_CONFIG_PATH=${home}/git/code/.opencode/opencode.jsonc" + "CHARGE_CANDIDATES_PATH=${home}/hatch-personal/workspace/goals/keep-the-four-repos-healthy/hidden_files/charges-candidates.json" + "CHARGES_SURFACED_STATE_PATH=${home}/hatch-personal/workspace/goals/keep-the-four-repos-healthy/hidden_files/charges-surfaced-state.json" + "CLAUDE_LAUNCH_RECORDS_PATH=${home}/hatch-personal/workspace/goals/keep-the-four-repos-healthy/hidden_files/claude-launch-records.jsonl" + "USAGE_SNAPSHOT_OUTBOX_PATH=${aggState}/usage-snapshot-outbox.jsonl" + "SANDBOX_OPENCODE_URL=http://127.0.0.1:13420" + "OPENCODE_SERVER_URL=http://127.0.0.1:13420" + "OPENCODE_SESSION_SOURCE=opencode-laptop" + "OPENCODE_SERVER_PASSWORD_FILE=${aggState}/opencode-server-password" + "PM_AGG_FRESHNESS_URL=http://127.0.0.1:4871/publish" "BWS_BIN=/run/current-system/sw/bin/bws" "BWS_ACCESS_TOKEN_FILE=${home}/.config/bws/access-token" # The digest archive (#1278) is runtime state too: one @@ -661,17 +693,6 @@ in Install.WantedBy = [ "timers.target" ]; }; - quota-gatherer = { - Unit.Description = "Run the quota gatherer every 15 minutes (pm-stack, #1151)"; - Timer = { - OnCalendar = "*:0/15"; - RandomizedDelaySec = 20; - Persistent = true; - Unit = "quota-gatherer.service"; - }; - Install.WantedBy = [ "timers.target" ]; - }; - pm-digest-daily = { Unit.Description = "Run the PM daily digest every morning at 07:00 local (pm-stack, #1278)"; Timer = { @@ -705,16 +726,6 @@ in Install.WantedBy = [ "timers.target" ]; }; - fleet-feed-collector = { - Unit.Description = "Collect the fleet feed for the laptop aggregator every ~5 minutes"; - Timer = { - OnBootSec = "2min"; - OnUnitActiveSec = "5min"; - Unit = "fleet-feed-collector.service"; - }; - Install.WantedBy = [ "timers.target" ]; - }; - pm-kaneo = { Unit.Description = "Retry pm-kaneo until the Kaneo stack is up (docker-ordering self-heal)"; Timer = { diff --git a/pm-stack/aggregator/install.sh b/pm-stack/aggregator/install.sh index 55e11fcdb6..119af65e2e 100755 --- a/pm-stack/aggregator/install.sh +++ b/pm-stack/aggregator/install.sh @@ -222,6 +222,18 @@ if [ "$CHANGED" -eq 1 ]; then echo "$SRC_INPUTS" >"$STATE_DIR/.deploy-inputs-hash" fi +# #8570: pm-core owns quota (15m) and fleet-feed (5m) schedules in-process. +# Retire any previously enabled user timers before the aggregator (re)starts, +# so the legacy collector cannot overlap the in-process one. +for RETIRED_TIMER in quota-gatherer.timer fleet-feed-collector.timer; do + if systemctl --user is-active --quiet "$RETIRED_TIMER"; then + systemctl --user stop "$RETIRED_TIMER" + fi + if systemctl --user is-enabled --quiet "$RETIRED_TIMER"; then + systemctl --user disable "$RETIRED_TIMER" + fi +done + systemctl --user daemon-reload systemctl --user enable pm-aggregator.service if [ "$CHANGED" -eq 1 ]; then @@ -255,33 +267,22 @@ curl -s "http://${TAILNET_IP}:4870/api/health" echo systemctl --user is-active pm-aggregator.service -# Quota gatherer (#1151): a user timer on the same 15-minute cadence -# as the Meta file exporter (#1301), running scripts/gather-quota.ts -# from this checkout. Units ship with this package (systemd/). Guarded: -# a checkout without the units skips this block instead of failing the install. +# Keep the quota oneshot service available for explicit operator runs, but +# do not install or enable its retired timer. GATHERER_SVC_SRC="$SRC/systemd/quota-gatherer.service" -GATHERER_TMR_SRC="$SRC/systemd/quota-gatherer.timer" -if [ -f "$GATHERER_SVC_SRC" ] && [ -f "$GATHERER_TMR_SRC" ]; then +if [ -f "$GATHERER_SVC_SRC" ]; then # Home-manager hosts manage these units as symlinks into /nix/store # (#9586): a plain cp over the symlink aborts the install on the # read-only store. Mirror the pm-aggregator unit guard above: skip # the copy for symlink-managed destinations and leave those units # to the NixOS/home-manager switch. GATHERER_SVC_DST="$HOME/.config/systemd/user/quota-gatherer.service" - GATHERER_TMR_DST="$HOME/.config/systemd/user/quota-gatherer.timer" if [ -L "$GATHERER_SVC_DST" ]; then echo "quota-gatherer.service is symlink-managed at $GATHERER_SVC_DST; skipping unit copy" else cp "$GATHERER_SVC_SRC" "$GATHERER_SVC_DST" fi - if [ -L "$GATHERER_TMR_DST" ]; then - echo "quota-gatherer.timer is symlink-managed at $GATHERER_TMR_DST; skipping unit copy" - else - cp "$GATHERER_TMR_SRC" "$GATHERER_TMR_DST" - fi systemctl --user daemon-reload - systemctl --user enable --now quota-gatherer.timer - echo "quota-gatherer.timer: $(systemctl --user is-active quota-gatherer.timer)" else - echo "quota-gatherer units not found — gatherer timer not installed" + echo "quota-gatherer service not found — explicit gatherer runs unavailable" fi diff --git a/pm-stack/aggregator/scripts/age-feed-drill.sh b/pm-stack/aggregator/scripts/age-feed-drill.sh index ff36c56697..eac5e262fe 100755 --- a/pm-stack/aggregator/scripts/age-feed-drill.sh +++ b/pm-stack/aggregator/scripts/age-feed-drill.sh @@ -4,7 +4,7 @@ # Deliberately age the fleet feed while the collector keeps running, and # verify the PM stack notices a feed that is alive but OLD — the failure # mode the kill-collector drill (first slice, #1823) cannot reach: there -# the collector is dead, here it runs on schedule and the data it +# the collector is paused, here it stays scheduled and the data it # presents is stale, so "everything is fine" is a lie the process tree # does not contradict. # @@ -14,8 +14,8 @@ # cannot overlap this one); # - the incident flag file ($PM_DRILL_INCIDENT_FLAG) must not exist — # during a real incident the stack is not a drill canvas; -# - the collector timer must be active (this drill's premise is a -# running collector) and the feed must currently be FRESH. An +# - the legacy collector timer must be inactive (pm-core owns +# collection) and the feed must currently be FRESH. An # already-stale feed is a real incident, not a drill. # 2. Saves the feed's exact bytes, then arms restore (trap on # EXIT/INT/TERM) immediately BEFORE the first write, so every @@ -23,10 +23,11 @@ # 3. Ages the feed by rewriting its top-level generatedAt into the past # (PM_DRILL_AGE_MS, default 20 min > the 15-min FEED_STALE_MS in # src/health.ts + src/sources/live.ts) while leaving every other -# field intact. The collector keeps running on its ~5-min timer; if +# field intact. The in-process pm-core collector keeps its 5-min cadence; if # it rewrites the feed with a fresh stamp mid-drill, the drill # re-ages it, which is exactly the "collector runs, data is old" -# scenario. +# scenario. The in-process pm-core collector runs on its ~5-minute +# cadence throughout the drill. # 4. Polls /api/health until feed.ageMs crosses FEED_STALE_MS and the # payload reports degraded, saving that payload as the fired-signal # evidence; it also records (best effort) whether the #1148 @@ -35,7 +36,7 @@ # carries the stale-feed warning (#1116 item 5). # 5. Restores ALWAYS once the aging has happened: the saved bytes are # written back atomically and the drill waits (up to -# PM_DRILL_RESTORE_WAIT_MIN) for the collector's next scheduled run +# PM_DRILL_RESTORE_WAIT_MIN) for the in-process collector's next 5-min tick # to make the feed fresh again, confirming via /api/health. The # restore is gated on the aging: a drill that refuses to start # touches nothing. @@ -47,8 +48,9 @@ # # Where it runs: on the host that owns the feed and the aggregator — # the laptop, where the collector moved on 2026-10-31 (code#3362/#3363). -# The collector/aggregator are NixOS user units, so the timer check uses -# `systemctl --user`; nothing here needs root. +# The aggregator is a NixOS user unit. The old collector timer is checked +# inactive to prevent a second collector from invalidating the drill; +# nothing here needs root. # # Scheduling: systemd/age-feed-drill.{service,timer} in this repo's # pm-stack/aggregator/systemd/ directory (weekly, in a quiet window that @@ -209,8 +211,9 @@ restore() { trap restore EXIT INT TERM # --- preconditions ---------------------------------------------------------- -systemctl --user is-active --quiet "$COLLECTOR_TIMER" || - die "$COLLECTOR_TIMER is not active; this drill's premise is a running collector, and a stopped collector outside a drill is itself a finding" +if systemctl --user is-active --quiet "$COLLECTOR_TIMER"; then + die "$COLLECTOR_TIMER is still active; pm-core owns collection and the legacy timer must be retired" +fi [ -r "$FEED_FILE" ] || die "cannot read the feed file $FEED_FILE" [ -n "$(feed_stamp)" ] || die "feed file $FEED_FILE has no readable generatedAt; refusing to drill blind" BASELINE="$(health_json | feed_facts)" || die "cannot read aggregator /api/health; refusing to drill blind" @@ -218,9 +221,9 @@ BASE_AGE="${BASELINE%% *}" [ "$BASE_AGE" -ge 0 ] 2>/dev/null || die "cannot read aggregator /api/health; refusing to drill blind" [ "$BASE_AGE" -le "$STALE_MS" ] || die "feed is already stale at drill start (age ${BASE_AGE}ms > ${STALE_MS}ms): that is a real incident, not a drill" cp -p "$FEED_FILE" "$BACKUP_FILE" || die "cannot save the feed's original bytes to $BACKUP_FILE" -log "preconditions ok: collector active, feed fresh (age ${BASE_AGE}ms), feed saved, no incident flag, lock held" +log "preconditions ok: legacy timer inactive, in-process collector scheduled, feed fresh (age ${BASE_AGE}ms), feed saved, no incident flag, lock held" -# --- age the feed, collector still running ------------------------------------ +# --- age the feed, in-process collector still scheduled ----------------------- # Pin the stamp once so every re-age during the drill presents the same # "alive but old" feed; the collector's own rewrites are re-aged below. PIN_STAMP="$(python3 -c ' @@ -345,7 +348,7 @@ if [ "${PM_DRILL_NO_POST:-0}" != "1" ] && command -v gh >/dev/null 2>&1; then if [ "$OUTCOME" = "passed" ]; then gh issue comment "$ISSUE" --repo "$ISSUE_REPO" --body "✅ **Chaos drill passed — age the feed** (queue task 7919, second slice of this issue, epic #$EPIC) -- Aged \`fleet-feed.json\`'s \`generatedAt\` by ${AGE_MS}ms at $STARTED_AT **while \`$COLLECTOR_TIMER\` stayed active** — the stale-but-alive feed the kill-collector drill cannot produce. Health payload at the signal moment: degraded=$DEGRADED, watchdog \`watchdog:feed\` item seen=$WATCHDOG. +- Aged \`fleet-feed.json\`'s \`generatedAt\` by ${AGE_MS}ms at $STARTED_AT **while pm-core's in-process collector remained scheduled** — the stale-but-alive feed the kill-collector drill cannot produce. Health payload at the signal moment: degraded=$DEGRADED, watchdog \`watchdog:feed\` item seen=$WATCHDOG. - The aggregator's feed-age signal crossed the 15-minute \`FEED_STALE_MS\` (#1148) threshold instead of presenting old data as fine. - Restoration confirmed via \`/api/health\`: the original bytes were written back and the collector's next run made the feed fresh again. - Script: \`pm-stack/aggregator/scripts/age-feed-drill.sh\` (interlocked: flock, incident-flag refusal, refuses to start on an already-stale feed or an inactive collector; always restores via trap). Result JSON is written to \`~/.local/state/pm-drills/age-feed-result.json\` per run." >/dev/null 2>&1 && diff --git a/pm-stack/aggregator/scripts/kill-collector-drill.sh b/pm-stack/aggregator/scripts/kill-collector-drill.sh index 60e2c7fd44..6abbba980f 100755 --- a/pm-stack/aggregator/scripts/kill-collector-drill.sh +++ b/pm-stack/aggregator/scripts/kill-collector-drill.sh @@ -11,30 +11,35 @@ # cannot overlap this one); # - an incident flag file ($PM_DRILL_INCIDENT_FLAG) must not exist — # during a real incident the stack is not a drill canvas; -# - the collector timer must be active and the feed must currently +# - the legacy collector timer must be inactive and the feed must currently # be FRESH (age < the staleness threshold). A feed that is # already stale is a real incident, not a drill. -# 2. Stops fleet-feed-collector.timer (and any in-flight oneshot). +# 2. Creates the pm-core pause file; subsequent in-process collector ticks +# leave the existing feed untouched until the drill restores it. +# Limitation: the gate is read only when a tick starts (pm-core-wiring.ts +# runFleetFeed). A collector run already in flight when the file appears +# finishes and may write one more fresh stamp. That delays the signal by +# up to one collector run; it cannot produce a false pass, because the +# drill passes only once the feed age actually crosses FEED_STALE_MS. # 3. Polls the aggregator's /api/health until the feed's age crosses # FEED_STALE_MS — 5 minutes, the #1148 watchdog threshold the code # itself uses (src/health.ts, src/sources/live.ts) — and records # the health payload at that moment as the fired-signal evidence. # 4. Restores, ALWAYS once the kill has happened (trap on -# EXIT/INT/TERM plus an explicit restore step): starts the timer -# again and immediately runs the collector once so the feed is -# fresh, then confirms via /api/health that the feed age is back +# EXIT/INT/TERM plus an explicit restore step): removes the pause +# file so the next in-process tick can refresh the feed, then confirms +# via /api/health that the feed age is back # under the threshold. The restore is gated on the kill: a drill # that refuses to start (step 1, or the preconditions below) -# touches nothing — no timer/service start on any refusal path. +# touches nothing — no pause file is created on any refusal path. # 5. Reports: writes a JSON result to the state dir; with gh available # it posts the result as a comment on #1283. If the expected signal # does NOT fire, it instead files a new issue under epic #1184 with # the drill evidence (that is the drill doing its job: a silent # failure of the honesty signals is a finding, not a drill error). # -# The old sandbox systemd timer was retired when the collector moved to -# the laptop. This drill is laptop-only until a laptop-hosted schedule is -# deliberately installed; the host guard below also protects manual runs. +# The collector now runs inside the laptop aggregator. The drill is +# laptop-only and pauses that in-process job through its state-file gate. # # Environment knobs: # PM_DRILL_STATE_DIR state/lock/result dir (default ~/.local/state/pm-drills) @@ -55,7 +60,7 @@ INCIDENT_FLAG="${PM_DRILL_INCIDENT_FLAG:-$STATE_DIR/incident.flag}" MAX_WAIT_MIN="${PM_DRILL_MAX_WAIT_MIN:-25}" STALE_MS=300000 # FEED_STALE_MS in aggregator src/feed.ts COLLECTOR_TIMER="fleet-feed-collector.timer" -COLLECTOR_SERVICE="fleet-feed-collector.service" +AGG_ENV_FILE="$HOME/.local/state/pm-aggregator/.env" ISSUE_REPO="developing-today/code" EPIC=1184 ISSUE=1283 @@ -119,47 +124,62 @@ except Exception: # --- restore: idempotent, and gated on the kill --------------------------- # The trap is installed before the precondition checks, so without the -# gate a REFUSAL (die -> exit) would fire restore() and start the +# gate a REFUSAL (die -> exit) would fire restore() and remove the # collector the drill just refused to touch — masking the very # findings the interlocks exist to surface (#2865). KILLED is armed -# immediately BEFORE the destructive timer stop — after every +# immediately BEFORE pause-file creation — after every # precondition refusal — so until that point restore() is a no-op and # every refusal path leaves the system exactly as it found it, while -# a signal interrupting the stop itself (this drill's systemd service -# is cancelled via TERM) still restores a timer the stop may already -# have deactivated (Codex P2 on PR #3027). +# a signal interrupting pause-file creation still removes a file that +# may already have been created. KILLED=0 RESTORED=0 restore() { [ "$KILLED" = 1 ] || return 0 [ "$RESTORED" = 1 ] && return 0 RESTORED=1 - log "restoring collector (timer start + immediate collection run)" - sudo -n systemctl start "$COLLECTOR_TIMER" 2>/dev/null || log "WARN: could not start $COLLECTOR_TIMER" - sudo -n systemctl start "$COLLECTOR_SERVICE" 2>/dev/null || log "WARN: could not start $COLLECTOR_SERVICE" + log "restoring collector (removing pm-core pause file)" + rm -f "$PAUSE_FILE" || log "WARN: could not remove $PAUSE_FILE" } trap restore EXIT INT TERM +# --- pause file: derive exactly as the aggregator does, or refuse ---------- +# pm-core-wiring.ts resolves the pause file as PM_CORE_FEED_PAUSE_FILE, else +# /fleet-feed.pause. The aggregator reads its +# config from AGG_ENV_FILE (EnvironmentFile of pm-aggregator.service). A +# drill that pauses a different file than the aggregator reads would pass its +# honesty signal without pausing anything, so refuse on any disagreement. +agg_env_value() { + [ -r "$AGG_ENV_FILE" ] || return 0 + sed -n "s/^$1=//p" "$AGG_ENV_FILE" | tail -n 1 +} +[ -r "$AGG_ENV_FILE" ] || die "cannot read aggregator config $AGG_ENV_FILE; refusing to pause a collector path it may not read" +AGG_FEED_FILE="$(agg_env_value PM_AGG_FEED_FILE)" +AGG_FEED_FILE="${AGG_FEED_FILE:-$HOME/.local/state/pm-aggregator/fleet-feed.json}" +AGG_PAUSE_FILE="$(agg_env_value PM_CORE_FEED_PAUSE_FILE)" +AGG_PAUSE_FILE="${AGG_PAUSE_FILE:-$(dirname "$AGG_FEED_FILE")/fleet-feed.pause}" +if [ -n "${PM_CORE_FEED_PAUSE_FILE:-}" ] && [ "$PM_CORE_FEED_PAUSE_FILE" != "$AGG_PAUSE_FILE" ]; then + die "PM_CORE_FEED_PAUSE_FILE ($PM_CORE_FEED_PAUSE_FILE) disagrees with the aggregator's pause file ($AGG_PAUSE_FILE); refusing" +fi +PAUSE_FILE="$AGG_PAUSE_FILE" + # --- preconditions ---------------------------------------------------------- -systemctl is-active --quiet "$COLLECTOR_TIMER" || die "$COLLECTOR_TIMER is not active; nothing to kill, and a stopped collector outside a drill is itself a finding" +if systemctl is-active --quiet "$COLLECTOR_TIMER"; then + die "$COLLECTOR_TIMER is still active; pm-core drill requires the legacy timer to be retired" +fi +[ ! -e "$PAUSE_FILE" ] || die "collector pause file already exists ($PAUSE_FILE); refusing to inherit another pause" BASELINE="$(health_json | feed_facts)" BASE_AGE="${BASELINE%% *}" [ "$BASE_AGE" -ge 0 ] || die "cannot read aggregator /api/health; refusing to drill blind" [ "$BASE_AGE" -lt "$STALE_MS" ] || die "feed is already stale at drill start (age ${BASE_AGE}ms >= ${STALE_MS}ms): that is a real incident, not a drill" -log "preconditions ok: collector active, feed fresh (age ${BASE_AGE}ms), no incident flag, lock held" - -# --- kill ------------------------------------------------------------------- -log "stopping $COLLECTOR_TIMER" -# Arm restoration BEFORE the destructive stop: if TERM/INT lands -# while systemctl stop is in flight, the timer may already be -# deactivated even though the stop never returns success — with the -# gate armed only after a successful stop, both traps would skip -# restore and leave the collector stopped indefinitely. Every -# precondition refusal is above this point, so arming here can never -# fire restore on a refusal. +log "preconditions ok: legacy timer inactive, feed fresh (age ${BASE_AGE}ms), no incident flag, lock held" + +# --- pause ----------------------------------------------------------------- +# Arm restoration BEFORE creating the pause file: if TERM/INT lands +# during creation, restore removes it if it exists. Every precondition +# refusal is above this point, so restoration never masks a refusal. KILLED=1 -sudo -n systemctl stop "$COLLECTOR_TIMER" || die "failed to stop $COLLECTOR_TIMER (sudo -n systemctl required)" -sudo -n systemctl stop "$COLLECTOR_SERVICE" 2>/dev/null || true +touch "$PAUSE_FILE" || die "failed to create collector pause file ($PAUSE_FILE)" # --- wait for the honesty signal --------------------------------------------- SIGNAL=0 @@ -184,7 +204,7 @@ done restore trap - EXIT INT TERM CONFIRMED=0 -for _ in 1 2 3 4 5 6; do +for _ in $(seq 1 20); do sleep 20 FACTS="$(health_json | feed_facts)" AGE="${FACTS%% *}" @@ -194,7 +214,7 @@ for _ in 1 2 3 4 5 6; do break fi done -[ "$CONFIRMED" = 1 ] || log "WARN: restoration not confirmed within ~2min (feed age ${AGE:-unknown}ms)" +[ "$CONFIRMED" = 1 ] || log "WARN: restoration not confirmed within ~7min (feed age ${AGE:-unknown}ms)" # --- report ------------------------------------------------------------------- OUTCOME="failed" @@ -218,8 +238,8 @@ if [ "${PM_DRILL_NO_POST:-0}" != "1" ] && command -v gh >/dev/null 2>&1; then if [ "$OUTCOME" = "passed" ]; then gh issue comment "$ISSUE" --repo "$ISSUE_REPO" --body "✅ **Chaos drill passed — kill-collector** (queue task 2667, first slice of this issue, epic #$EPIC) -- Stopped \`$COLLECTOR_TIMER\` on laptop host amd at $STARTED_AT; the aggregator's feed-age signal reached the 5-minute \`FEED_STALE_MS\` (#1148) threshold — the honesty signal fired instead of the dashboard presenting a dead feed as fine. Health payload at the signal moment was captured by the drill. -- Collector restored (timer restarted + immediate collection run) and restoration confirmed via \`/api/health\`: feed fresh again. +- Paused pm-core's in-process fleet-feed scheduler on laptop host amd at $STARTED_AT; the aggregator's feed-age signal reached the 5-minute \`FEED_STALE_MS\` (#1148) threshold — the honesty signal fired instead of the dashboard presenting a dead feed as fine. Health payload at the signal moment was captured by the drill. +- Collector restored by removing the pause file; restoration was confirmed via \`/api/health\` after an in-process tick: feed fresh again. - Script: \`pm-stack/aggregator/scripts/kill-collector-drill.sh\` (interlocked: flock, incident-flag refusal, refuses to start on an already-stale feed; always restores via trap). Result JSON is written to \`~/.local/state/pm-drills/kill-collector-result.json\` on laptop host amd per run." >/dev/null 2>&1 && log "posted result comment on #$ISSUE" || log "WARN: gh comment on #$ISSUE failed" else diff --git a/pm-stack/aggregator/src/pm-core-jobs.ts b/pm-stack/aggregator/src/pm-core-jobs.ts deleted file mode 100644 index 3fc8acf5b5..0000000000 --- a/pm-stack/aggregator/src/pm-core-jobs.ts +++ /dev/null @@ -1,43 +0,0 @@ -/** Own the quota and fleet-feed jobs from the aggregator process (#8570). - * - * The legacy oneshot scripts remain executable for rollback/manual runs, but - * live pm-core imports their exported entry points and owns their cadence. - * Their normal output files remain the jobs' responsibility; this audit log - * records scheduler outcomes only and is never read for freshness. - */ -import { appendFile, mkdir } from "node:fs/promises"; -import { dirname, join } from "node:path"; -import { homedir } from "node:os"; -import { createPmCoreScheduler, type SchedulerAudit } from "./pm-core-scheduler.ts"; - -const DEFAULT_AUDIT_PATH = join(homedir(), ".local/state/pm-aggregator/pm-core-jobs.jsonl"); - -export async function startPmCoreJobs( - options: { auditPath?: string; warn?: (message: string) => void } = {}, -): Promise> { - // Dynamic imports keep fixture/dev tools from loading host-only job - // dependencies unless this live process actually starts the schedulers. - const [{ main: runQuota }, { main: runFleetFeed }] = await Promise.all([ - import("../scripts/gather-quota.ts"), - import("../scripts/collect-fleet-feed.ts"), - ]); - const auditPath = options.auditPath ?? process.env.PM_CORE_JOBS_AUDIT_PATH ?? DEFAULT_AUDIT_PATH; - const scheduler = createPmCoreScheduler({ - runQuota: async () => { - const code = await runQuota(); - if (code !== 0) throw new Error(`quota gatherer exited with status ${code}`); - }, - runFleetFeed, - writeAudit: async (record: SchedulerAudit) => { - await mkdir(dirname(auditPath), { recursive: true }); - await appendFile(auditPath, `${JSON.stringify(record)}\n`, "utf8"); - }, - }); - scheduler.start(); - // Preserve the old oneshot behavior: refresh promptly after service start, - // then let the scheduler own the established 15m/5m intervals. - void scheduler.runNow("quota"); - void scheduler.runNow("fleet-feed"); - options.warn?.("pm-core owns quota (15m) and fleet-feed (5m) schedules"); - return scheduler; -} diff --git a/pm-stack/aggregator/src/pm-core-scheduler.ts b/pm-stack/aggregator/src/pm-core-scheduler.ts index 755bf5b19e..2a234fadda 100644 --- a/pm-stack/aggregator/src/pm-core-scheduler.ts +++ b/pm-stack/aggregator/src/pm-core-scheduler.ts @@ -16,10 +16,15 @@ export interface SchedulerAudit { job: SchedulerJobName; startedAt: string; finishedAt: string; - status: "ok" | "error"; + status: "ok" | "error" | "skipped"; error?: string; + reason?: string; } +/** A job returns `{ skipped }` when a gate (for example the drill pause file) + * means the tick did no work; anything else is a normal ok. */ +export type JobResult = { skipped: string } | void; + export interface PmCoreScheduler { start(): void; stop(): void; @@ -28,7 +33,7 @@ export interface PmCoreScheduler { } type Timer = ReturnType; -type Job = () => Promise | void; +type Job = () => Promise | JobResult; export function createPmCoreScheduler(options: { runQuota: Job; @@ -71,8 +76,18 @@ export function createPmCoreScheduler(options: { active.add(job); const startedAt = now().toISOString(); try { - await jobs[job](); - await writeAuditSafely({ job, startedAt, finishedAt: now().toISOString(), status: "ok" }); + const result = await jobs[job](); + if (typeof result === "object" && result !== null && "skipped" in result) { + await writeAuditSafely({ + job, + startedAt, + finishedAt: now().toISOString(), + status: "skipped", + reason: result.skipped, + }); + } else { + await writeAuditSafely({ job, startedAt, finishedAt: now().toISOString(), status: "ok" }); + } } catch (error) { const message = error instanceof Error ? error.message : String(error); await writeAuditSafely({ diff --git a/pm-stack/aggregator/src/pm-core-wiring.ts b/pm-stack/aggregator/src/pm-core-wiring.ts index 24f01f7c16..d9b6633f5e 100644 --- a/pm-stack/aggregator/src/pm-core-wiring.ts +++ b/pm-stack/aggregator/src/pm-core-wiring.ts @@ -13,18 +13,25 @@ * own argv. The quota gatherer loads the same way for symmetry — * startup stays free of script module side effects. */ -import { appendFile, mkdir } from "node:fs/promises"; +import { access, appendFile, mkdir } from "node:fs/promises"; import { dirname, join } from "node:path"; -import { createPmCoreScheduler, type PmCoreScheduler, type SchedulerAudit } from "./pm-core-scheduler.ts"; +import { + createPmCoreScheduler, + type JobResult, + type PmCoreScheduler, + type SchedulerAudit, +} from "./pm-core-scheduler.ts"; export interface PmCoreJobs { runQuota: () => Promise; - runFleetFeed: () => Promise; + runFleetFeed: () => Promise; } export interface PmCoreJobDeps { /** The environment the fleet-feed job pins its output path into. */ env?: Record; + /** A present file pauses collector ticks for the laptop chaos drill. */ + feedPauseFile?: string; /** Injectable for tests; defaults to the gatherer's own main(). */ loadQuotaMain?: () => Promise<() => Promise>; /** Injectable for tests; defaults to the collector's own main(). */ @@ -33,6 +40,7 @@ export interface PmCoreJobDeps { export function createPmCoreJobs(options: { feedFile: string } & PmCoreJobDeps): PmCoreJobs { const env = options.env ?? process.env; + const feedPauseFile = options.feedPauseFile ?? env.PM_CORE_FEED_PAUSE_FILE ?? join(dirname(options.feedFile), "fleet-feed.pause"); const loadQuotaMain = options.loadQuotaMain ?? (async () => (await import("../scripts/gather-quota.ts")).main); const loadFleetFeedMain = options.loadFleetFeedMain ?? (async () => (await import("../scripts/collect-fleet-feed.ts")).main); @@ -48,7 +56,13 @@ export function createPmCoreJobs(options: { feedFile: string } & PmCoreJobDeps): throw new Error(`quota gatherer reported failure (exit ${exitCode})`); } }, - async runFleetFeed() { + async runFleetFeed(): Promise { + try { + await access(feedPauseFile); + return { skipped: `fleet-feed paused by ${feedPauseFile}` }; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + } // The collector resolves its output path at module top level from // FLEET_FEED_OUT, falling back to a checkout-relative path — so // the pin must be in place before the module is first imported. @@ -116,6 +130,10 @@ export function startPmCoreSchedulers(options: { clearInterval: options.clearInterval, }); scheduler.start(); + // Preserve the previous startPmCoreJobs behaviour: refresh promptly after + // a restart instead of waiting up to one full scheduler cadence. + void scheduler.runNow("quota"); + void scheduler.runNow("fleet-feed"); // Shutdown tied to process signals: stop the schedulers, detach the // handlers, then re-send the signal to ourselves so the process diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 58886836bd..fda18e11b9 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -12,7 +12,6 @@ import { homedir, tmpdir } from "node:os"; import { join } from "node:path"; import { Database } from "bun:sqlite"; import { createQuotaRefresher, systemdTrigger } from "./quota-refresh.ts"; -import { startPmCoreJobs } from "./pm-core-jobs.ts"; import { buildQuotaAnalytics, primeAttemptAggregates, type QuotaAnalytics } from "./analytics-store.ts"; import { decodePathSegment } from "./path-segment.ts"; import { errorBoundaryResponse, notFoundResponse } from "./error-boundary.ts"; @@ -5519,19 +5518,6 @@ const freshnessIpcServer = Bun.serve({ }); console.log(`freshness publisher listening on http://${freshnessIpcServer.hostname}:${freshnessIpcServer.port}`); -// #8570: in live mode the aggregator process owns the quota gatherer and -// fleet-feed collector schedules. Their output files remain audit/debug -// products; request freshness is held by the in-process stores/caches. -if (cfg.source === "live") { - void startPmCoreJobs({ - warn: (message) => console.log(`[pm-core] ${message}`), - }).catch((error) => { - console.error( - `[pm-core] failed to start scheduled jobs: ${error instanceof Error ? error.message : String(error)}`, - ); - }); -} - // #3976: start the anti-entropy loop in live mode — one pass now, // then the 5-minute cadence. Fixtures mode has no journal to reconcile. if (cfg.source === "live") { @@ -5539,10 +5525,9 @@ if (cfg.source === "live") { freshnessReconciler.start(); } -// #8570: pm-core consolidation — in live mode the quota gatherer and -// the fleet-feed collector also run as in-process schedulers on the -// seam's cadences (quota 15 minutes, fleet-feed 5 minutes), ahead of -// the systemd timer-unit cutover (a later slice of this issue). +// #8570: pm-core owns quota and fleet-feed schedules on the seam's +// cadences (quota 15 minutes, fleet-feed 5 minutes). Systemd timers are +// retired; the drill pause file can suspend fleet-feed ticks safely. // Shutdown is tied to process signals inside the wiring. if (cfg.source === "live") { startPmCoreSchedulers({ feedFile: cfg.feedFile }); diff --git a/pm-stack/aggregator/systemd/quota-gatherer.timer b/pm-stack/aggregator/systemd/quota-gatherer.timer deleted file mode 100644 index b46c9e20ea..0000000000 --- a/pm-stack/aggregator/systemd/quota-gatherer.timer +++ /dev/null @@ -1,11 +0,0 @@ -[Unit] -Description=Run the quota gatherer every 15 minutes (pm-stack, #1151) - -[Timer] -OnCalendar=*:0/15 -RandomizedDelaySec=20 -Persistent=true -Unit=quota-gatherer.service - -[Install] -WantedBy=timers.target diff --git a/pm-stack/aggregator/test/age-feed-drill.test.ts b/pm-stack/aggregator/test/age-feed-drill.test.ts index eb9d510b84..a5a8082011 100644 --- a/pm-stack/aggregator/test/age-feed-drill.test.ts +++ b/pm-stack/aggregator/test/age-feed-drill.test.ts @@ -20,7 +20,7 @@ import { join } from "node:path"; const DRILL = join(import.meta.dir, "..", "scripts", "age-feed-drill.sh"); interface Scenario { - timerActive: boolean; + legacyTimerActive: boolean; healthPlan: string[]; // per health call: fresh | stale | fail incidentFlag?: boolean; holdLock?: boolean; @@ -125,7 +125,7 @@ printf '{"degraded":%s,"feed":{"generatedAt":"%s","ageMs":0}}' "$([ "$mode" = st PM_DRILL_ATTENTION_CMD: `printf '%s' '{"attention":[{"id":"watchdog:feed"}]}'`, PM_DRILL_NO_POST: "1", PM_DRILL_RESTORE_WAIT_MIN: "1", - STUB_TIMER_ACTIVE: scn.timerActive ? "1" : "0", + STUB_TIMER_ACTIVE: scn.legacyTimerActive ? "1" : "0", STUB_REWRITE_ON_SLEEP: scn.rewriteOnSleep ? "1" : "0", }; // #1116 item (5): stub the rendered overview page the drill greps for @@ -171,16 +171,16 @@ printf '%s' '
3 of 3 services up
'`, } describe("age-feed drill: refusals touch nothing (#2865 lesson)", () => { - test("collector timer inactive -> refuse, feed unchanged", () => { - const r = runDrill({ timerActive: false, healthPlan: ["fresh"] }); + test("legacy collector timer active -> refuse, feed unchanged", () => { + const r = runDrill({ legacyTimerActive: true, healthPlan: ["fresh"] }); expect(r.status).toBe(1); - expect(r.stdout).toContain("is not active"); + expect(r.stdout).toContain("legacy timer must be retired"); expect(r.feedBytes).toBe(r.originalFeed); expect(existsSync(r.resultFile)).toBe(false); }); test("incident flag present -> refuse before any systemctl call", () => { - const r = runDrill({ timerActive: true, healthPlan: ["fresh"], incidentFlag: true }); + const r = runDrill({ legacyTimerActive: false, healthPlan: ["fresh"], incidentFlag: true }); expect(r.status).toBe(1); expect(r.stdout).toContain("incident flag present"); expect(r.systemctlLog.trim()).toBe(""); @@ -188,21 +188,21 @@ describe("age-feed drill: refusals touch nothing (#2865 lesson)", () => { }); test("drill lock held -> refuse, feed unchanged", () => { - const r = runDrill({ timerActive: true, healthPlan: ["fresh"], holdLock: true }); + const r = runDrill({ legacyTimerActive: false, healthPlan: ["fresh"], holdLock: true }); expect(r.status).toBe(1); expect(r.stdout).toContain("holds the lock"); expect(r.feedBytes).toBe(r.originalFeed); }); test("aggregator health unreadable -> refuse, feed unchanged", () => { - const r = runDrill({ timerActive: true, healthPlan: ["fail"] }); + const r = runDrill({ legacyTimerActive: false, healthPlan: ["fail"] }); expect(r.status).toBe(1); expect(r.stdout).toContain("refusing to drill blind"); expect(r.feedBytes).toBe(r.originalFeed); }); test("feed already stale -> refuse (real incident), feed unchanged", () => { - const r = runDrill({ timerActive: true, healthPlan: ["stale"] }); + const r = runDrill({ legacyTimerActive: false, healthPlan: ["stale"] }); expect(r.status).toBe(1); expect(r.stdout).toContain("already stale"); expect(r.feedBytes).toBe(r.originalFeed); @@ -213,7 +213,7 @@ describe("age-feed drill: a real run ages, notices, and restores", () => { test("fresh -> aged -> signal fires -> restore confirmed, outcome passed", () => { // Health reads in order: baseline (fresh), wait-poll (stale -> // signal), restore confirmation (fresh). - const r = runDrill({ timerActive: true, healthPlan: ["fresh", "stale", "fresh"] }); + const r = runDrill({ legacyTimerActive: false, healthPlan: ["fresh", "stale", "fresh"] }); expect(r.status).toBe(0); expect(r.feedBytes).toBe(r.originalFeed); expect(existsSync(r.resultFile)).toBe(true); @@ -233,7 +233,7 @@ describe("age-feed drill: a real run ages, notices, and restores", () => { // health reads: baseline fresh, wait-poll fresh (collector's write // landed during the sleep), wait-poll stale -> signal, restore fresh. const r = runDrill({ - timerActive: true, + legacyTimerActive: false, healthPlan: ["fresh", "fresh", "stale", "fresh"], rewriteOnSleep: true, }); @@ -251,7 +251,7 @@ describe("age-feed drill: a real run ages, notices, and restores", () => { describe("age-feed drill: rendered-page stale warning (#1116 item 5)", () => { test("page carrying the stale banner is recorded as seen", () => { - const r = runDrill({ timerActive: true, healthPlan: ["fresh", "stale", "fresh"], page: "warn" }); + const r = runDrill({ legacyTimerActive: false, healthPlan: ["fresh", "stale", "fresh"], page: "warn" }); expect(r.status).toBe(0); const result = JSON.parse(readFileSync(r.resultFile, "utf8")); expect(result.outcome).toBe("passed"); @@ -259,7 +259,7 @@ describe("age-feed drill: rendered-page stale warning (#1116 item 5)", () => { }); test("readable page without the banner is recorded as not seen", () => { - const r = runDrill({ timerActive: true, healthPlan: ["fresh", "stale", "fresh"], page: "silent" }); + const r = runDrill({ legacyTimerActive: false, healthPlan: ["fresh", "stale", "fresh"], page: "silent" }); expect(r.status).toBe(0); expect(r.stdout).toContain("has no stale-feed warning"); const result = JSON.parse(readFileSync(r.resultFile, "utf8")); @@ -267,7 +267,7 @@ describe("age-feed drill: rendered-page stale warning (#1116 item 5)", () => { }); test("unreadable page is recorded as unknown, drill still passes on the health signal", () => { - const r = runDrill({ timerActive: true, healthPlan: ["fresh", "stale", "fresh"], page: "fail" }); + const r = runDrill({ legacyTimerActive: false, healthPlan: ["fresh", "stale", "fresh"], page: "fail" }); expect(r.status).toBe(0); const result = JSON.parse(readFileSync(r.resultFile, "utf8")); expect(result.outcome).toBe("passed"); diff --git a/pm-stack/aggregator/test/install-rehearsal.sh b/pm-stack/aggregator/test/install-rehearsal.sh index de4783f281..ef1727417a 100644 --- a/pm-stack/aggregator/test/install-rehearsal.sh +++ b/pm-stack/aggregator/test/install-rehearsal.sh @@ -156,6 +156,12 @@ grep -Fx 'WorkingDirectory=%h/git/code/pm-stack/aggregator' \ "$HOME_TEST/.config/systemd/user/quota-gatherer.service" >/dev/null grep -Fx 'Environment=QUOTA_CURRENT_PATH=%h/.local/state/pm-aggregator/quota-current.json' \ "$HOME_TEST/.config/systemd/user/quota-gatherer.service" >/dev/null +test ! -e "$HOME_TEST/.config/systemd/user/quota-gatherer.timer" +! grep -F 'systemctl --user enable --now quota-gatherer.timer' "$LOG" >/dev/null +grep -F 'systemctl --user stop quota-gatherer.timer' "$LOG" >/dev/null +RETIRE_LINE="$(grep -n -F 'systemctl --user stop quota-gatherer.timer' "$LOG" | head -n 1 | cut -d: -f1)" +RESTART_LINE="$(grep -n -F 'systemctl --user restart pm-aggregator.service' "$LOG" | head -n 1 | cut -d: -f1)" +test -n "$RETIRE_LINE" && test -n "$RESTART_LINE" && test "$RETIRE_LINE" -lt "$RESTART_LINE" # The old feed bridge survives; the package itself is no longer copied # into the state directory. diff --git a/pm-stack/aggregator/test/kill-collector-drill.test.ts b/pm-stack/aggregator/test/kill-collector-drill.test.ts index 4c3466fcb5..fb60b84ac5 100644 --- a/pm-stack/aggregator/test/kill-collector-drill.test.ts +++ b/pm-stack/aggregator/test/kill-collector-drill.test.ts @@ -22,7 +22,10 @@ const DRILL = join(import.meta.dir, "..", "scripts", "kill-collector-drill.sh"); interface Scenario { host?: string; - interruptStop?: boolean; // stub systemctl stop sends TERM to the drill, then fails + interruptPause?: boolean; // stub touch sends TERM to the drill while creating the pause file + pauseOverride?: string; // drill-side PM_CORE_FEED_PAUSE_FILE (defaults to the test pause file) + aggEnvPauseFile?: string; // PM_CORE_FEED_PAUSE_FILE written into the aggregator .env + noAggEnv?: boolean; // omit the aggregator .env entirely timerActive: boolean; healthPlan: string[]; // per health-channel call: fresh | stale | fail incidentFlag?: boolean; @@ -34,12 +37,14 @@ function runDrill(scn: Scenario) { const home = join(base, "home"); const bin = join(base, "bin"); const state = join(base, "state"); + const pauseFile = join(state, "fleet-feed.pause"); mkdirSync(join(home, "tools"), { recursive: true }); mkdirSync(bin, { recursive: true }); mkdirSync(state, { recursive: true }); const stubLog = join(base, "systemctl.log"); writeFileSync(stubLog, ""); + const realTouch = Bun.which("touch") ?? "/usr/bin/touch"; const writeExe = (path: string, body: string) => { writeFileSync(path, body); chmodSync(path, 0o755); @@ -54,10 +59,6 @@ echo "systemctl $*" >> "${stubLog}" if [ "$1" = "is-active" ]; then [ "\${STUB_TIMER_ACTIVE:-1}" = "1" ] && exit 0 || exit 1 fi -if [ "$1" = "stop" ] && [ "\${STUB_INTERRUPT_STOP:-0}" = "1" ]; then - kill -TERM "$PPID" - exit 1 -fi exit 0 `, ); @@ -70,6 +71,16 @@ exec "$@" ); // The drill waits minutes in real runs; the stub makes waits instant. writeExe(join(bin, "sleep"), `#!/bin/sh\nexit 0\n`); + writeExe( + join(bin, "touch"), + `#!/bin/sh +"${realTouch}" "$@" +if [ "\${STUB_INTERRUPT_PAUSE:-0}" = "1" ]; then + kill -TERM "$PPID" + exit 1 +fi +`, + ); // Health channel: the drill reads it via ~/tools/laptop-ssh.sh. Each // invocation consumes the next plan entry (the last one repeats). @@ -100,6 +111,15 @@ printf '{"feed":{"generatedAt":"%s"},"degraded":false}' "$(cat "${base}/gen-at") if (scn.incidentFlag) writeFileSync(join(state, "incident.flag"), ""); + const aggEnvDir = join(home, ".local", "state", "pm-aggregator"); + if (!scn.noAggEnv) { + mkdirSync(aggEnvDir, { recursive: true }); + writeFileSync( + join(aggEnvDir, ".env"), + `PM_AGG_FEED_FILE=${join(state, "fleet-feed.json")}\n${scn.aggEnvPauseFile ? `PM_CORE_FEED_PAUSE_FILE=${scn.aggEnvPauseFile}\n` : ""}`, + ); + } + let lockHolder: ReturnType | null = null; if (scn.holdLock) { lockHolder = Bun.spawn(["flock", join(state, "kill-collector.lock"), "sleep", "15"], { @@ -117,8 +137,9 @@ printf '{"feed":{"generatedAt":"%s"},"degraded":false}' "$(cat "${base}/gen-at") PATH: `${bin}:${process.env.PATH}`, PM_DRILL_STATE_DIR: state, PM_DRILL_NO_POST: "1", + PM_CORE_FEED_PAUSE_FILE: scn.pauseOverride ?? pauseFile, STUB_TIMER_ACTIVE: scn.timerActive ? "1" : "0", - STUB_INTERRUPT_STOP: scn.interruptStop ? "1" : "0", + STUB_INTERRUPT_PAUSE: scn.interruptPause ? "1" : "0", }, encoding: "utf8", timeout: 30000, @@ -129,6 +150,7 @@ printf '{"feed":{"generatedAt":"%s"},"degraded":false}' "$(cat "${base}/gen-at") stderr: r.stderr ?? "", systemctlLog: readFileSync(stubLog, "utf8"), resultFile: join(state, "kill-collector-result.json"), + pauseFile, }; } finally { lockHolder?.kill(); @@ -140,6 +162,34 @@ function expectNoStart(log: string) { expect(starts).toEqual([]); } +describe("kill-collector drill: pause path agrees with the aggregator (#8570)", () => { + test("drill override that disagrees with the aggregator's pause file -> refuse, touch nothing", () => { + const elsewhere = join(tmpdir(), `elsewhere-${Date.now()}.pause`); + const r = runDrill({ timerActive: false, healthPlan: ["fresh"], pauseOverride: elsewhere }); + expect(r.status).toBe(1); + expect(r.stdout).toContain("disagrees with the aggregator's pause file"); + expect(r.systemctlLog.trim()).toBe(""); + expect(existsSync(elsewhere)).toBe(false); + expect(existsSync(r.pauseFile)).toBe(false); + }); + + test("aggregator .env pins a pause file the drill does not match -> refuse", () => { + const pinned = join(tmpdir(), `pinned-${Date.now()}.pause`); + const r = runDrill({ timerActive: false, healthPlan: ["fresh"], aggEnvPauseFile: pinned, pauseOverride: undefined }); + expect(r.status).toBe(1); + expect(r.stdout).toContain("disagrees with the aggregator's pause file"); + expect(existsSync(r.pauseFile)).toBe(false); + }); + + test("unreadable aggregator .env -> refuse before creating any pause file", () => { + const r = runDrill({ timerActive: false, healthPlan: ["fresh"], noAggEnv: true }); + expect(r.status).toBe(1); + expect(r.stdout).toContain("cannot read aggregator config"); + expect(r.systemctlLog.trim()).toBe(""); + expect(existsSync(r.pauseFile)).toBe(false); + }); +}); + describe("kill-collector drill: refusals touch nothing (#2865)", () => { test("non-laptop host -> refuse before any systemctl call", () => { const r = runDrill({ host: "sandbox", timerActive: true, healthPlan: ["fresh"] }); @@ -148,11 +198,12 @@ describe("kill-collector drill: refusals touch nothing (#2865)", () => { expect(r.systemctlLog.trim()).toBe(""); }); - test("collector timer inactive -> refuse, no systemctl start", () => { - const r = runDrill({ timerActive: false, healthPlan: ["fresh"] }); + test("legacy collector timer still active -> refuse without creating pause file", () => { + const r = runDrill({ timerActive: true, healthPlan: ["fresh"] }); expect(r.status).toBe(1); - expect(r.stdout).toContain("is not active"); + expect(r.stdout).toContain("legacy timer to be retired"); expectNoStart(r.systemctlLog); + expect(existsSync(r.pauseFile)).toBe(false); }); test("incident flag present -> refuse before any systemctl call", () => { @@ -170,53 +221,42 @@ describe("kill-collector drill: refusals touch nothing (#2865)", () => { }); test("aggregator health unreadable -> refuse, no systemctl start", () => { - const r = runDrill({ timerActive: true, healthPlan: ["fail"] }); + const r = runDrill({ timerActive: false, healthPlan: ["fail"] }); expect(r.status).toBe(1); expect(r.stdout).toContain("refusing to drill blind"); expectNoStart(r.systemctlLog); }); test("feed already stale -> refuse (real incident), no systemctl start", () => { - const r = runDrill({ timerActive: true, healthPlan: ["stale"] }); + const r = runDrill({ timerActive: false, healthPlan: ["stale"] }); expect(r.status).toBe(1); expect(r.stdout).toContain("already stale"); expectNoStart(r.systemctlLog); }); }); -describe("kill-collector drill: an interrupted stop still restores (#2865, Codex P2 on #3027)", () => { - test("TERM lands while systemctl stop is in flight -> restore starts timer + service", () => { - // The stub stop signals the drill (TERM, as systemd cancellation - // does) after the stop is already in flight, then fails. Restore - // must be armed BEFORE the stop, or both traps skip it and the - // collector timer stays stopped indefinitely. - const r = runDrill({ timerActive: true, healthPlan: ["fresh"], interruptStop: true }); +describe("kill-collector drill: interrupted pause creation restores the collector", () => { + test("TERM lands while pause file is being created -> restore removes it", () => { + const r = runDrill({ timerActive: false, healthPlan: ["fresh"], interruptPause: true }); expect(r.status).not.toBe(0); - const calls = r.systemctlLog.split("\n").filter(Boolean); - const starts = calls.filter((l) => l.includes(" start ")); - expect(starts.filter((l) => l.includes("start fleet-feed-collector.timer"))).toHaveLength(1); - expect(starts.filter((l) => l.includes("start fleet-feed-collector.service"))).toHaveLength(1); + expect(r.systemctlLog).not.toContain("stop fleet-feed-collector"); + expect(r.systemctlLog).not.toContain("start fleet-feed-collector"); + expect(existsSync(r.pauseFile)).toBe(false); }); }); describe("kill-collector drill: a real kill still restores (#2865)", () => { - test("kill -> signal fires -> restore starts timer + service, outcome passed", () => { + test("pause -> signal fires -> resume in-process collector, outcome passed", () => { // Health reads in order: baseline (fresh), wait-poll (stale -> // signal), evidence capture (stale), restore confirmation (fresh). const r = runDrill({ - timerActive: true, + timerActive: false, healthPlan: ["fresh", "stale", "stale", "fresh"], }); expect(r.status).toBe(0); const calls = r.systemctlLog.split("\n").filter(Boolean); - const stopTimer = calls.findIndex((l) => l.includes("stop fleet-feed-collector.timer")); - const stopSvc = calls.findIndex((l) => l.includes("stop fleet-feed-collector.service")); - const startTimer = calls.findIndex((l) => l.includes("start fleet-feed-collector.timer")); - const startSvc = calls.findIndex((l) => l.includes("start fleet-feed-collector.service")); - expect(stopTimer).toBeGreaterThanOrEqual(0); - expect(stopSvc).toBeGreaterThan(stopTimer); - expect(startTimer).toBeGreaterThan(stopSvc); - expect(startSvc).toBeGreaterThan(startTimer); + expect(calls).toEqual(["systemctl is-active --quiet fleet-feed-collector.timer"]); + expect(existsSync(r.pauseFile)).toBe(false); expect(existsSync(r.resultFile)).toBe(true); const result = JSON.parse(readFileSync(r.resultFile, "utf8")); expect(result.outcome).toBe("passed"); diff --git a/pm-stack/aggregator/test/pm-core-scheduler.test.ts b/pm-stack/aggregator/test/pm-core-scheduler.test.ts index 24aba526c9..0d068530d7 100644 --- a/pm-stack/aggregator/test/pm-core-scheduler.test.ts +++ b/pm-stack/aggregator/test/pm-core-scheduler.test.ts @@ -63,6 +63,23 @@ describe("pm-core scheduler (#8570)", () => { expect(audits[0].job).toBe("quota"); }); + test("a job that reports a skip is audited as skipped with its reason, not ok", async () => { + const audits: SchedulerAudit[] = []; + const scheduler = createPmCoreScheduler({ + runQuota: () => {}, + runFleetFeed: () => ({ skipped: "paused for drill" }), + writeAudit: (record) => { + audits.push(record); + }, + }); + + await scheduler.runNow("fleet-feed"); + expect(audits).toHaveLength(1); + expect(audits[0]?.job).toBe("fleet-feed"); + expect(audits[0]?.status).toBe("skipped"); + expect(audits[0]?.reason).toBe("paused for drill"); + }); + test("records a failed job without stopping the other scheduler", async () => { const audits: SchedulerAudit[] = []; const scheduler = createPmCoreScheduler({ diff --git a/pm-stack/aggregator/test/pm-core-wiring.test.ts b/pm-stack/aggregator/test/pm-core-wiring.test.ts index 122744026b..bae50ea0d1 100644 --- a/pm-stack/aggregator/test/pm-core-wiring.test.ts +++ b/pm-stack/aggregator/test/pm-core-wiring.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test"; import { EventEmitter } from "node:events"; -import { mkdtemp, readFile } from "node:fs/promises"; +import { mkdtemp, readFile, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { FLEET_FEED_CADENCE_MS, QUOTA_CADENCE_MS, type SchedulerAudit } from "../src/pm-core-scheduler.ts"; @@ -93,9 +93,12 @@ describe("pm-core wiring (#8570)", () => { resignal: () => {}, }); - timers.scheduled[0].callback(); await flush(); expect(gatherCalls).toBe(1); + audits.length = 0; + timers.scheduled[0].callback(); + await flush(); + expect(gatherCalls).toBe(2); expect(audits.map((audit) => [audit.job, audit.status])).toEqual([["quota", "ok"]]); runtime.shutdown(); }); @@ -118,6 +121,8 @@ describe("pm-core wiring (#8570)", () => { resignal: () => {}, }); + await flush(); + audits.length = 0; timers.scheduled[0].callback(); await flush(); expect(audits).toHaveLength(1); @@ -155,6 +160,110 @@ describe("pm-core wiring (#8570)", () => { expect(collectorCalls).toBe(1); }); + test("the fleet-feed pause file skips collection without loading the collector", async () => { + const dir = await mkdtemp(join(tmpdir(), "pm-core-feed-pause-")); + const pauseFile = join(dir, "fleet-feed.pause"); + await writeFile(pauseFile, "drill\n"); + let loaderCalls = 0; + const jobs = createPmCoreJobs({ + feedFile: join(dir, "fleet-feed.json"), + loadFleetFeedMain: async () => { + loaderCalls += 1; + return async () => {}; + }, + }); + + const result = await jobs.runFleetFeed(); + expect(loaderCalls).toBe(0); + expect(result).toEqual({ skipped: `fleet-feed paused by ${pauseFile}` }); + }); + + test("without a pause file the fleet-feed job runs and reports no skip", async () => { + const dir = await mkdtemp(join(tmpdir(), "pm-core-feed-nopause-")); + let loaderCalls = 0; + const jobs = createPmCoreJobs({ + feedFile: join(dir, "fleet-feed.json"), + env: {}, + loadFleetFeedMain: async () => { + loaderCalls += 1; + return async () => {}; + }, + }); + + const result = await jobs.runFleetFeed(); + expect(loaderCalls).toBe(1); + expect(result).toBeUndefined(); + }); + + test("a paused fleet-feed tick is audited as skipped with the pause reason, not ok", async () => { + const dir = await mkdtemp(join(tmpdir(), "pm-core-feed-audit-")); + const pauseFile = join(dir, "fleet-feed.pause"); + await writeFile(pauseFile, "drill\n"); + const audits: SchedulerAudit[] = []; + const timers = fakeTimers(); + const runtime = startPmCoreSchedulers({ + feedFile: join(dir, "fleet-feed.json"), + jobDeps: { + env: {}, + feedPauseFile: pauseFile, + loadQuotaMain: async () => async () => 0, + loadFleetFeedMain: async () => async () => { + throw new Error("collector must not run while paused"); + }, + }, + writeAudit: (record) => { + audits.push(record); + }, + setInterval: timers.setInterval, + clearInterval: timers.clearInterval, + signalTarget: new EventEmitter(), + resignal: () => {}, + }); + await flush(); + runtime.shutdown(); + + const feedAudits = audits.filter((record) => record.job === "fleet-feed"); + expect(feedAudits).toHaveLength(1); + expect(feedAudits[0]?.status).toBe("skipped"); + expect(feedAudits[0]?.reason).toBe(`fleet-feed paused by ${pauseFile}`); + }); + + test("startup refreshes both jobs once instead of waiting for the first cadence", async () => { + const dir = await mkdtemp(join(tmpdir(), "pm-core-startup-")); + const audits: SchedulerAudit[] = []; + const calls: string[] = []; + const timers = fakeTimers(); + const runtime = startPmCoreSchedulers({ + feedFile: join(dir, "fleet-feed.json"), + jobDeps: { + env: {}, + feedPauseFile: join(dir, "no-such.pause"), + loadQuotaMain: async () => async () => { + calls.push("quota"); + return 0; + }, + loadFleetFeedMain: async () => async () => { + calls.push("fleet-feed"); + }, + }, + writeAudit: (record) => { + audits.push(record); + }, + setInterval: timers.setInterval, + clearInterval: timers.clearInterval, + signalTarget: new EventEmitter(), + resignal: () => {}, + }); + await flush(); + runtime.shutdown(); + + expect(calls.sort()).toEqual(["fleet-feed", "quota"]); + expect(audits.map((record) => `${record.job}:${record.status}`).sort()).toEqual([ + "fleet-feed:ok", + "quota:ok", + ]); + }); + test("an operator-provided FLEET_FEED_OUT pin always wins over the feed file", async () => { const env: Record = { FLEET_FEED_OUT: "/preset/feed.json" }; let pinSeenAtLoad: string | undefined; @@ -215,13 +324,14 @@ describe("pm-core wiring (#8570)", () => { resignal: () => {}, }); + await flush(); timers.scheduled[0].callback(); await flush(); const lines = (await readFile(join(dir, "pm-core-scheduler-audit.jsonl"), "utf8")).trim().split("\n"); - expect(lines).toHaveLength(1); - const record = JSON.parse(lines[0]) as SchedulerAudit; - expect(record.job).toBe("quota"); - expect(record.status).toBe("ok"); + const records = lines.map((line) => JSON.parse(line) as SchedulerAudit); + expect(records.length).toBeGreaterThanOrEqual(2); + expect(records.every((record) => record.status === "ok")).toBe(true); + expect(records.filter((record) => record.job === "quota")).toHaveLength(2); runtime.shutdown(); }); }); diff --git a/pm-stack/scripts/deploy-install-smoke.test.sh b/pm-stack/scripts/deploy-install-smoke.test.sh index c22a652e87..8c243c3fca 100755 --- a/pm-stack/scripts/deploy-install-smoke.test.sh +++ b/pm-stack/scripts/deploy-install-smoke.test.sh @@ -315,7 +315,6 @@ printf '%s\n' '// fixture' >"$AGG_SRC/test/smoke.test.ts" printf '%s\n' '# fixture' >"$AGG_SRC/scripts/smoke.sh" printf '%s\n' '// fixture' >"$AGG_SRC/opencode-tools/smoke.ts" printf '%s\n' '[Service]' >"$AGG_SRC/systemd/quota-gatherer.service" -printf '%s\n' '[Timer]' >"$AGG_SRC/systemd/quota-gatherer.timer" printf '%s\n' '[Service]' >"$AGG_HOME/git/code/pm-stack/systemd/pm-aggregator.service" printf '%s\n' 'fake encrypted aggregator fixture' >"$AGG_HOME/secrets/pm-stack.sops.yaml" ln -s "$AGG_SRC" "$AGG_EXPECTED_SRC" From 0df2d0162132f3358e198e5935011b43998e49a1 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Tue, 24 Nov 2026 01:22:31 -0600 Subject: [PATCH 2/3] fix(pm-stack): preserve feed refresh and serialize drills --- nixos/services/pm-stack/default.nix | 1 + pm-stack/aggregator/scripts/age-feed-drill.sh | 6 +++--- .../aggregator/scripts/kill-collector-drill.sh | 6 +++--- pm-stack/aggregator/src/pm-core-wiring.ts | 12 ++++++++++++ pm-stack/aggregator/test/age-feed-drill.test.ts | 2 +- .../test/kill-collector-drill.test.ts | 2 +- pm-stack/aggregator/test/pm-core-wiring.test.ts | 17 +++++++++++++++++ 7 files changed, 38 insertions(+), 8 deletions(-) diff --git a/nixos/services/pm-stack/default.nix b/nixos/services/pm-stack/default.nix index 88b35da82a..8d5d28b224 100644 --- a/nixos/services/pm-stack/default.nix +++ b/nixos/services/pm-stack/default.nix @@ -566,6 +566,7 @@ in "PM_AGG_STORE_BACKEND=turso" "PM_AGG_STORE_WRITER=fleet-feed-collector" "FLEET_FEED_OUT=${aggState}/fleet-feed.json" + "PM_CORE_FEED_CREDENTIAL_REFRESH=${home}/.local/bin/fleet-feed-oc-password.sh" "PM_AGG_FRESHNESS_URL=http://127.0.0.1:4871/publish" "QUOTA_VIEW_PATH=${home}/hatch-personal/workspace/goals/stewardship-commission-recurring-review-and-dispatch/hidden_files/visibility/quota-view.md" "QUOTA_REGISTRY_PATH=${home}/hatch-personal/workspace/goals/keep-the-four-repos-healthy/hidden_files/provider-quota-registry.md" diff --git a/pm-stack/aggregator/scripts/age-feed-drill.sh b/pm-stack/aggregator/scripts/age-feed-drill.sh index eac5e262fe..4a5c6c83bd 100755 --- a/pm-stack/aggregator/scripts/age-feed-drill.sh +++ b/pm-stack/aggregator/scripts/age-feed-drill.sh @@ -10,8 +10,8 @@ # # What it does, in order: # 1. Interlocks (any failure = refuse to start, nothing is touched): -# - flock on the drill lock (a second drill, manual or scheduled, -# cannot overlap this one); +# - shared flock on the drill lock (the age-feed and kill-collector +# drills, manual or scheduled, cannot overlap one another); # - the incident flag file ($PM_DRILL_INCIDENT_FLAG) must not exist — # during a real incident the stack is not a drill canvas; # - the legacy collector timer must be inactive (pm-core owns @@ -113,7 +113,7 @@ die() { } # --- interlock: one drill at a time --------------------------------------- -exec 9>"$STATE_DIR/age-feed.lock" +exec 9>"$STATE_DIR/pm-drills.lock" if ! flock -n 9; then die "another age-feed drill holds the lock; not starting" fi diff --git a/pm-stack/aggregator/scripts/kill-collector-drill.sh b/pm-stack/aggregator/scripts/kill-collector-drill.sh index 6abbba980f..4a5292d39d 100755 --- a/pm-stack/aggregator/scripts/kill-collector-drill.sh +++ b/pm-stack/aggregator/scripts/kill-collector-drill.sh @@ -7,8 +7,8 @@ # # What it does, in order: # 1. Interlocks (any failure = refuse to start, nothing is touched): -# - an flock on the drill lock (a second drill, manual or scheduled, -# cannot overlap this one); +# - a shared flock on the drill lock (the age-feed and kill-collector +# drills, manual or scheduled, cannot overlap one another); # - an incident flag file ($PM_DRILL_INCIDENT_FLAG) must not exist — # during a real incident the stack is not a drill canvas; # - the legacy collector timer must be inactive and the feed must currently @@ -83,7 +83,7 @@ HOST="$(hostname -s)" [ "$HOST" = "amd" ] || die "must run on laptop host 'amd'; refusing on '$HOST'" # --- interlock: one drill at a time --------------------------------------- -exec 9>"$STATE_DIR/kill-collector.lock" +exec 9>"$STATE_DIR/pm-drills.lock" if ! flock -n 9; then die "another kill-collector drill holds the lock; not starting" fi diff --git a/pm-stack/aggregator/src/pm-core-wiring.ts b/pm-stack/aggregator/src/pm-core-wiring.ts index d9b6633f5e..e3f68a97b4 100644 --- a/pm-stack/aggregator/src/pm-core-wiring.ts +++ b/pm-stack/aggregator/src/pm-core-wiring.ts @@ -13,8 +13,10 @@ * own argv. The quota gatherer loads the same way for symmetry — * startup stays free of script module side effects. */ +import { execFile } from "node:child_process"; import { access, appendFile, mkdir } from "node:fs/promises"; import { dirname, join } from "node:path"; +import { promisify } from "node:util"; import { createPmCoreScheduler, type JobResult, @@ -32,6 +34,8 @@ export interface PmCoreJobDeps { env?: Record; /** A present file pauses collector ticks for the laptop chaos drill. */ feedPauseFile?: string; + /** Refresh the collector's credentials immediately before each collection. */ + refreshFleetFeedCredentials?: () => Promise; /** Injectable for tests; defaults to the gatherer's own main(). */ loadQuotaMain?: () => Promise<() => Promise>; /** Injectable for tests; defaults to the collector's own main(). */ @@ -44,6 +48,13 @@ export function createPmCoreJobs(options: { feedFile: string } & PmCoreJobDeps): const loadQuotaMain = options.loadQuotaMain ?? (async () => (await import("../scripts/gather-quota.ts")).main); const loadFleetFeedMain = options.loadFleetFeedMain ?? (async () => (await import("../scripts/collect-fleet-feed.ts")).main); + const refreshFleetFeedCredentials = + options.refreshFleetFeedCredentials ?? + (async () => { + const helper = env.PM_CORE_FEED_CREDENTIAL_REFRESH; + if (!helper) return; + await promisify(execFile)(helper, { env: env as NodeJS.ProcessEnv }); + }); return { /** The gatherer's main() reports a failed tick as a non-zero exit @@ -69,6 +80,7 @@ export function createPmCoreJobs(options: { feedFile: string } & PmCoreJobDeps): // The board reads cfg.feedFile; the in-process collector must // publish exactly there. An operator-provided pin always wins. if (!env.FLEET_FEED_OUT) env.FLEET_FEED_OUT = options.feedFile; + await refreshFleetFeedCredentials(); const main = await loadFleetFeedMain(); await main(); }, diff --git a/pm-stack/aggregator/test/age-feed-drill.test.ts b/pm-stack/aggregator/test/age-feed-drill.test.ts index a5a8082011..9647c5acc1 100644 --- a/pm-stack/aggregator/test/age-feed-drill.test.ts +++ b/pm-stack/aggregator/test/age-feed-drill.test.ts @@ -107,7 +107,7 @@ printf '{"degraded":%s,"feed":{"generatedAt":"%s","ageMs":0}}' "$([ "$mode" = st let lockHolder: ReturnType | null = null; if (scn.holdLock) { - lockHolder = Bun.spawn(["flock", join(state, "age-feed.lock"), "sleep", "15"], { + lockHolder = Bun.spawn(["flock", join(state, "pm-drills.lock"), "sleep", "15"], { stdout: "ignore", stderr: "ignore", }); diff --git a/pm-stack/aggregator/test/kill-collector-drill.test.ts b/pm-stack/aggregator/test/kill-collector-drill.test.ts index fb60b84ac5..937b7dbf3a 100644 --- a/pm-stack/aggregator/test/kill-collector-drill.test.ts +++ b/pm-stack/aggregator/test/kill-collector-drill.test.ts @@ -122,7 +122,7 @@ printf '{"feed":{"generatedAt":"%s"},"degraded":false}' "$(cat "${base}/gen-at") let lockHolder: ReturnType | null = null; if (scn.holdLock) { - lockHolder = Bun.spawn(["flock", join(state, "kill-collector.lock"), "sleep", "15"], { + lockHolder = Bun.spawn(["flock", join(state, "pm-drills.lock"), "sleep", "15"], { stdout: "ignore", stderr: "ignore", }); diff --git a/pm-stack/aggregator/test/pm-core-wiring.test.ts b/pm-stack/aggregator/test/pm-core-wiring.test.ts index bae50ea0d1..46a794aa7c 100644 --- a/pm-stack/aggregator/test/pm-core-wiring.test.ts +++ b/pm-stack/aggregator/test/pm-core-wiring.test.ts @@ -160,6 +160,23 @@ describe("pm-core wiring (#8570)", () => { expect(collectorCalls).toBe(1); }); + test("the fleet-feed job refreshes credentials before collecting", async () => { + const calls: string[] = []; + const jobs = createPmCoreJobs({ + feedFile: "/state/fleet-feed.json", + refreshFleetFeedCredentials: async () => { + calls.push("refresh"); + }, + loadFleetFeedMain: async () => async () => { + calls.push("collect"); + }, + }); + + await jobs.runFleetFeed(); + + expect(calls).toEqual(["refresh", "collect"]); + }); + test("the fleet-feed pause file skips collection without loading the collector", async () => { const dir = await mkdtemp(join(tmpdir(), "pm-core-feed-pause-")); const pauseFile = join(dir, "fleet-feed.pause"); From 00e39763c02fb1d9c24efdf2bb35044f2198ba2b Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Tue, 24 Nov 2026 01:38:57 -0600 Subject: [PATCH 3/3] test(pm-stack): use available temp root for install rehearsal --- pm-stack/aggregator/test/install-rehearsal.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pm-stack/aggregator/test/install-rehearsal.sh b/pm-stack/aggregator/test/install-rehearsal.sh index ef1727417a..949830ecc6 100644 --- a/pm-stack/aggregator/test/install-rehearsal.sh +++ b/pm-stack/aggregator/test/install-rehearsal.sh @@ -5,7 +5,9 @@ set -euo pipefail PKG="$(cd "$(dirname "$0")/.." && pwd)" -TMP="$(mktemp -d /tmp/opencode/pm-aggregator-install.XXXXXX)" +TMP_ROOT="${TMPDIR:-${XDG_RUNTIME_DIR:-/tmp}}" +if [[ ! -d "$TMP_ROOT" || ! -w "$TMP_ROOT" ]]; then TMP_ROOT=/tmp; fi +TMP="$(mktemp -d "${TMP_ROOT%/}/pm-aggregator-install.XXXXXX")" # The legacy-store seed below writes through the INSTALL_SRC symlink # into the real package dir, so a pre-existing real store is copied # aside first and restored on every exit path (Codex P1 on PR #8765):