Merge port/shadow-01 (SHADOW-01) into v0.7.0 release candidate
Conflicts: deploy/build/package scripts (flysim-session, fly-shadow and fly-session all built, packaged and given cpuset drop-ins; fly-runtime and fly-shadow-run both converged), fly-legacy-session Cargo.toml and lib.rs (service and shadow both kept, tokio gains signal), runbook and implementation guide (both sections kept).
This commit is contained in:
commit
b3f6d6fbba
40 changed files with 5794 additions and 83 deletions
|
|
@ -479,6 +479,210 @@ in-process and process, and the compatibility string is unchanged.
|
||||||
memory image (0.37 ms, 65,536 shim reads), the three domain calls' JSON, digests and cache
|
memory image (0.37 ms, 65,536 shim reads), the three domain calls' JSON, digests and cache
|
||||||
(about 0.5 ms together) and the task's evaluation, which the legacy loop does too.
|
(about 0.5 ms together) and the task's evaluation, which the legacy loop does too.
|
||||||
|
|
||||||
|
### SHADOW-01 — The session runtime beside the live fly (port slice)
|
||||||
|
|
||||||
|
**2026-09-29: built** on `port/shadow-01` off `port/task-01`, and awaiting review. It changes no
|
||||||
|
live behaviour. flysim gains trace switches that are off unless set, and the compatibility string
|
||||||
|
is unchanged. The contract is [legacy-gameboy-v1](legacy-gameboy-v1.md) section 18: the inputs,
|
||||||
|
the architecture, what is compared, the declared differences, the window and the verdict CUT-01
|
||||||
|
reads.
|
||||||
|
|
||||||
|
- **flysim** (`trace.rs`, `frame.rs`). These additions are recording only:
|
||||||
|
- `FLY_TRACE_DIR` writes one trace file per process. A restart truncated the one `FLY_TRACE`
|
||||||
|
path.
|
||||||
|
- `FLY_TRACE_MAX_BYTES` caps a file; the default in directory mode is 4 GiB.
|
||||||
|
- `FLY_TRACE_LEDGERS=<n>` adds `ledgersDigest` every *n* transitions.
|
||||||
|
- `frame::ledgers_string` is now the one definition of the ledger string. The session task's
|
||||||
|
`ledgers_of` calls it.
|
||||||
|
- **`fly-legacy-session::shadow`** and the binary `fly-shadow`:
|
||||||
|
- `follow` reads the per-process files. It hands out complete lines only, and a file ends when
|
||||||
|
a newer one exists.
|
||||||
|
- `spool` copies every new store generation as it appears. It keeps a floor and a byte bound,
|
||||||
|
and never writes to a live store.
|
||||||
|
- `checkpoint` exports the shadow's capture of a live save's boundary and compares it with the
|
||||||
|
live file byte for byte, after `host-fields` and `archive-order`.
|
||||||
|
- `verdict` is `fly-shadow-verdict-v1` and the cutover rule (`allows_cutover`,
|
||||||
|
`fly-shadow check`).
|
||||||
|
- The runner boots each segment from the live process's startup save (TASK-01's import). It
|
||||||
|
replays the admissions, runs the transition, and takes the live captures in the live order
|
||||||
|
around a deferred rollback. It compares with `trace::compare_line`, which is now shared with
|
||||||
|
`trace::compare`. It stops on the first divergence and writes `divergence.json` with 30
|
||||||
|
transitions of context.
|
||||||
|
- **infra.** `units/flyshadow.service` is report-only and has no `[Install]`. It is not bound to
|
||||||
|
flysim, runs `SCHED_IDLE` and stays stopped on exit status 3. `bin/fly-shadow-run` has the
|
||||||
|
commands `start`, `stop`, `status` and `check`. `05-deploy.sh` converges both and pins the
|
||||||
|
unit to the page and encoder CPUs. `build-flysim.sh` and `package-release.sh` ship
|
||||||
|
`fly-shadow` and `fly-session`. `lint.sh` holds the unit to all of this. The runbook has a
|
||||||
|
"Shadow run (SHADOW-01)" section.
|
||||||
|
- **Rehearsal** (`tools/shadow-rehearsal.sh`). It runs the real `flysim` service and the real
|
||||||
|
`fly-shadow` side by side from one checkpoint, with sugar posted to the control API and service
|
||||||
|
restarts. It runs on a build box, never on a host.
|
||||||
|
|
||||||
|
**Offline rehearsal** (a build box, `tools/shadow-rehearsal.sh`, FAFB in macros mode). The real
|
||||||
|
service ran at real time or unthrottled, with sugar posted every 10 to 20 s and a restart in every
|
||||||
|
run. It totalled **4,090 brain seconds (68 brain minutes), 244,327 transitions, 13 processes and
|
||||||
|
zero divergence**:
|
||||||
|
|
||||||
|
| Run | Start | Brain s | Transitions | What it covered |
|
||||||
|
| --- | --- | --- | --- | --- |
|
||||||
|
| main | the row 67 Pewter Gym stream checkpoint (rung 10), real time, restarts at 12 and 24 min | 2,161 | 129,086 | 126 sugar, 7 rewards, 4,134 macro events, 484 saves byte-identical, a ledger digest every boundary |
|
||||||
|
| reward | row 58 door, adapter ledger thinned (the TASK-01 brain arm, `examples/reward_bearing.rs`) | 601 | 35,894 | the real brain earns `map`, `exploration`, `boundary`, `talk` and `battle` (11 rewards); 138 saves |
|
||||||
|
| rollback | FND-01's `rollback` checkpoint | 302 | 18,056 | a ratchet rollback and the durable save after it; a `talk` reward |
|
||||||
|
| climb | FND-01's `climb` checkpoint | 303 | 18,069 | a ratchet slot save, and the milestone archive before it compared under `archive-order` |
|
||||||
|
| smoke | row 67, unthrottled | 122 | 7,305 | the first run |
|
||||||
|
| final | row 67, real time, the final binary, the lag guard on | 601 | 35,917 | the box was contended by other runs, so the live loop fell behind real time 5 times; each time the guard paused the shadow (667 s in all), and all 143 saves were still compared |
|
||||||
|
|
||||||
|
The reward run's box was loaded: the shadow ran at 25 frames a second against the live 52 and
|
||||||
|
finished 12 minutes behind. Every save was still compared, from the spool.
|
||||||
|
|
||||||
|
`tests/shadow.rs` (ROM, the toy connectome in raw mode) runs the real service through a restart
|
||||||
|
under a shadow, then plants four differences on copies of that run's trace and spool. Each one
|
||||||
|
stops a fresh shadow with the right kind, field and step:
|
||||||
|
|
||||||
|
- a work-RAM digest;
|
||||||
|
- a ledger digest;
|
||||||
|
- a sugar removed, which diverges on the brain at that transition;
|
||||||
|
- a live save's `rankSinceMs`.
|
||||||
|
|
||||||
|
**Cost.** These figures come from a shared 8-core build box, so they are indicative only. Other
|
||||||
|
agents' runs made paired measurements vary by up to 2x.
|
||||||
|
|
||||||
|
- *The shadow.* Over the whole main run it used 1.47 cores to follow 52.3 frames a second. The
|
||||||
|
live service used 1.43 cores for 53.5 frames a second. That is about 28 ms and 27 ms of CPU a
|
||||||
|
frame, so the session runtime costs about what the legacy loop does (x1.05).
|
||||||
|
- *Wall time a frame.* With 2 sweep threads the mean was 14.7 ms on the quieter box. Replaying the
|
||||||
|
main trace unthrottled gave these means:
|
||||||
|
- in-process with 1, 2 and 3 threads: 23.7, 19.7 and 17.0 ms;
|
||||||
|
- thread mode with 2 threads: 18.5 ms;
|
||||||
|
- process mode with 2 threads: 18.5 ms.
|
||||||
|
|
||||||
|
Every replay was identical again: five more comparisons of 20,000 transitions each.
|
||||||
|
- *Memory.* The shadow's resident size was about 130 MB, against the live service's 54 MB.
|
||||||
|
- *The live trace* with a ledger digest every frame costs about 1 ms of CPU a frame in the best
|
||||||
|
paired sample, which is within this box's noise; FND-01 measured about 2 ms. The live loop has
|
||||||
|
1.7-1.8x real-time capacity on 3 threads. The trace is about 750 bytes a transition, which is
|
||||||
|
160 MB per live hour.
|
||||||
|
|
||||||
|
The resource plan for the release container is in the SHADOW-01 run report and in
|
||||||
|
`units/flyshadow.service`:
|
||||||
|
|
||||||
|
- `SCHED_IDLE` on the page and encoder CPUs, never flysim's;
|
||||||
|
- 2 sweep threads;
|
||||||
|
- a back-off whenever the live `fly_lag_seconds` grows;
|
||||||
|
- a 3 GB memory ceiling;
|
||||||
|
- a ledger digest every 60 transitions.
|
||||||
|
|
||||||
|
To keep up, the shadow needs about 1.7 idle cores. With less it runs behind real time: the trace
|
||||||
|
is on disk, the spool covers about 15 minutes of hot saves, and the verdict comes later.
|
||||||
|
|
||||||
|
**Found on the way.** binjgb's exported state does not carry the audio resampler's phase. An
|
||||||
|
emulator imported from a state therefore drifts from a powered-on one in its channel accumulators.
|
||||||
|
The drift shows in the exported bytes only (frame and WRAM are identical). Every restart restores
|
||||||
|
through an import in both runtimes, so the two agree. A fresh start does not import, and the
|
||||||
|
shadow follows one by powering on as well.
|
||||||
|
|
||||||
|
**Gates** (a build box with rom-env): `cargo test --workspace --release` with `--no-fail-fast`
|
||||||
|
had three failures, each accounted for:
|
||||||
|
|
||||||
|
- `flysim` `integration` is the known load-sensitive test. It failed at box load 25 and passes
|
||||||
|
alone.
|
||||||
|
- `rom_macros_mode`'s no-PP turn is red on this base. Row 67 fixes it on main.
|
||||||
|
- A shadow-test threshold depended on the box's speed. It was fixed, and the test passes at load
|
||||||
|
22.
|
||||||
|
|
||||||
|
`clippy --workspace --all-targets -D warnings` is clean. `npm test` passed 688 with 0 failures,
|
||||||
|
typecheck is clean, and `infra/tests/lint.sh` passed every check. The compatibility string is
|
||||||
|
648 B `8ce67b97...` in raw and macros mode, unchanged.
|
||||||
|
|
||||||
|
**Review fix round, 2026-09-29** (APPROVE-WITH-NOTES). The branch was rebased onto port/task-01's
|
||||||
|
fix round, `2fc9fd7`: an artifact-backed task ledger, the palette seed, queued saves and bounded
|
||||||
|
history. The shadow now bounds its coordinator's history per segment. The fixes:
|
||||||
|
|
||||||
|
- *R1.* The verdict hashes `flysim-session`, SERVE-01's service, with the other release binaries.
|
||||||
|
`check` defaults to `--binary flysim-session --current /opt/fly/current`. It requires the
|
||||||
|
verdict's release to be the directory the link resolves to, with every shadowed binary
|
||||||
|
unchanged there.
|
||||||
|
- *R2.* Every session-side failure is a divergence:
|
||||||
|
- a session that does not start;
|
||||||
|
- a restore-gate refusal (`tests/shadow.rs` now plants one);
|
||||||
|
- a capture with no agent;
|
||||||
|
- an unrecorded transition;
|
||||||
|
- an unbuildable trace line.
|
||||||
|
|
||||||
|
Skips carry a kind, and only the live side's own kinds allow a cutover.
|
||||||
|
- *N1.* The live trace needs the shadow's heartbeat to start and to keep going, and flysim keeps
|
||||||
|
the trace directory under 8 GiB. The runbook's claim is corrected.
|
||||||
|
- *N2.* `fly-shadow-run` records a baseline and runs `flyshadow-guard.timer`. The guard stops
|
||||||
|
everything and restarts flysim without the trace on 1 s of lag growth, or when the realtime
|
||||||
|
factor drops below min(0.97, baseline - 0.03). `lint.sh` drives the rule on six cases.
|
||||||
|
- *N3.* Both `pass` and the cutover require one live save compared per 600 brain seconds, with at
|
||||||
|
most 10 % unavailable. The cutover also requires a shadow at most 3,600 transitions behind.
|
||||||
|
|
||||||
|
**Cost re-measured on the rebased tip.** This was a 12-brain-minute rehearsal on the same box,
|
||||||
|
at real time, with a restart and the guard on. It had 43,104 transitions, 197 saves byte-identical
|
||||||
|
and zero divergence. The box was contended by other runs again; the guard paused the shadow for
|
||||||
|
911 s and it still passed. Unthrottled replays of its trace, all identical, gave these mean
|
||||||
|
milliseconds per frame:
|
||||||
|
|
||||||
|
| Mode | ms per frame (mean) |
|
||||||
|
| --- | --- |
|
||||||
|
| in-process, 2 threads | 15.1 |
|
||||||
|
| in-process, 3 threads | 13.3 |
|
||||||
|
| thread mode, 3 threads | 14.9 |
|
||||||
|
| process mode, 2 threads | 15.4 |
|
||||||
|
|
||||||
|
Earlier the same 2-thread and 3-thread in-process arms took 19.7 and 17.0 ms. With 3 threads the
|
||||||
|
shadow keeps real time with about 20 % to spare.
|
||||||
|
|
||||||
|
**Review round 2, 2026-09-30** (APPROVE-WITH-NOTES; R3 and G1 were required before `start`).
|
||||||
|
The branch was rebased onto port/task-01 `eaf588d`, and main v0.6.7 was merged in: row 68 and
|
||||||
|
adapter `pokered-unique8-v8`. The live shadow will therefore carry the v8 compatibility string.
|
||||||
|
The fixtures were already v8 on main.
|
||||||
|
|
||||||
|
- *R3.* `allows_cutover` floors the window at `REQUIRED_BRAIN_SECONDS` (10,800). A verdict run with
|
||||||
|
a shorter `--required-brain-seconds` passes as a rehearsal but never passes `check`. There is a
|
||||||
|
test case for this.
|
||||||
|
- *G1, the host guard.*
|
||||||
|
- `start` measures a 10-minute baseline of 60 samples before the shadow exists: the median RTF,
|
||||||
|
its spread as 1.4826 x MAD, and the lag growth rate over the most recent half.
|
||||||
|
- The guard trips only on a sustained degradation *against that baseline*: 3 checks in a row in
|
||||||
|
which the last 5 samples of the same process fall below it, in RTF or in lag rate, by more
|
||||||
|
than max(0.05, 4 x spread / sqrt 5).
|
||||||
|
- It stops itself when the shadow is not running. `check` refuses after a trip or with the
|
||||||
|
shadow down.
|
||||||
|
- Tested over two kinds of trace:
|
||||||
|
- *Synthetic*, shaped on the release container: a flat 0.66, 0.77-0.99 and 0.6-1.0 noisy, per
|
||||||
|
second and per sample, and real time with hiccups. There was no false trip in 800 3-hour
|
||||||
|
runs, and every one of 400 degradations tripped (to 0.55-0.75, and 0.66 to 0.58).
|
||||||
|
- *Recorded* from a real flysim, now fixtures: alone (at about 1.0, and at 0.4-1.0 under box
|
||||||
|
load) no trip; with a real idle shadow on other cpus no trip; with a real shadow on the fly's
|
||||||
|
own cpu (0.66 to 0.44-0.60) a trip at check 7.
|
||||||
|
- One recording had a load step inside its baseline, which widened a mean/sd baseline to a
|
||||||
|
0.25 margin. That is why the baseline is robust.
|
||||||
|
- *G1, the in-shadow back-off* (`LagJudge`). It pauses the shadow while the live lag grows faster
|
||||||
|
than the baseline rate plus the margin (re-read from `baseline.json`). It lifts itself for
|
||||||
|
10 minutes when a pause did not help, because then the shadow is not the cause. Tests show:
|
||||||
|
- a flat 0.66 fly is never paused;
|
||||||
|
- with no baseline, at most 1 minute in 11 is paused;
|
||||||
|
- a shadow that costs the fly time stays paused about half the time.
|
||||||
|
- *N3.* `lagTransitions` is recomputed at every verdict write, over the rest of the current file
|
||||||
|
and every newer one, including while the shadow is backed off.
|
||||||
|
|
||||||
|
**2026-09-30: `tests/shadow.rs` "one trace file per process" (0 vs 2) on a build box.** It is not
|
||||||
|
a timing, load or segment-handling bug.
|
||||||
|
- *Cause.* The failing runs used a `flysim` binary that was not built from the tree under test.
|
||||||
|
`cargo test -p fly-legacy-session` does not build `flysim`'s binary, and the build box's bx
|
||||||
|
target directory was shared by name with other trees. That binary predated `FLY_TRACE_DIR`, so
|
||||||
|
it wrote no trace at all. The failure was reproduced by running such a test binary against its
|
||||||
|
own stale `flysim`.
|
||||||
|
- *Fix.* The test now builds the `flysim` binary itself: `cargo build -p flysim --bin flysim`,
|
||||||
|
with the same target directory and profile, which does nothing when the binary is current.
|
||||||
|
This was proved on a target that another tree's `flysim` had populated.
|
||||||
|
- *What production could miss, and now cannot.* A live process that runs without a trace is now
|
||||||
|
a `coverage` divergence (above). That covers a process whose consumer check failed, and one
|
||||||
|
whose trace could not be created. In `FLY_TRACE_DIR` mode, a trace-creation failure no longer
|
||||||
|
stops flysim from starting. The test adds such a process, untraced, and the shadow fails.
|
||||||
|
|
||||||
### STATE-01 — Coherent all-participant checkpoint/recovery
|
### STATE-01 — Coherent all-participant checkpoint/recovery
|
||||||
|
|
||||||
**Depends on:** SESSION-02, MEDIA-01; validate with fake agents first, then AGENT-01/ENV-01.
|
**Depends on:** SESSION-02, MEDIA-01; validate with fake agents first, then AGENT-01/ENV-01.
|
||||||
|
|
|
||||||
|
|
@ -705,3 +705,176 @@ graph validation for new bundles, and the composite behaviour identity of FOUNDA
|
||||||
**not** in this document. They ship with PROF-02b, before DATA-01, as their own contract.
|
**not** in this document. They ship with PROF-02b, before DATA-01, as their own contract.
|
||||||
Nothing here constrains them, except that a new profile never reuses this profile's id or its
|
Nothing here constrains them, except that a new profile never reuses this profile's id or its
|
||||||
legacy exception.
|
legacy exception.
|
||||||
|
|
||||||
|
## 18. The shadow run (SHADOW-01)
|
||||||
|
|
||||||
|
**Amendment, 2026-09-29 (SHADOW-01).** The operator's decision of 2026-09-23 gates the automatic
|
||||||
|
cutover (CUT-01) on "a 3-hour shadow run with zero divergence". This section fixes what that
|
||||||
|
means. The implementation is `fly-legacy-session::shadow` and the binary `fly-shadow`, with the unit
|
||||||
|
`infra/units/flyshadow.service` and the script `infra/bin/fly-shadow-run`.
|
||||||
|
|
||||||
|
**The inputs.** The legacy loop is deterministic, given two things: the state a process starts
|
||||||
|
from and the admissions applied at the top of each frame. Every nondeterministic input reaches
|
||||||
|
the fly through one of those two:
|
||||||
|
|
||||||
|
| Input | How it reaches the fly | How the shadow gets it |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Restart, watchdog kill, `fly-loop-recover`, `fly-reset-to-milestone`, deploy | A new process restores a checkpoint (section 14), or warms up a fresh fly, and writes a durable startup save of the state it starts from | The trace's start line names that save (`g<N>`); the shadow boots a new session from it through the ordinary FLYSIM01 import |
|
||||||
|
| Sugar (`POST /stimulate`) | Admitted on wall time and the live pulse (rate limiter, "no overlap"), applied at the top of a frame | The transition's `admissions`, replayed into the admission queue (`LegacyAdmission::replay_sugar`) |
|
||||||
|
| Operator reward pulse (`POST /reward`) | Off in every shipped configuration (403) | Cannot be reproduced (section 15 amendment): the rest of that segment is reported uncompared |
|
||||||
|
| Wall time | Pacing, publish rate, checkpoint intervals, pause (no frame runs). None changes a transition | Not needed. The trace records which saves were taken where |
|
||||||
|
| Chat | A caption track; it reaches nothing the fly does | Not needed |
|
||||||
|
| Threads | The sweep's result does not depend on the thread count (AGENT-01) | The shadow picks its own |
|
||||||
|
|
||||||
|
So "the same inputs" means *the same start state per process and the same admissions per
|
||||||
|
transition*. Admission itself is not compared. The session runtime decides admission against a
|
||||||
|
pulse one commit stale, by the operator's decision (section 15). A shadow that re-decided sugar on
|
||||||
|
its own clock would diverge by design, not by fault.
|
||||||
|
|
||||||
|
**The architecture: the legacy fly stays primary, and the shadow follows its trace.** The live
|
||||||
|
service writes `FLY_TRACE` (FND-01) with three switches added for the shadow. None changes a
|
||||||
|
behaviour field or anything the fly does:
|
||||||
|
|
||||||
|
- `FLY_TRACE_DIR` writes one file per process, `trace-<start wall ms>-<pid>.jsonl`.
|
||||||
|
- `FLY_TRACE_MAX_BYTES` caps each file (4 GiB by default in directory mode).
|
||||||
|
- `FLY_TRACE_LEDGERS=<n>` adds `ledgersDigest` every *n* transitions. This is the SHA-256 of
|
||||||
|
`flysim::frame::ledgers_string` after the boundary: adapter export, ratchet, slot, and the
|
||||||
|
executor's scene, bound set, running macro, counts and "nearer".
|
||||||
|
|
||||||
|
`fly-shadow` follows the files in start order. For each file it takes these steps:
|
||||||
|
|
||||||
|
1. It boots a session (agent, world, task and executor, as in TASK-01) from that process's startup
|
||||||
|
save. A fresh start is different: the stores were empty and the startup save is at boundary 0.
|
||||||
|
In that case the shadow runs the same power-on scaffold and warm-up
|
||||||
|
(`Environment.Initialize`, `Agent.Initialize`), and holds the startup save to its own
|
||||||
|
boundary 0, byte for byte. An import would not give the same emulator. binjgb's audio
|
||||||
|
resampler phase is not in its exported state, so the channel accumulators of an imported
|
||||||
|
emulator drift from those of a powered-on one, in the exported state only. Both restores of a
|
||||||
|
restart import, so they agree.
|
||||||
|
2. For every transition, it replays the admissions and runs `Coordinator::step`. It takes a
|
||||||
|
capture wherever the live trace records one, before or after the boundary's rollback as the
|
||||||
|
live loop took it, then applies the deferred rollback.
|
||||||
|
3. It builds its own trace line from what crossed the session's boundaries (`trace::line`) and
|
||||||
|
compares it with the live line, field by field.
|
||||||
|
|
||||||
|
A spool thread copies every new store generation as it appears, because a hot file lives only
|
||||||
|
about ten seconds. The shadow never writes to the live stores.
|
||||||
|
|
||||||
|
The reverse arrangement was considered: the session runtime as primary, with legacy as the
|
||||||
|
checker. It would make the shadow run the cutover itself, and a divergence would already be on
|
||||||
|
the stream. A second legacy process in lockstep was also considered. It adds nothing, because the
|
||||||
|
live process's own trace *is* the legacy behaviour.
|
||||||
|
|
||||||
|
**What is compared, per boundary.**
|
||||||
|
|
||||||
|
- *The trace line*, every transition. The fields are `step`, `admissions`, `ticksAdvanced`,
|
||||||
|
`brainTicks`, `remainder`, `ratesDigest`, `spikesDigest`, `spikeCount`, `decision`, `mask`,
|
||||||
|
`macroEvents`, `framebufferDigest`, `wramDigest`, `rewards`, `rank`, `acknowledgedBoundary`
|
||||||
|
and `boundaryActions`. `boundaryActions` covers the slot saves with their state digests and
|
||||||
|
the rollbacks.
|
||||||
|
- *The ledgers*: `ledgersDigest` on the transitions that carry it. The shadow digests the same
|
||||||
|
string from its own task (`task::ledgers_of` is `ledgers_string`). This covers the executor's
|
||||||
|
ledgers, which no checkpoint carries.
|
||||||
|
- *The checkpoint bytes*, at every live save the spool still holds. The shadow captures the same
|
||||||
|
boundary and exports FLYSIM01 through the shared encoder (STATE-02). It compares the export
|
||||||
|
byte for byte with the live file after the substitutions named below. `compatibility`,
|
||||||
|
`speed` and `rankSinceMs` are the shadow's own, so they are compared too.
|
||||||
|
|
||||||
|
**Declared differences**, excluded by name. The verdict lists the same names.
|
||||||
|
|
||||||
|
| Name | What is excluded |
|
||||||
|
| --- | --- |
|
||||||
|
| `archive-order` | A legacy milestone archive taken before that boundary's slot save (`afterActions` 0 ahead of a `save-slot`, sections 4 and 16) holds the pre-capture ratchet and slot. The live file's `ratchet`, `ratchetGame` and `ratchetFrame` stand in for the shadow's in that capture only. The operator accepted this on 2026-09-23 ("Archive order") |
|
||||||
|
| `decision-list-order` | The decision is compared as `gameboy-channels-v1` sees it (section 6, `trace::channels`) |
|
||||||
|
| `host-fields` | `generation`, `wallMs` and `lastEventId` are the live file's. They are host bookkeeping: the shadow keeps no feed event log (SERVE-01's service host keeps its own) and allocates no generations, because it writes no store |
|
||||||
|
| `admission-replay` | Sugar is replayed, not re-decided (above) |
|
||||||
|
| `operator-reward-pulse` | A segment with one is reported uncompared from that transition on |
|
||||||
|
|
||||||
|
**The window.** The verdict is `pass` once the compared transitions add up to **10,800 s of
|
||||||
|
live brain time** (the sum of `ticksAdvanced`, 3 h at real time) with zero divergence, and at least
|
||||||
|
one live save per 600 of those brain seconds has been compared byte for byte. That time may span
|
||||||
|
several processes.
|
||||||
|
|
||||||
|
*Skips* are only the live side's own events (`SKIP_KINDS`):
|
||||||
|
|
||||||
|
- `startup-save-gone`: a process whose startup save was already gone when the shadow reached it,
|
||||||
|
because the shadow started late or its spool evicted the file;
|
||||||
|
- `operator-reward-pulse`;
|
||||||
|
- `trace-cap`: the live trace stopped at its byte cap, or with no consumer;
|
||||||
|
- `no-transition`: a process that ran none.
|
||||||
|
|
||||||
|
A skip adds nothing to the window. A trace the shadow cannot read is `trace-malformed`, which
|
||||||
|
refuses the cutover. A process killed hard loses its unflushed tail, and those transitions are
|
||||||
|
not compared.
|
||||||
|
|
||||||
|
The first difference of any kind stops the shadow with `diverged` (exit status 3) and writes
|
||||||
|
`divergence.json` with the 30 transition pairs before it. The same applies to every session-side
|
||||||
|
failure, which is **never** a skip:
|
||||||
|
|
||||||
|
- a trace field;
|
||||||
|
- the ledgers;
|
||||||
|
- the checkpoint bytes;
|
||||||
|
- a session that does not start;
|
||||||
|
- a startup save the candidate's restore gate refuses or the session runtime cannot restore;
|
||||||
|
- a step, capture or rollback error;
|
||||||
|
- a transition the session did not record;
|
||||||
|
- *coverage*: a live flysim process that booted while the shadow ran and left no trace
|
||||||
|
(amended 2026-09-30).
|
||||||
|
|
||||||
|
The shadow reads every boot header in the live sugar journal. Every flysim process writes one,
|
||||||
|
traced or not. It holds each header to a trace file created after the previous boot and before
|
||||||
|
this one. A process that ran untraced can never be compared, so the verdict fails. It does not
|
||||||
|
pass on the processes that were traced.
|
||||||
|
|
||||||
|
A shadow that keeps running after `pass` turns the verdict to `diverged` on a later difference.
|
||||||
|
|
||||||
|
**The live fly never pays for the shadow (amended by the SHADOW-01 review).** Three mechanisms
|
||||||
|
make sure of it:
|
||||||
|
|
||||||
|
- *The trace is on only while a shadow consumes it.* The shadow writes a heartbeat
|
||||||
|
(`<trace dir>/consumer`) every 30 s and removes it when it stops. flysim starts no trace without
|
||||||
|
a fresh heartbeat, stops a running one within a minute of frames once the heartbeat is more than
|
||||||
|
10 minutes old, and keeps the directory under 8 GiB. A heartbeat dated ahead of flysim's clock
|
||||||
|
counts as fresh. A trace flysim cannot create (a full disk, the directory's permissions) never
|
||||||
|
stops the live fly from starting: that process runs untraced, and the shadow reports it as a
|
||||||
|
coverage divergence.
|
||||||
|
- *The guard* (`fly-shadow-run guard`, every 60 s, root) judges the live fly against its own pace
|
||||||
|
before the shadow existed. The live fly does not always keep real time: the release container
|
||||||
|
has run at a realtime factor of 0.66, and at 0.77-0.99 after its cpuset rebalance. So `start`
|
||||||
|
first measures a 10-minute baseline over sixty 10-s `fly_realtime_factor` means. It records
|
||||||
|
their median and their spread (1.4826 x MAD), so a step in the window cannot set or widen it,
|
||||||
|
and the `fly_lag_seconds` growth rate over the most recent half. The guard trips only on a *sustained* degradation against
|
||||||
|
that baseline: 3 checks in a row in which the last 5 samples of the same process fall below the
|
||||||
|
baseline realtime factor, or grow lag faster than the baseline rate, by more than
|
||||||
|
max(0.05, 4 x spread / sqrt 5). A trip stops everything and restarts flysim without the trace.
|
||||||
|
The guard stops itself when the shadow is not running. `lint.sh` holds the rule to the release
|
||||||
|
container's profiles, synthesized, and to four traces recorded from a real flysim with and
|
||||||
|
without a real shadow (`infra/tests/fixtures/shadow-guard`). In 800 synthetic 3-hour runs it
|
||||||
|
found no false trip, and it caught all 400 degradations.
|
||||||
|
- *The shadow* runs at `SCHED_IDLE` off flysim's CPUs. It pauses for a minute while the live lag
|
||||||
|
grows faster than the baseline rate. When a pause does not help, the shadow is not the cause,
|
||||||
|
and it stops pausing for 10 minutes.
|
||||||
|
|
||||||
|
**The verdict contract (for CUT-01).** The shadow writes `verdict.json` in the format
|
||||||
|
`fly-shadow-verdict-v1` (`shadow::verdict`, whose module notes list the fields). CUT-01 cuts over
|
||||||
|
automatically only if all of the following hold when it reads the file, at the moment of cutting
|
||||||
|
over:
|
||||||
|
|
||||||
|
- `status` is `pass` and `firstDivergence` is `null`;
|
||||||
|
- `compared.brainSeconds` ≥ `required.brainSeconds`, and never less than the operator's 10,800 s,
|
||||||
|
whatever window the shadow was run with;
|
||||||
|
- *Saves were compared.* At least one per 600 brain seconds was compared byte for byte, and at
|
||||||
|
most 10 % of those the trace named were unavailable.
|
||||||
|
- *The release.* `candidate.release` is the directory `/opt/fly/current` resolves to now. Every
|
||||||
|
binary in `candidate.binaries` still has its recorded SHA-256 there. The binary switched to,
|
||||||
|
`flysim-session` (SERVE-01's service), is one of them.
|
||||||
|
- `candidate.compatibility` is the live `--print-compatibility`;
|
||||||
|
- every `skipped` entry is one of the live side's own kinds;
|
||||||
|
- *the shadow is alive and caught up*: `updatedAt` is at most 5 minutes old and
|
||||||
|
`lagTransitions` is at most 3,600, counted at every write (paused or not) over the rest of the
|
||||||
|
current file and every newer one;
|
||||||
|
- (`fly-shadow-run check`) the guard has not tripped and `flyshadow.service` is running.
|
||||||
|
|
||||||
|
`fly-shadow check` (and `fly-shadow-run check`) implements exactly this rule and exits 0 only when
|
||||||
|
it holds. Anything else keeps the legacy fly. The one-command rollback `fly-runtime legacy` is
|
||||||
|
CUT-01's.
|
||||||
|
|
|
||||||
|
|
@ -710,10 +710,14 @@ if [ -n "${CPUSET:-}" ]; then
|
||||||
# it is enabled it serves the page from the page's CPUs, never from flysim's.
|
# it is enabled it serves the page from the page's CPUs, never from flysim's.
|
||||||
# flysim-session (SERVE-01) is the session runtime's standalone unit: flysim's cores.
|
# flysim-session (SERVE-01) is the session runtime's standalone unit: flysim's cores.
|
||||||
# (`fly-runtime session` runs it AS flysim.service, which already has them.)
|
# (`fly-runtime session` runs it AS flysim.service, which already has them.)
|
||||||
for u in flysim xvfb flystage flystage-web flycast pulse mediamtx flyedge flysim-session; do
|
# flyshadow (SHADOW-01) is off by default too; when started it gets every CPU that is not
|
||||||
|
# flysim's, at SCHED_IDLE (its unit), so it only ever uses what the page and the encoder
|
||||||
|
# leave idle and never a cycle of the live fly's.
|
||||||
|
for u in flysim xvfb flystage flystage-web flycast pulse mediamtx flyedge flysim-session flyshadow; do
|
||||||
case "$u" in
|
case "$u" in
|
||||||
flysim|flysim-session) cpus="$sim_cpus" ;;
|
flysim|flysim-session) cpus="$sim_cpus" ;;
|
||||||
flycast) cpus="$encoder_cpus" ;;
|
flycast) cpus="$encoder_cpus" ;;
|
||||||
|
flyshadow) cpus="${page_cpus},${encoder_cpus}" ;;
|
||||||
*) cpus="$page_cpus" ;;
|
*) cpus="$page_cpus" ;;
|
||||||
esac
|
esac
|
||||||
{
|
{
|
||||||
|
|
@ -741,7 +745,7 @@ fi
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
log "05-deploy: converging bin/ helpers to /opt/fly/bin"
|
log "05-deploy: converging bin/ helpers to /opt/fly/bin"
|
||||||
ct_exec "$CTID" -- mkdir -p /opt/fly/bin
|
ct_exec "$CTID" -- mkdir -p /opt/fly/bin
|
||||||
for name in fly-watchdog fly-loop-recover fly-loop-reset fly-recap fly-retention fly-reset-to-milestone fly-runtime flypush flystage-launch flycast-launch wait-for-x wait-for-stage wait-for-health; do
|
for name in fly-watchdog fly-loop-recover fly-loop-reset fly-recap fly-retention fly-reset-to-milestone fly-runtime fly-shadow-run flypush flystage-launch flycast-launch wait-for-x wait-for-stage wait-for-health; do
|
||||||
converge_file "$CTID" "$INFRA_DIR/bin/$name" "/opt/fly/bin/$name" 0755 root:root >/dev/null
|
converge_file "$CTID" "$INFRA_DIR/bin/$name" "/opt/fly/bin/$name" 0755 root:root >/dev/null
|
||||||
done
|
done
|
||||||
|
|
||||||
|
|
|
||||||
401
infra/bin/fly-shadow-run
Executable file
401
infra/bin/fly-shadow-run
Executable file
|
|
@ -0,0 +1,401 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# infra/bin/fly-shadow-run — start, stop, guard and read SHADOW-01's shadow run on the release
|
||||||
|
# container. Pushed to /opt/fly/bin/fly-shadow-run by 05-deploy.sh. Run as root inside the
|
||||||
|
# container, by the coordinator, with the container claimed in the host's agent claim log (one
|
||||||
|
# agent at a time).
|
||||||
|
#
|
||||||
|
# fly-shadow-run start baseline the live fly (10 min), turn flysim's trace on, start flyshadow.service
|
||||||
|
# and the live-impact guard, restart flysim once
|
||||||
|
# fly-shadow-run stop stop the shadow and the guard, turn the trace off (at flysim's next
|
||||||
|
# restart; --restart-flysim restarts it now), remove trace and spool
|
||||||
|
# fly-shadow-run status the verdict in one screen
|
||||||
|
# fly-shadow-run check CUT-01's hook: exit 0 only if the verdict allows the automatic cutover
|
||||||
|
# into the release /opt/fly/current points to, onto flysim-session
|
||||||
|
# fly-shadow-run guard (flyshadow-guard.timer, every 60 s) stop everything and restart flysim
|
||||||
|
# without the trace if the live fly pays for the shadow
|
||||||
|
# fly-shadow-run simulate BASELINE.jsonl CHECKS.jsonl the guard's rule over recorded samples
|
||||||
|
# fly-shadow-run baseline SAMPLES.jsonl the baseline those samples give
|
||||||
|
#
|
||||||
|
# The shadow is report-only (infra/units/flyshadow.service). `start` restarts flysim.service once,
|
||||||
|
# the same operator action as the unstick rule's restart: a restore keeps the rung and clears the
|
||||||
|
# ledgers. It is needed because flysim reads FLY_TRACE_DIR at start, and because the shadow can
|
||||||
|
# only follow a process from that process's own startup save.
|
||||||
|
#
|
||||||
|
# The trace cannot outlive the shadow: flysim starts no trace, and stops a running one within a
|
||||||
|
# minute, when the shadow's heartbeat (<trace dir>/consumer, every 30 s) is missing or older than
|
||||||
|
# 10 minutes; flysim also keeps the trace directory under 8 GiB, and the shadow deletes every file
|
||||||
|
# it has compared.
|
||||||
|
#
|
||||||
|
# The guard (SHADOW-01 review N2, recalibrated by round 2, G1). The live fly does not always run
|
||||||
|
# at real time (the release CT has run at a realtime factor of 0.66, and 0.77-0.99 after its cpuset
|
||||||
|
# rebalance), so the guard judges the live fly against ITSELF, before the shadow existed:
|
||||||
|
# - `start` first samples the live fly over FLY_SHADOW_BASELINE_SECONDS (600): sixty 10-s means
|
||||||
|
# of fly_realtime_factor and fly_lag_seconds. The BASELINE is robust: the median RTF, its
|
||||||
|
# spread (1.4826 x the median absolute deviation) and the lag growth rate over the most recent
|
||||||
|
# half (seconds of lag per wall second: about 1 - RTF when the loop is behind real time), so a
|
||||||
|
# step within the window neither sets the baseline nor widens the margin. It refuses to start
|
||||||
|
# on fewer than half the samples running.
|
||||||
|
# - Every 60 s the guard takes one 10-s sample. Over the last 5 samples of the same flysim
|
||||||
|
# process (a restart starts the window again) it compares the mean RTF and the lag growth
|
||||||
|
# rate with the baseline. The margin is max(0.05, 4 x the baseline spread / sqrt(5)), so it
|
||||||
|
# scales with how noisy this fly already was.
|
||||||
|
# - It TRIPS only on a SUSTAINED degradation: 3 checks in a row with the 5-sample mean RTF below
|
||||||
|
# the baseline mean minus the margin, or the lag growth rate above the baseline rate plus it.
|
||||||
|
# A paused, booting or recovering fly is not judged.
|
||||||
|
# `fly-shadow-run simulate BASELINE.jsonl CHECKS.jsonl` runs this rule over recorded samples;
|
||||||
|
# lint drives it over real and synthetic RTF traces (infra/tests/fixtures/shadow-guard/).
|
||||||
|
# Tripping stops flyshadow.service and the guard timer, removes the trace drop-in, restarts
|
||||||
|
# flysim.service without the trace, and writes /srv/fly/shadow/guard-tripped.json. When the shadow
|
||||||
|
# is no longer running (it diverged, passed and stopped, or crashed), the guard stops its own
|
||||||
|
# timer and changes nothing: it only ever acts against a running shadow. "No longer running" means
|
||||||
|
# ActiveState inactive or failed (systemctl show), never activating: the shadow's 10-s crash-restart
|
||||||
|
# delay must not switch the guard off. `check` also requires the guard timer active and baseline.json.
|
||||||
|
#
|
||||||
|
# Files (all owned by fly):
|
||||||
|
# /srv/fly/shadow/trace/trace-<ms>-<pid>.jsonl flysim's per-process trace (4 GiB each, 8 in all)
|
||||||
|
# /srv/fly/shadow/trace/consumer the shadow's heartbeat
|
||||||
|
# /srv/fly/shadow/spool/ copies of the live saves, bounded (512 MiB)
|
||||||
|
# /srv/fly/shadow/verdict.json fly-shadow-verdict-v1 (the CUT-01 contract)
|
||||||
|
# /srv/fly/shadow/divergence.json the first divergence with its context
|
||||||
|
# /srv/fly/shadow/baseline.json the guard's baseline (and baseline-samples.jsonl)
|
||||||
|
# /srv/fly/shadow/guard-state.json the guard's recent samples
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
SHADOW_DIR="${FLY_SHADOW_DIR:-/srv/fly/shadow}"
|
||||||
|
DROPIN_DIR=/etc/systemd/system/flysim.service.d
|
||||||
|
DROPIN="$DROPIN_DIR/shadow-trace.conf"
|
||||||
|
BIN="${FLY_SHADOW_BIN:-/opt/fly/current/fly-shadow}"
|
||||||
|
METRICS_URL="${FLY_METRICS_URL:-http://127.0.0.1:9101}"
|
||||||
|
CONTROL_URL="${FLY_CONTROL_URL:-http://127.0.0.1:7401}"
|
||||||
|
# The ledger digest period in transitions: about one a second. Every boundary is proved in the
|
||||||
|
# offline rehearsal (the SHADOW-01 report); on the stream a digest a second bounds the extra work.
|
||||||
|
LEDGERS_EVERY="${FLY_SHADOW_LEDGERS_EVERY:-60}"
|
||||||
|
BASELINE_SECONDS="${FLY_SHADOW_BASELINE_SECONDS:-600}"
|
||||||
|
|
||||||
|
die() { echo "fly-shadow-run: $*" >&2; exit 2; }
|
||||||
|
log() { echo "fly-shadow-run: $*"; }
|
||||||
|
|
||||||
|
need_root() { [ "$(id -u)" = 0 ] || die "run as root (it installs a drop-in and restarts flysim)"; }
|
||||||
|
|
||||||
|
# One JSON sample of the live fly: {t, status, rtMean, lag, uptime}, the realtime factor averaged
|
||||||
|
# over 10 one-second reads.
|
||||||
|
sample() {
|
||||||
|
python3 - "$METRICS_URL" "$CONTROL_URL" <<'PY'
|
||||||
|
import json, sys, time, urllib.request
|
||||||
|
metrics_url, control_url = sys.argv[1], sys.argv[2]
|
||||||
|
def metrics():
|
||||||
|
text = urllib.request.urlopen(metrics_url + "/metrics", timeout=3).read().decode()
|
||||||
|
out = {}
|
||||||
|
for line in text.splitlines():
|
||||||
|
if line.startswith("#"):
|
||||||
|
continue
|
||||||
|
parts = line.split()
|
||||||
|
if len(parts) == 2:
|
||||||
|
try:
|
||||||
|
out[parts[0]] = float(parts[1])
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
return out
|
||||||
|
factors = []
|
||||||
|
for _ in range(10):
|
||||||
|
factors.append(metrics().get("fly_realtime_factor", 0.0))
|
||||||
|
time.sleep(1)
|
||||||
|
m = metrics()
|
||||||
|
try:
|
||||||
|
status = json.load(urllib.request.urlopen(control_url + "/status", timeout=3)).get("status")
|
||||||
|
except Exception:
|
||||||
|
status = None
|
||||||
|
print(json.dumps({"t": time.time(), "status": status, "rtMean": sum(factors) / len(factors),
|
||||||
|
"lag": m.get("fly_lag_seconds"), "uptime": m.get("fly_uptime_seconds")}))
|
||||||
|
PY
|
||||||
|
}
|
||||||
|
|
||||||
|
# The guard's rule, one definition for `baseline`, `decide` and `simulate`.
|
||||||
|
GUARD_PY='
|
||||||
|
import json, math, sys
|
||||||
|
WINDOW, SUSTAIN, MIN_MARGIN = 5, 3, 0.05
|
||||||
|
|
||||||
|
def running(s):
|
||||||
|
return s.get("status") == "running" and s.get("lag") is not None and s.get("uptime") is not None
|
||||||
|
|
||||||
|
def rate(samples):
|
||||||
|
"""Lag growth per wall second over the longest same-process run of samples."""
|
||||||
|
best, run = None, []
|
||||||
|
for s in samples:
|
||||||
|
if run and s["uptime"] < run[-1]["uptime"]:
|
||||||
|
run = []
|
||||||
|
run.append(s)
|
||||||
|
if len(run) >= 2 and (best is None or len(run) > len(best)):
|
||||||
|
best = list(run)
|
||||||
|
if not best or best[-1]["t"] <= best[0]["t"]:
|
||||||
|
return None
|
||||||
|
return max(0.0, (best[-1]["lag"] - best[0]["lag"]) / (best[-1]["t"] - best[0]["t"]))
|
||||||
|
|
||||||
|
def baseline(samples):
|
||||||
|
"""Robust statistics of the running samples: a step in the live fly within the window (its own
|
||||||
|
warm-up, a load coming or going) must neither set the baseline nor widen the margin, as long
|
||||||
|
as most of the window is on one side of it. The RTF is the median; its spread is 1.4826 x the
|
||||||
|
median absolute deviation, which estimates the standard deviation without the step; the lag
|
||||||
|
growth rate is taken over the most recent half, after any early step."""
|
||||||
|
ok = [s for s in samples if running(s)]
|
||||||
|
if len(ok) < max(3, len(samples) // 2):
|
||||||
|
raise SystemExit("baseline: only %d of %d samples running" % (len(ok), len(samples)))
|
||||||
|
recent = ok[len(ok) // 2:]
|
||||||
|
rtf = sorted(s["rtMean"] for s in ok)
|
||||||
|
median = rtf[len(rtf) // 2] if len(rtf) % 2 else (rtf[len(rtf) // 2 - 1] + rtf[len(rtf) // 2]) / 2
|
||||||
|
dev = sorted(abs(x - median) for x in rtf)
|
||||||
|
mad = dev[len(dev) // 2] if len(dev) % 2 else (dev[len(dev) // 2 - 1] + dev[len(dev) // 2]) / 2
|
||||||
|
sd = 1.4826 * mad
|
||||||
|
lag_rate = rate(recent)
|
||||||
|
return {"rtfMean": median, "rtfSd": sd, "lagRate": lag_rate if lag_rate is not None else 0.0,
|
||||||
|
"samples": len(ok), "margin": max(MIN_MARGIN, 4 * sd / math.sqrt(WINDOW))}
|
||||||
|
|
||||||
|
def decide(base, state, s):
|
||||||
|
"""Returns (state, verdict); the verdict starts with ok or trip."""
|
||||||
|
history, run = state.get("history", []), state.get("degradedRun", 0)
|
||||||
|
if not running(s):
|
||||||
|
return state, "ok (flysim is %s: not judged)" % s.get("status")
|
||||||
|
if history and s["uptime"] < history[-1]["uptime"]:
|
||||||
|
history, run = [], 0
|
||||||
|
history = (history + [s])[-WINDOW:]
|
||||||
|
state = {"history": history, "degradedRun": run}
|
||||||
|
if len(history) < WINDOW:
|
||||||
|
state["degradedRun"] = 0
|
||||||
|
return state, "ok (warming: %d of %d samples in this process)" % (len(history), WINDOW)
|
||||||
|
rtf = sum(h["rtMean"] for h in history) / WINDOW
|
||||||
|
lag_rate = rate(history) or 0.0
|
||||||
|
m = base["margin"]
|
||||||
|
why = []
|
||||||
|
if rtf < base["rtfMean"] - m:
|
||||||
|
why.append("realtime factor %.3f < baseline %.3f - %.3f" % (rtf, base["rtfMean"], m))
|
||||||
|
if lag_rate > base["lagRate"] + m:
|
||||||
|
why.append("lag growth %.3f s/s > baseline %.3f + %.3f" % (lag_rate, base["lagRate"], m))
|
||||||
|
state["degradedRun"] = run + 1 if why else 0
|
||||||
|
if state["degradedRun"] >= SUSTAIN:
|
||||||
|
return state, "trip " + "; ".join(why) + " (%d checks in a row)" % state["degradedRun"]
|
||||||
|
if why:
|
||||||
|
return state, "ok degraded %d/%d: %s" % (state["degradedRun"], SUSTAIN, "; ".join(why))
|
||||||
|
return state, "ok"
|
||||||
|
|
||||||
|
def load_jsonl(path):
|
||||||
|
return [json.loads(line) for line in open(path) if line.strip()]
|
||||||
|
|
||||||
|
mode = sys.argv[1]
|
||||||
|
if mode == "baseline":
|
||||||
|
print(json.dumps(baseline(load_jsonl(sys.argv[2]))))
|
||||||
|
elif mode == "decide":
|
||||||
|
base, state = json.load(open(sys.argv[2])), json.load(open(sys.argv[3]))
|
||||||
|
state, verdict = decide(base, state, json.load(open(sys.argv[4])))
|
||||||
|
json.dump(state, open(sys.argv[3], "w"))
|
||||||
|
print(verdict)
|
||||||
|
sys.exit(1 if verdict.startswith("trip") else 0)
|
||||||
|
elif mode == "simulate":
|
||||||
|
base = baseline(load_jsonl(sys.argv[2]))
|
||||||
|
state, n = {}, 0
|
||||||
|
for n, s in enumerate(load_jsonl(sys.argv[3]), 1):
|
||||||
|
state, verdict = decide(base, state, s)
|
||||||
|
if verdict.startswith("trip"):
|
||||||
|
print("trip at check %d: %s (baseline %s)" % (n, verdict, json.dumps(base)))
|
||||||
|
sys.exit(1)
|
||||||
|
print("no trip over %d checks (baseline %s)" % (n, json.dumps(base)))
|
||||||
|
'
|
||||||
|
|
||||||
|
start() {
|
||||||
|
need_root
|
||||||
|
[ -x "$BIN" ] || die "$BIN is missing: this release predates SHADOW-01"
|
||||||
|
systemctl is-active --quiet flyshadow.service && die "flyshadow.service is already running"
|
||||||
|
install -d -o fly -g fly -m 0755 "$SHADOW_DIR" "$SHADOW_DIR/trace"
|
||||||
|
# A previous run's verdict is kept beside, never read as this run's.
|
||||||
|
if [ -f "$SHADOW_DIR/verdict.json" ]; then
|
||||||
|
mv "$SHADOW_DIR/verdict.json" "$SHADOW_DIR/verdict.$(date -u +%Y%m%dT%H%M%SZ).json"
|
||||||
|
fi
|
||||||
|
rm -f "$SHADOW_DIR/divergence.json" "$SHADOW_DIR/guard-tripped.json"
|
||||||
|
log "recording the live fly's baseline over ${BASELINE_SECONDS} s, before the shadow exists"
|
||||||
|
local n samples base
|
||||||
|
n=$(( BASELINE_SECONDS / 10 ))
|
||||||
|
[ "$n" -ge 3 ] || die "FLY_SHADOW_BASELINE_SECONDS must be at least 30"
|
||||||
|
samples="$SHADOW_DIR/baseline-samples.jsonl"
|
||||||
|
: > "$samples"
|
||||||
|
for _ in $(seq 1 "$n"); do
|
||||||
|
sample >> "$samples" || die "could not read flysim's metrics for the baseline"
|
||||||
|
done
|
||||||
|
base="$(python3 -c "$GUARD_PY" baseline "$samples")" \
|
||||||
|
|| die "flysim did not run normally during the baseline; not starting the shadow"
|
||||||
|
printf '%s\n' "$base" > "$SHADOW_DIR/baseline.json"
|
||||||
|
printf '{}\n' > "$SHADOW_DIR/guard-state.json"
|
||||||
|
chown fly:fly "$SHADOW_DIR/baseline.json" "$samples" "$SHADOW_DIR/guard-state.json"
|
||||||
|
log "baseline: $base"
|
||||||
|
mkdir -p "$DROPIN_DIR"
|
||||||
|
cat > "$DROPIN" <<EOF
|
||||||
|
# written by fly-shadow-run start (SHADOW-01); removed by fly-shadow-run stop and by its guard.
|
||||||
|
[Service]
|
||||||
|
Environment=FLY_TRACE_DIR=$SHADOW_DIR/trace
|
||||||
|
Environment=FLY_TRACE_LEDGERS=$LEDGERS_EVERY
|
||||||
|
EOF
|
||||||
|
systemctl daemon-reload
|
||||||
|
systemctl start flyshadow.service
|
||||||
|
# flysim starts no trace without a live consumer: wait for the shadow's heartbeat.
|
||||||
|
for _ in $(seq 1 60); do
|
||||||
|
[ -f "$SHADOW_DIR/trace/consumer" ] && break
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
[ -f "$SHADOW_DIR/trace/consumer" ] || { stop_all "the shadow wrote no heartbeat"; die "flyshadow.service did not come up"; }
|
||||||
|
log "flyshadow.service started; restarting flysim.service so the shadow follows it from its start"
|
||||||
|
systemctl restart flysim.service
|
||||||
|
systemctl start flyshadow-guard.timer
|
||||||
|
log "started, guarded every 60 s. Read progress with: fly-shadow-run status"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Stops the shadow and the guard and turns the trace off. $1: why (logged).
|
||||||
|
stop_all() {
|
||||||
|
systemctl stop flyshadow-guard.timer 2>/dev/null || true
|
||||||
|
systemctl stop flyshadow.service 2>/dev/null || true
|
||||||
|
rm -f "$DROPIN"
|
||||||
|
systemctl daemon-reload
|
||||||
|
log "stopped the shadow: $1"
|
||||||
|
}
|
||||||
|
|
||||||
|
stop() {
|
||||||
|
need_root
|
||||||
|
local restart_flysim=0 keep=0
|
||||||
|
for arg in "$@"; do
|
||||||
|
case "$arg" in
|
||||||
|
--restart-flysim) restart_flysim=1 ;;
|
||||||
|
--keep) keep=1 ;;
|
||||||
|
*) die "stop: unknown option $arg" ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
stop_all "fly-shadow-run stop"
|
||||||
|
if [ "$restart_flysim" = 1 ]; then
|
||||||
|
systemctl restart flysim.service
|
||||||
|
log "flysim.service restarted without the trace"
|
||||||
|
else
|
||||||
|
log "flysim stops its current trace within a minute (no consumer) and starts none at its next restart"
|
||||||
|
fi
|
||||||
|
rm -f "$SHADOW_DIR/baseline.json" "$SHADOW_DIR/guard-state.json"
|
||||||
|
if [ "$keep" = 0 ]; then
|
||||||
|
rm -rf "$SHADOW_DIR/spool" "$SHADOW_DIR/work"
|
||||||
|
find "$SHADOW_DIR/trace" -name 'trace-*.jsonl' -delete 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
log "the verdict stays in $SHADOW_DIR/verdict.json"
|
||||||
|
}
|
||||||
|
|
||||||
|
# "ActiveState/SubState" of a unit, from `systemctl show` (`is-active` cannot tell a crashed unit
|
||||||
|
# waiting out its restart delay, activating/auto-restart, from a stopped one).
|
||||||
|
unit_state() {
|
||||||
|
local out active
|
||||||
|
out="$(systemctl show -p ActiveState,SubState "$1" 2>/dev/null)" || true
|
||||||
|
active="$(printf '%s\n' "$out" | sed -n 's/^ActiveState=//p')"
|
||||||
|
# An unreadable state is not "stopped": the guard keeps running and judges the fly.
|
||||||
|
case "$active" in
|
||||||
|
active|inactive|failed|activating|deactivating|reloading) printf '%s\n' "$active" ;;
|
||||||
|
*) printf 'unknown\n' ;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
guard() {
|
||||||
|
need_root
|
||||||
|
if [ ! -f "$SHADOW_DIR/baseline.json" ]; then
|
||||||
|
log "no baseline: nothing to guard"
|
||||||
|
systemctl stop flyshadow-guard.timer 2>/dev/null || true
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
# The guard acts only against a shadow that is up or on its way up. One that diverged, passed
|
||||||
|
# and stopped, or was stopped costs the live fly nothing more (ActiveState inactive/failed), and
|
||||||
|
# flysim stops its trace without the shadow's heartbeat. During the shadow's crash-restart delay
|
||||||
|
# (Restart=on-failure, RestartSec=10) the unit is `activating` (auto-restart): the guard must
|
||||||
|
# keep running, or the restarted shadow runs unguarded while `check` still allows a cutover
|
||||||
|
# (SHADOW-01 review round 3, G1-a).
|
||||||
|
local active_state
|
||||||
|
active_state="$(unit_state flyshadow.service)"
|
||||||
|
case "$active_state" in
|
||||||
|
inactive|failed)
|
||||||
|
log "flyshadow.service is $active_state: the guard stops itself and changes nothing"
|
||||||
|
systemctl stop flyshadow-guard.timer 2>/dev/null || true
|
||||||
|
exit 0
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
[ -f "$SHADOW_DIR/guard-state.json" ] || printf '{}\n' > "$SHADOW_DIR/guard-state.json"
|
||||||
|
local now tmp verdict
|
||||||
|
now="$(sample)" || { log "could not read flysim's metrics; not judged this minute"; exit 0; }
|
||||||
|
tmp="$(mktemp)"
|
||||||
|
printf '%s\n' "$now" > "$tmp"
|
||||||
|
if verdict="$(python3 -c "$GUARD_PY" decide "$SHADOW_DIR/baseline.json" "$SHADOW_DIR/guard-state.json" "$tmp")"; then
|
||||||
|
rm -f "$tmp"
|
||||||
|
log "guard: $verdict ($now)"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
rm -f "$tmp"
|
||||||
|
log "guard TRIPPED: $verdict ($now)"
|
||||||
|
stop_all "guard: $verdict"
|
||||||
|
rm -f "$SHADOW_DIR/baseline.json" "$SHADOW_DIR/guard-state.json"
|
||||||
|
python3 -c 'import json,sys,datetime; json.dump({"at": datetime.datetime.now(datetime.timezone.utc).isoformat(), "reason": sys.argv[1], "sample": json.loads(sys.argv[2])}, open(sys.argv[3], "w"))' \
|
||||||
|
"$verdict" "$now" "$SHADOW_DIR/guard-tripped.json"
|
||||||
|
systemctl restart flysim.service
|
||||||
|
log "flysim.service restarted without the trace; see $SHADOW_DIR/guard-tripped.json"
|
||||||
|
}
|
||||||
|
|
||||||
|
status() {
|
||||||
|
systemctl is-active flyshadow.service || true
|
||||||
|
systemctl is-active flyshadow-guard.timer || true
|
||||||
|
[ -f "$SHADOW_DIR/guard-tripped.json" ] && echo "GUARD TRIPPED: $(cat "$SHADOW_DIR/guard-tripped.json")"
|
||||||
|
[ -f "$SHADOW_DIR/verdict.json" ] || { echo "no verdict yet"; return 0; }
|
||||||
|
python3 - "$SHADOW_DIR/verdict.json" <<'PY'
|
||||||
|
import json, sys
|
||||||
|
v = json.load(open(sys.argv[1]))
|
||||||
|
c = v["compared"]
|
||||||
|
print(f"verdict {v['status']}: {v['reason']}")
|
||||||
|
print(f" compared {c['brainSeconds']:.0f} of {v['required']['brainSeconds']:.0f} brain s "
|
||||||
|
f"({c['transitions']} transitions, {c['segments']} segments); updated {v['updatedAt']}")
|
||||||
|
print(f" sugar {c['sugar']}, rewards {c['rewards']} {c['rewardKinds']}, macro events {c['macroEvents']}, "
|
||||||
|
f"slot saves {c['slotSaves']}, rollbacks {c['rollbacks']}, ledger checks {c['ledgerChecks']}")
|
||||||
|
print(f" checkpoints {c['checkpoints']}; skipped {v['skipped']}; spool evicted {v['spoolEvicted']}")
|
||||||
|
print(f" behind the live trace ~{v['lagTransitions']} transitions; live lag {v['liveLagSeconds']} s; cost {v['cost']}")
|
||||||
|
if v["firstDivergence"]:
|
||||||
|
print(f" FIRST DIVERGENCE: {json.dumps(v['firstDivergence'])}")
|
||||||
|
PY
|
||||||
|
}
|
||||||
|
|
||||||
|
check() {
|
||||||
|
# A tripped guard, a shadow that is not running, or a run that no guard watched never allows a
|
||||||
|
# cutover, whatever the verdict file says: the guard timer must be active and its baseline
|
||||||
|
# present (G1-a).
|
||||||
|
if [ -f "$SHADOW_DIR/guard-tripped.json" ]; then
|
||||||
|
echo "cutover refused: the guard tripped ($(cat "$SHADOW_DIR/guard-tripped.json"))"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if ! systemctl is-active --quiet flyshadow.service; then
|
||||||
|
echo "cutover refused: flyshadow.service is not running"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if ! systemctl is-active --quiet flyshadow-guard.timer; then
|
||||||
|
echo "cutover refused: flyshadow-guard.timer is not active (this run is not guarded)"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if [ ! -f "$SHADOW_DIR/baseline.json" ]; then
|
||||||
|
echo "cutover refused: no baseline.json (this run was not baselined by fly-shadow-run start)"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
[ -x "$BIN" ] || die "$BIN is missing"
|
||||||
|
# The live service's configuration, for its compatibility string.
|
||||||
|
set -a
|
||||||
|
# shellcheck disable=SC1091
|
||||||
|
. /etc/fly/fly.env
|
||||||
|
set +a
|
||||||
|
# The release CUT-01 switches into and the binary it switches to: SERVE-01's service there.
|
||||||
|
"$BIN" check --verdict "$SHADOW_DIR/verdict.json" --current /opt/fly/current \
|
||||||
|
--binary flysim-session "$@"
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd="${1:-}"
|
||||||
|
[ $# -gt 0 ] && shift
|
||||||
|
case "$cmd" in
|
||||||
|
start) start ;;
|
||||||
|
stop) stop "$@" ;;
|
||||||
|
status) status ;;
|
||||||
|
check) check "$@" ;;
|
||||||
|
guard) guard ;;
|
||||||
|
baseline) [ $# = 1 ] || die "baseline SAMPLES.jsonl"; python3 -c "$GUARD_PY" baseline "$1" ;;
|
||||||
|
simulate) [ $# = 2 ] || die "simulate BASELINE.jsonl CHECKS.jsonl"; python3 -c "$GUARD_PY" simulate "$1" "$2" ;;
|
||||||
|
*) echo "usage: fly-shadow-run start|stop [--restart-flysim] [--keep]|status|check [--max-age-seconds N]|guard|baseline SAMPLES.jsonl|simulate BASELINE.jsonl CHECKS.jsonl" >&2; exit 2 ;;
|
||||||
|
esac
|
||||||
|
|
@ -86,10 +86,12 @@ log "building in $crate_dir for target-cpu=haswell (the host is E5-2660 v3, Hasw
|
||||||
# looks for it.
|
# looks for it.
|
||||||
RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin fly-edge
|
RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin fly-edge
|
||||||
# flysim-session (SERVE-01): the live fly on the session runtime, a drop-in for flysim
|
# flysim-session (SERVE-01): the live fly on the session runtime, a drop-in for flysim
|
||||||
# that `fly-runtime session` points flysim.service at; and fly-session, its worker program
|
# that `fly-runtime session` points flysim.service at; fly-shadow (SHADOW-01,
|
||||||
# (FLY_SESSION_MODE=process only). Same features as flysim, built every time so a release
|
# infra/units/flyshadow.service): the session runtime shadowing the live fly; and
|
||||||
# can switch runtimes without a rebuild. Both land next to OUT_PATH.
|
# fly-session, their worker program (FLY_SESSION_MODE=process only). Same features as flysim,
|
||||||
RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin flysim-session --bin fly-session "${features_args[@]}"
|
# built every time so a release can switch runtimes without a rebuild. All land next to
|
||||||
|
# OUT_PATH, where package-release.sh looks for them.
|
||||||
|
RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin flysim-session --bin fly-shadow --bin fly-session "${features_args[@]}"
|
||||||
)
|
)
|
||||||
|
|
||||||
built="${crate_dir}/target/${CARGO_TARGET}/release/flysim"
|
built="${crate_dir}/target/${CARGO_TARGET}/release/flysim"
|
||||||
|
|
@ -123,7 +125,7 @@ edge_out="$(dirname "$OUT_PATH")/fly-edge"
|
||||||
cp "$edge_built" "$edge_out"
|
cp "$edge_built" "$edge_out"
|
||||||
chmod 0755 "$edge_out"
|
chmod 0755 "$edge_out"
|
||||||
log "built $edge_out ($(du -h "$edge_out" | cut -f1))"
|
log "built $edge_out ($(du -h "$edge_out" | cut -f1))"
|
||||||
for extra in flysim-session fly-session; do
|
for extra in flysim-session fly-shadow fly-session; do
|
||||||
extra_built="${crate_dir}/target/${CARGO_TARGET}/release/${extra}"
|
extra_built="${crate_dir}/target/${CARGO_TARGET}/release/${extra}"
|
||||||
[ -x "$extra_built" ] || die "expected binary not found after build: $extra_built"
|
[ -x "$extra_built" ] || die "expected binary not found after build: $extra_built"
|
||||||
extra_out="$(dirname "$OUT_PATH")/${extra}"
|
extra_out="$(dirname "$OUT_PATH")/${extra}"
|
||||||
|
|
|
||||||
|
|
@ -15,9 +15,11 @@
|
||||||
# left one beside FLYSIM_BIN; flyedge.service stays
|
# left one beside FLYSIM_BIN; flyedge.service stays
|
||||||
# inactive on a release without it)
|
# inactive on a release without it)
|
||||||
# flysim-session (the session runtime, SERVE-01, and fly-session, its
|
# flysim-session (the session runtime, SERVE-01, and fly-session, its
|
||||||
# fly-session worker program; mode 0755, when build-flysim.sh left
|
# fly-shadow worker program; mode 0755, when build-flysim.sh left
|
||||||
# them beside FLYSIM_BIN. `fly-runtime session` refuses
|
# fly-session them beside FLYSIM_BIN. `fly-runtime session` refuses
|
||||||
# a release without flysim-session)
|
# a release without flysim-session. fly-shadow is
|
||||||
|
# SHADOW-01's shadow; flyshadow.service stays inactive
|
||||||
|
# on a release without it)
|
||||||
# stage/... (apps/stage's build output)
|
# stage/... (apps/stage's build output)
|
||||||
# bridge/... (services/bridge + node_modules)
|
# bridge/... (services/bridge + node_modules)
|
||||||
# data/fafb-v783/... (the connectome, from the repo; FLY_DATASET points here)
|
# data/fafb-v783/... (the connectome, from the repo; FLY_DATASET points here)
|
||||||
|
|
@ -86,13 +88,16 @@ if [ -x "$EDGE_BIN" ]; then
|
||||||
else
|
else
|
||||||
log "no fly-edge beside $FLYSIM_BIN; packaging without it (FLY_FEED_VIA=bus unavailable in this release)"
|
log "no fly-edge beside $FLYSIM_BIN; packaging without it (FLY_FEED_VIA=bus unavailable in this release)"
|
||||||
fi
|
fi
|
||||||
for extra in flysim-session fly-session; do
|
for extra in flysim-session fly-shadow fly-session; do
|
||||||
EXTRA_BIN="$(dirname "$FLYSIM_BIN")/${extra}"
|
EXTRA_BIN="$(dirname "$FLYSIM_BIN")/${extra}"
|
||||||
if [ -x "$EXTRA_BIN" ]; then
|
if [ -x "$EXTRA_BIN" ]; then
|
||||||
cp "$EXTRA_BIN" "${release_dir}/${extra}"
|
cp "$EXTRA_BIN" "${release_dir}/${extra}"
|
||||||
chmod 0755 "${release_dir}/${extra}"
|
chmod 0755 "${release_dir}/${extra}"
|
||||||
else
|
else
|
||||||
log "no ${extra} beside $FLYSIM_BIN; packaging without it (fly-runtime session unavailable in this release)"
|
case "$extra" in
|
||||||
|
fly-shadow) log "no ${extra} beside $FLYSIM_BIN; packaging without it (no shadow run in this release)" ;;
|
||||||
|
*) log "no ${extra} beside $FLYSIM_BIN; packaging without it (fly-runtime session unavailable in this release)" ;;
|
||||||
|
esac
|
||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
cp -a "$STAGE_DIR" "${release_dir}/stage"
|
cp -a "$STAGE_DIR" "${release_dir}/stage"
|
||||||
|
|
|
||||||
|
|
@ -519,6 +519,83 @@ pct exec $CTID -- /opt/fly/bin/fly-runtime legacy # the one-command rollback
|
||||||
cannot be enabled). It is for a rehearsal or a soak on a container whose `flysim.service` is
|
cannot be enabled). It is for a rehearsal or a soak on a container whose `flysim.service` is
|
||||||
stopped, not for switching the stream.
|
stopped, not for switching the stream.
|
||||||
|
|
||||||
|
## Shadow run (SHADOW-01)
|
||||||
|
|
||||||
|
The session runtime, run beside the live fly as the gate for the automatic cutover (CUT-01). The
|
||||||
|
contract is `docs/design/session-framework/legacy-gameboy-v1.md` section 18. The shadow is
|
||||||
|
report-only: it presses no button, serves no port, and only reads flysim's stores and trace. Claim
|
||||||
|
the release container in the host log first, as for any host work.
|
||||||
|
|
||||||
|
```
|
||||||
|
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run start # baseline, trace on, shadow + guard, one flysim restart
|
||||||
|
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run status # the verdict (and a guard trip) in one screen
|
||||||
|
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run check # CUT-01's hook: exit 0 = cutover allowed
|
||||||
|
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run stop --restart-flysim # shadow, guard and trace off
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Start** first records the live fly's baseline for 10 minutes, before the shadow exists: sixty
|
||||||
|
10-s means of `fly_realtime_factor` (their mean and spread) and the `fly_lag_seconds` growth
|
||||||
|
rate. It refuses unless flysim ran normally for most of that time. Then it:
|
||||||
|
1. installs `flysim.service.d/shadow-trace.conf` (`FLY_TRACE_DIR=/srv/fly/shadow/trace`,
|
||||||
|
`FLY_TRACE_LEDGERS=60`);
|
||||||
|
2. starts `flyshadow.service` and waits for its heartbeat;
|
||||||
|
3. restarts `flysim.service` once;
|
||||||
|
4. starts `flyshadow-guard.timer`.
|
||||||
|
|
||||||
|
`FLY_SHADOW_BASELINE_SECONDS` shortens the baseline, for tests only. The restart is the same one
|
||||||
|
the unstick rule uses: the rung is kept and the ledgers are cleared. A previous `verdict.json`
|
||||||
|
is kept beside the new one, renamed with its time.
|
||||||
|
- **The guard** runs every 60 s, automatically, and judges the live fly against its own baseline,
|
||||||
|
not against real time. A fly that already ran at 0.66 is fine at 0.66. It trips only on a
|
||||||
|
sustained degradation: 3 checks in a row in which the last 5 samples of the same flysim process
|
||||||
|
fall below the baseline, or grow lag faster than it, by more than the margin. The margin is
|
||||||
|
max(0.05, 4 x the baseline spread / sqrt 5). A trip is at the earliest about 7 minutes after a
|
||||||
|
real degradation begins. A tripped guard stops the shadow and the guard, removes the drop-in and
|
||||||
|
restarts flysim without the trace. It records why in `/srv/fly/shadow/guard-tripped.json`, and
|
||||||
|
`status` shows it. A paused fly is not judged, and a restarted one starts its window again.
|
||||||
|
Once the shadow is down for good (`ActiveState` inactive or failed: diverged, stopped, given up),
|
||||||
|
the guard stops itself and changes nothing. While the shadow waits out its 10-s crash-restart delay
|
||||||
|
(`activating`) the guard keeps running. A trip is not a divergence: fix the resources, then `start` again.
|
||||||
|
- **While it runs**, every later flysim restart (the unstick rule, the watchdog,
|
||||||
|
`fly-loop-recover`, `fly-reset-to-milestone`) starts a new trace file. The shadow follows it on
|
||||||
|
its own; nothing needs doing. The 3 h window is live *brain* time summed over those processes.
|
||||||
|
Stopping or restarting `flyshadow.service` itself starts the window again.
|
||||||
|
- **Pass**: `status` shows `verdict pass` once both of these hold with zero divergence:
|
||||||
|
- 10,800 brain seconds are compared;
|
||||||
|
- at least one live save per 10 brain minutes has been compared byte for byte.
|
||||||
|
|
||||||
|
The shadow keeps following, and the verdict stays `pass` only while nothing diverges. CUT-01
|
||||||
|
runs `check` at the moment it cuts over. `check` also requires all of these:
|
||||||
|
- at least 10,800 brain seconds, whatever window the shadow was started with;
|
||||||
|
- the guard has not tripped, `flyshadow.service` is running, `flyshadow-guard.timer` is active and
|
||||||
|
`baseline.json` exists (a run no guard watched is never cut over);
|
||||||
|
- the verdict is for the release `/opt/fly/current` points to, with `flysim-session` and every
|
||||||
|
other shadowed binary unchanged;
|
||||||
|
- the shadow is caught up (at most about a minute behind);
|
||||||
|
- the verdict's `updatedAt` is neither older than the max age nor more than 60 s in the future
|
||||||
|
(a clock stepped back must not keep an old pass fresh);
|
||||||
|
- no segment was skipped for a reason other than the live side's own.
|
||||||
|
- **Divergence**: the shadow stops itself (exit status 3; the unit does not restart it). A failure
|
||||||
|
of the session runtime itself counts: it did not start, the restore gate refused the live save,
|
||||||
|
or a step failed. The shadow leaves `verdict.json` at `diverged` and
|
||||||
|
`/srv/fly/shadow/divergence.json` with the field, both values and the 30 transitions before it.
|
||||||
|
On a checkpoint difference it also leaves both checkpoint files. It removes its heartbeat, so
|
||||||
|
flysim stops tracing within a minute. The live fly is untouched. Run `stop --keep`, pull the
|
||||||
|
files for the review, and do not cut over.
|
||||||
|
- **The trace cannot outlive the shadow.** flysim starts no trace without the shadow's fresh
|
||||||
|
heartbeat (`/srv/fly/shadow/trace/consumer`), and stops a running trace within a minute once the
|
||||||
|
heartbeat is more than 10 minutes old. That happens when the shadow crashed, diverged, was
|
||||||
|
stopped, or the guard tripped. flysim keeps the trace directory under 8 GiB, and the shadow
|
||||||
|
deletes every file it has compared.
|
||||||
|
- **Resources**: the shadow is a second whole brain, at about the live fly's CPU per frame. It
|
||||||
|
runs `SCHED_IDLE` on the page and encoder CPUs, never on flysim's (05-deploy.sh writes its
|
||||||
|
`cpuset.conf`). It pauses for a minute while flysim's lag grows faster than its baseline rate, and
|
||||||
|
it stops pausing when a pause does not help. Disk: about
|
||||||
|
160 MB of trace per live hour, and a spool of at most 512 MiB.
|
||||||
|
- **Stop** stops the unit and the guard, removes the drop-in, and deletes the trace and the spool
|
||||||
|
(`--keep` keeps them). Without `--restart-flysim`, the running flysim stops its current trace
|
||||||
|
within a minute, because its consumer is gone.
|
||||||
|
|
||||||
## CPU partition (cpuset)
|
## CPU partition (cpuset)
|
||||||
|
|
||||||
`05-deploy.sh` derives the in-guest `AllowedCPUs=` drop-ins for every app unit
|
`05-deploy.sh` derives the in-guest `AllowedCPUs=` drop-ins for every app unit
|
||||||
|
|
|
||||||
19
infra/tests/fixtures/shadow-guard/README.md
vendored
Normal file
19
infra/tests/fixtures/shadow-guard/README.md
vendored
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
# Recorded live-fly samples for `fly-shadow-run`'s guard
|
||||||
|
|
||||||
|
These samples come from a real `flysim` (legacy, FAFB, macros mode, at real time) on a shared build
|
||||||
|
box on 2026-09-30. They are in `fly-shadow-run`'s own format and cadence:
|
||||||
|
|
||||||
|
- `baseline.jsonl` holds 60 samples 10 s apart;
|
||||||
|
- `checks.jsonl` holds 20 samples a minute apart, after the same flysim restart that `start` does.
|
||||||
|
|
||||||
|
`lint.sh` runs `fly-shadow-run simulate` over each case and holds it to `expect`:
|
||||||
|
|
||||||
|
| Case | Setup | Expect |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `slow-alone` | 1 cpu, 1 thread; no shadow | pass |
|
||||||
|
| `slow-shadow-same` | the same fly, with a real `fly-shadow` following it at normal priority on the same cpu. The live fly dropped from 0.66 to 0.44-0.60 | trip |
|
||||||
|
| `fast-shadow-idle` | 3 cpus, 3 threads; a real `fly-shadow` at `SCHED_IDLE` on other cpus. The box was already loaded, and the fly ran at 0.4-0.85 | pass |
|
||||||
|
| `fast-alone` | 3 cpus, 3 threads; no shadow | pass |
|
||||||
|
|
||||||
|
The box's own load moved the fly between 0.4 and 1.0 during some baselines. Those steps are why
|
||||||
|
the baseline is robust: the median, and the spread taken as the MAD.
|
||||||
60
infra/tests/fixtures/shadow-guard/fast-alone/baseline.jsonl
vendored
Normal file
60
infra/tests/fixtures/shadow-guard/fast-alone/baseline.jsonl
vendored
Normal file
|
|
@ -0,0 +1,60 @@
|
||||||
|
{"t": 1790738128.362942, "status": "running", "rtMean": 0.7588339770286441, "lag": 33.479, "uptime": 71.223399881}
|
||||||
|
{"t": 1790738138.4285393, "status": "running", "rtMean": 1.0036906365382738, "lag": 33.479, "uptime": 81.293069051}
|
||||||
|
{"t": 1790738148.4962938, "status": "running", "rtMean": 0.9970303099114692, "lag": 33.479, "uptime": 91.408291997}
|
||||||
|
{"t": 1790738158.5748143, "status": "running", "rtMean": 0.9957513747669762, "lag": 33.479, "uptime": 101.483131764}
|
||||||
|
{"t": 1790738168.9591897, "status": "running", "rtMean": 0.819013893871745, "lag": 35.496, "uptime": 111.869185712}
|
||||||
|
{"t": 1790738179.0497794, "status": "running", "rtMean": 0.955720505211804, "lag": 35.496, "uptime": 121.957242118}
|
||||||
|
{"t": 1790738189.13739, "status": "running", "rtMean": 0.8799930137133124, "lag": 36.498, "uptime": 132.018380479}
|
||||||
|
{"t": 1790738199.2148638, "status": "running", "rtMean": 0.8902680060117365, "lag": 37.521, "uptime": 142.113434378}
|
||||||
|
{"t": 1790738209.3021023, "status": "running", "rtMean": 0.8803874146669992, "lag": 38.524, "uptime": 152.181022738}
|
||||||
|
{"t": 1790738219.3764796, "status": "running", "rtMean": 0.8658710279839296, "lag": 40.54, "uptime": 162.284831945}
|
||||||
|
{"t": 1790738229.4663715, "status": "running", "rtMean": 0.8894453486450183, "lag": 41.541, "uptime": 172.367967371}
|
||||||
|
{"t": 1790738239.553954, "status": "running", "rtMean": 0.9052554309116678, "lag": 42.543, "uptime": 182.460932044}
|
||||||
|
{"t": 1790738249.6388013, "status": "running", "rtMean": 0.9129316585556161, "lag": 43.544, "uptime": 192.526870399}
|
||||||
|
{"t": 1790738259.7050216, "status": "running", "rtMean": 0.9999965689074697, "lag": 43.544, "uptime": 202.609470103}
|
||||||
|
{"t": 1790738269.7767544, "status": "running", "rtMean": 0.9378600900744024, "lag": 43.544, "uptime": 212.690426315}
|
||||||
|
{"t": 1790738279.8516681, "status": "running", "rtMean": 0.7973579434723355, "lag": 45.556, "uptime": 222.761268128}
|
||||||
|
{"t": 1790738289.9210968, "status": "running", "rtMean": 0.9352522067409303, "lag": 46.571, "uptime": 232.836669514}
|
||||||
|
{"t": 1790738300.0552127, "status": "running", "rtMean": 0.7150556877963433, "lag": 49.584, "uptime": 242.963564523}
|
||||||
|
{"t": 1790738310.2007082, "status": "running", "rtMean": 1.0059437251512073, "lag": 49.584, "uptime": 253.109498917}
|
||||||
|
{"t": 1790738320.2790272, "status": "running", "rtMean": 1.00373183915971, "lag": 49.584, "uptime": 263.195154054}
|
||||||
|
{"t": 1790738330.3444412, "status": "running", "rtMean": 0.9972521469939926, "lag": 49.584, "uptime": 273.255265175}
|
||||||
|
{"t": 1790738340.4204133, "status": "running", "rtMean": 0.8495939168264007, "lag": 50.586, "uptime": 283.330032566}
|
||||||
|
{"t": 1790738350.5301325, "status": "running", "rtMean": 0.7839208383476353, "lag": 52.599, "uptime": 293.439062795}
|
||||||
|
{"t": 1790738360.6693776, "status": "running", "rtMean": 0.9653471893141468, "lag": 53.6, "uptime": 303.576346295}
|
||||||
|
{"t": 1790738370.8137631, "status": "running", "rtMean": 0.6241158180206947, "lag": 57.623, "uptime": 313.699656832}
|
||||||
|
{"t": 1790738380.9961703, "status": "running", "rtMean": 0.5687473149333804, "lag": 61.68, "uptime": 323.912074763}
|
||||||
|
{"t": 1790738391.089262, "status": "running", "rtMean": 0.5804323097526403, "lag": 65.706, "uptime": 333.967914558}
|
||||||
|
{"t": 1790738401.19394, "status": "running", "rtMean": 0.5362910197658861, "lag": 70.779, "uptime": 344.048343544}
|
||||||
|
{"t": 1790738411.3023837, "status": "running", "rtMean": 0.5510464052357773, "lag": 74.845, "uptime": 354.205680506}
|
||||||
|
{"t": 1790738421.4007213, "status": "running", "rtMean": 0.5652293538813947, "lag": 79.905, "uptime": 364.315364667}
|
||||||
|
{"t": 1790738431.503473, "status": "running", "rtMean": 0.57359026862898, "lag": 83.964, "uptime": 374.377908576}
|
||||||
|
{"t": 1790738441.6479023, "status": "running", "rtMean": 0.5540343187796515, "lag": 87.999, "uptime": 384.55919851}
|
||||||
|
{"t": 1790738451.7651033, "status": "running", "rtMean": 0.6037429716311573, "lag": 92.018, "uptime": 394.673360423}
|
||||||
|
{"t": 1790738461.8663146, "status": "running", "rtMean": 0.6985130182613225, "lag": 95.095, "uptime": 404.755070174}
|
||||||
|
{"t": 1790738471.9642298, "status": "running", "rtMean": 0.7594984860121092, "lag": 98.14, "uptime": 414.851205955}
|
||||||
|
{"t": 1790738482.0506132, "status": "running", "rtMean": 0.8166532570546075, "lag": 99.145, "uptime": 424.958463239}
|
||||||
|
{"t": 1790738492.1384304, "status": "running", "rtMean": 0.8807780226062987, "lag": 100.145, "uptime": 434.992925627}
|
||||||
|
{"t": 1790738502.2033277, "status": "running", "rtMean": 1.0802703218851182, "lag": 100.145, "uptime": 445.108112717}
|
||||||
|
{"t": 1790738512.273309, "status": "running", "rtMean": 0.9857221768324773, "lag": 100.145, "uptime": 455.179728346}
|
||||||
|
{"t": 1790738522.3412535, "status": "running", "rtMean": 1.0008941796078314, "lag": 100.145, "uptime": 465.243065017}
|
||||||
|
{"t": 1790738532.4065015, "status": "running", "rtMean": 1.0144037951650158, "lag": 100.145, "uptime": 475.316217749}
|
||||||
|
{"t": 1790738542.4878814, "status": "running", "rtMean": 0.995240358864496, "lag": 100.145, "uptime": 485.400446119}
|
||||||
|
{"t": 1790738552.5522985, "status": "running", "rtMean": 0.9958695819760208, "lag": 100.145, "uptime": 495.331048011}
|
||||||
|
{"t": 1790738562.6135433, "status": "running", "rtMean": 0.9990484834746928, "lag": 100.145, "uptime": 505.518260558}
|
||||||
|
{"t": 1790738572.6848962, "status": "running", "rtMean": 0.9999101070487516, "lag": 100.145, "uptime": 515.603359756}
|
||||||
|
{"t": 1790738582.7517495, "status": "running", "rtMean": 1.0067915374872096, "lag": 100.145, "uptime": 525.63843004}
|
||||||
|
{"t": 1790738592.8203006, "status": "running", "rtMean": 0.9933226593909843, "lag": 100.145, "uptime": 535.714625602}
|
||||||
|
{"t": 1790738602.8871908, "status": "running", "rtMean": 0.9997146956682066, "lag": 100.145, "uptime": 545.76592055}
|
||||||
|
{"t": 1790738612.9580173, "status": "running", "rtMean": 0.9995574815559497, "lag": 100.145, "uptime": 555.842376949}
|
||||||
|
{"t": 1790738623.0309892, "status": "running", "rtMean": 1.0009077839472587, "lag": 100.145, "uptime": 565.932440918}
|
||||||
|
{"t": 1790738633.1058488, "status": "running", "rtMean": 0.905700103566834, "lag": 101.148, "uptime": 576.014824329}
|
||||||
|
{"t": 1790738643.2241693, "status": "running", "rtMean": 0.9002632818253182, "lag": 102.159, "uptime": 586.12547679}
|
||||||
|
{"t": 1790738653.3037221, "status": "running", "rtMean": 1.001384402969126, "lag": 102.159, "uptime": 596.212798092}
|
||||||
|
{"t": 1790738663.377194, "status": "running", "rtMean": 1.0025847949946505, "lag": 102.159, "uptime": 606.291720522}
|
||||||
|
{"t": 1790738673.450081, "status": "running", "rtMean": 0.9982495351402143, "lag": 102.159, "uptime": 616.368169968}
|
||||||
|
{"t": 1790738683.5147092, "status": "running", "rtMean": 1.000470259093377, "lag": 102.159, "uptime": 626.427550974}
|
||||||
|
{"t": 1790738693.5863135, "status": "running", "rtMean": 0.9966639708181871, "lag": 102.159, "uptime": 636.458204371}
|
||||||
|
{"t": 1790738703.651422, "status": "running", "rtMean": 0.9994712074317433, "lag": 102.159, "uptime": 646.54138456}
|
||||||
|
{"t": 1790738713.7201247, "status": "running", "rtMean": 0.9965700494189607, "lag": 102.159, "uptime": 656.631814013}
|
||||||
|
{"t": 1790738723.7912498, "status": "running", "rtMean": 1.0007973265331749, "lag": 102.159, "uptime": 666.694264297}
|
||||||
20
infra/tests/fixtures/shadow-guard/fast-alone/checks.jsonl
vendored
Normal file
20
infra/tests/fixtures/shadow-guard/fast-alone/checks.jsonl
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
{"t": 1790738735.0354905, "status": "running", "rtMean": 0.999484237762719, "lag": 0.0, "uptime": 11.07355663}
|
||||||
|
{"t": 1790738795.1101537, "status": "running", "rtMean": 0.998153021033785, "lag": 0.0, "uptime": 71.129215866}
|
||||||
|
{"t": 1790738855.1800184, "status": "running", "rtMean": 0.9926228160612285, "lag": 0.0, "uptime": 131.202241399}
|
||||||
|
{"t": 1790738915.249556, "status": "running", "rtMean": 0.9992177109183569, "lag": 0.0, "uptime": 191.273914994}
|
||||||
|
{"t": 1790738975.3090174, "status": "running", "rtMean": 1.0004807207169564, "lag": 0.0, "uptime": 251.312728385}
|
||||||
|
{"t": 1790739035.3770518, "status": "running", "rtMean": 0.99729025135176, "lag": 0.0, "uptime": 311.41256314}
|
||||||
|
{"t": 1790739095.4512274, "status": "running", "rtMean": 0.9963104110487839, "lag": 0.0, "uptime": 371.442377297}
|
||||||
|
{"t": 1790739155.5106263, "status": "running", "rtMean": 0.9986795197502222, "lag": 0.0, "uptime": 431.514951288}
|
||||||
|
{"t": 1790739215.5753255, "status": "running", "rtMean": 0.998777006263299, "lag": 0.0, "uptime": 491.615126509}
|
||||||
|
{"t": 1790739275.6377265, "status": "running", "rtMean": 0.9993828850549406, "lag": 0.0, "uptime": 551.643819315}
|
||||||
|
{"t": 1790739335.6982403, "status": "running", "rtMean": 0.9998689452246822, "lag": 0.0, "uptime": 611.710123532}
|
||||||
|
{"t": 1790739395.7690253, "status": "running", "rtMean": 1.0066090326463777, "lag": 0.0, "uptime": 671.806084883}
|
||||||
|
{"t": 1790739455.8361878, "status": "running", "rtMean": 0.9991477060779191, "lag": 0.0, "uptime": 731.837495033}
|
||||||
|
{"t": 1790739515.8999934, "status": "running", "rtMean": 0.9968497132252894, "lag": 0.0, "uptime": 791.918687829}
|
||||||
|
{"t": 1790739575.9599848, "status": "running", "rtMean": 0.9993416499626159, "lag": 0.0, "uptime": 851.966694729}
|
||||||
|
{"t": 1790739636.031231, "status": "running", "rtMean": 0.9997509681411471, "lag": 0.0, "uptime": 912.047324838}
|
||||||
|
{"t": 1790739696.1082256, "status": "running", "rtMean": 0.9993880587210896, "lag": 0.0, "uptime": 972.143571488}
|
||||||
|
{"t": 1790739756.1715124, "status": "running", "rtMean": 0.9978257533955007, "lag": 0.0, "uptime": 1032.192931507}
|
||||||
|
{"t": 1790739816.2371426, "status": "running", "rtMean": 1.0003866207887322, "lag": 0.0, "uptime": 1092.269950437}
|
||||||
|
{"t": 1790739876.297765, "status": "running", "rtMean": 0.9997339122145353, "lag": 0.0, "uptime": 1152.311864977}
|
||||||
1
infra/tests/fixtures/shadow-guard/fast-alone/expect
vendored
Normal file
1
infra/tests/fixtures/shadow-guard/fast-alone/expect
vendored
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
pass
|
||||||
60
infra/tests/fixtures/shadow-guard/fast-shadow-idle/baseline.jsonl
vendored
Normal file
60
infra/tests/fixtures/shadow-guard/fast-shadow-idle/baseline.jsonl
vendored
Normal file
|
|
@ -0,0 +1,60 @@
|
||||||
|
{"t": 1790736255.1832466, "status": "running", "rtMean": 0.44899475378270337, "lag": 40.531, "uptime": 71.111642723}
|
||||||
|
{"t": 1790736265.3486006, "status": "running", "rtMean": 0.40737226174421837, "lag": 46.58, "uptime": 81.296028671}
|
||||||
|
{"t": 1790736275.462523, "status": "running", "rtMean": 0.43926524622884744, "lag": 51.607, "uptime": 91.41614284}
|
||||||
|
{"t": 1790736285.5483737, "status": "running", "rtMean": 0.4992672422167786, "lag": 57.668, "uptime": 101.49334599}
|
||||||
|
{"t": 1790736295.691844, "status": "running", "rtMean": 0.4722833612045654, "lag": 62.729, "uptime": 111.631919513}
|
||||||
|
{"t": 1790736305.8359153, "status": "running", "rtMean": 0.49364414852989763, "lag": 67.756, "uptime": 121.766530366}
|
||||||
|
{"t": 1790736316.0044537, "status": "running", "rtMean": 0.4592358802945983, "lag": 72.814, "uptime": 131.934151579}
|
||||||
|
{"t": 1790736326.1091528, "status": "running", "rtMean": 0.4414601438247983, "lag": 78.84, "uptime": 142.0534588}
|
||||||
|
{"t": 1790736336.2525842, "status": "running", "rtMean": 0.4540765983005316, "lag": 83.88, "uptime": 152.198379259}
|
||||||
|
{"t": 1790736346.4600585, "status": "running", "rtMean": 0.4173426800525677, "lag": 89.957, "uptime": 162.413446602}
|
||||||
|
{"t": 1790736356.5611305, "status": "running", "rtMean": 0.4606621035712305, "lag": 96.016, "uptime": 172.491203687}
|
||||||
|
{"t": 1790736366.7702422, "status": "running", "rtMean": 0.46203321509514217, "lag": 101.071, "uptime": 182.696019242}
|
||||||
|
{"t": 1790736376.9394329, "status": "running", "rtMean": 0.4863329297033063, "lag": 106.126, "uptime": 192.889038592}
|
||||||
|
{"t": 1790736387.0649624, "status": "running", "rtMean": 0.4495199219435465, "lag": 112.232, "uptime": 203.013465866}
|
||||||
|
{"t": 1790736397.1682742, "status": "running", "rtMean": 0.42863654848005284, "lag": 118.286, "uptime": 213.12621802}
|
||||||
|
{"t": 1790736407.2758026, "status": "running", "rtMean": 0.4139101392220675, "lag": 123.367, "uptime": 223.208709667}
|
||||||
|
{"t": 1790736417.43286, "status": "running", "rtMean": 0.43302060621434524, "lag": 129.445, "uptime": 233.357393123}
|
||||||
|
{"t": 1790736427.5712192, "status": "running", "rtMean": 0.43801120859089393, "lag": 135.505, "uptime": 243.507406013}
|
||||||
|
{"t": 1790736437.7151752, "status": "running", "rtMean": 0.4402615997407782, "lag": 140.554, "uptime": 253.661724645}
|
||||||
|
{"t": 1790736447.85799, "status": "running", "rtMean": 0.48112727487436235, "lag": 146.635, "uptime": 263.813400946}
|
||||||
|
{"t": 1790736458.0452223, "status": "running", "rtMean": 0.4318712743090674, "lag": 151.707, "uptime": 273.954505321}
|
||||||
|
{"t": 1790736468.1886797, "status": "running", "rtMean": 0.42247469989908265, "lag": 157.751, "uptime": 284.121781118}
|
||||||
|
{"t": 1790736478.3070867, "status": "running", "rtMean": 0.414255858741203, "lag": 163.851, "uptime": 294.242313229}
|
||||||
|
{"t": 1790736488.4334955, "status": "running", "rtMean": 0.42798509497809467, "lag": 169.928, "uptime": 304.374179381}
|
||||||
|
{"t": 1790736498.598869, "status": "running", "rtMean": 0.6973435620918129, "lag": 171.95, "uptime": 314.520569518}
|
||||||
|
{"t": 1790736508.6862988, "status": "running", "rtMean": 0.8506385364177339, "lag": 173.964, "uptime": 324.645689838}
|
||||||
|
{"t": 1790736518.7639382, "status": "running", "rtMean": 0.6393757799420648, "lag": 176.98, "uptime": 334.702167477}
|
||||||
|
{"t": 1790736528.8444629, "status": "running", "rtMean": 0.7563780548037421, "lag": 179.995, "uptime": 344.767409573}
|
||||||
|
{"t": 1790736538.9335213, "status": "running", "rtMean": 0.7299449362518324, "lag": 183.099, "uptime": 354.892773648}
|
||||||
|
{"t": 1790736549.0587013, "status": "running", "rtMean": 0.7495898580324455, "lag": 185.1, "uptime": 365.018206452}
|
||||||
|
{"t": 1790736559.125795, "status": "running", "rtMean": 0.7466250548943967, "lag": 188.191, "uptime": 375.072270628}
|
||||||
|
{"t": 1790736569.2290745, "status": "running", "rtMean": 0.7135159366386999, "lag": 191.217, "uptime": 385.16395309}
|
||||||
|
{"t": 1790736579.3221574, "status": "running", "rtMean": 0.6444057032246826, "lag": 194.311, "uptime": 395.24551542}
|
||||||
|
{"t": 1790736589.387774, "status": "running", "rtMean": 0.7078500629057103, "lag": 197.356, "uptime": 405.328315223}
|
||||||
|
{"t": 1790736599.457208, "status": "running", "rtMean": 0.7724222621426244, "lag": 199.41, "uptime": 415.395630334}
|
||||||
|
{"t": 1790736609.5669358, "status": "running", "rtMean": 0.7238637707089501, "lag": 202.432, "uptime": 425.523861591}
|
||||||
|
{"t": 1790736619.667222, "status": "running", "rtMean": 0.636988015566429, "lag": 206.491, "uptime": 435.596000401}
|
||||||
|
{"t": 1790736629.7565455, "status": "running", "rtMean": 0.6846194839249449, "lag": 209.511, "uptime": 445.705233095}
|
||||||
|
{"t": 1790736639.9320571, "status": "running", "rtMean": 0.5775285955158141, "lag": 213.527, "uptime": 455.875805326}
|
||||||
|
{"t": 1790736650.1127295, "status": "running", "rtMean": 0.6874672985502784, "lag": 216.574, "uptime": 466.047794887}
|
||||||
|
{"t": 1790736660.23605, "status": "running", "rtMean": 0.7980788454806589, "lag": 218.599, "uptime": 476.191578571}
|
||||||
|
{"t": 1790736670.3181207, "status": "running", "rtMean": 0.8373465907575423, "lag": 220.629, "uptime": 486.259561672}
|
||||||
|
{"t": 1790736680.5240602, "status": "running", "rtMean": 0.5739965775984952, "lag": 224.72, "uptime": 496.479775337}
|
||||||
|
{"t": 1790736690.6629243, "status": "running", "rtMean": 0.5286072075517942, "lag": 229.778, "uptime": 506.594493598}
|
||||||
|
{"t": 1790736700.8302114, "status": "running", "rtMean": 0.6743407053708753, "lag": 232.792, "uptime": 516.784837195}
|
||||||
|
{"t": 1790736710.9810565, "status": "running", "rtMean": 0.4833175202797613, "lag": 237.843, "uptime": 526.927338551}
|
||||||
|
{"t": 1790736721.1076307, "status": "running", "rtMean": 0.5049205359243616, "lag": 242.912, "uptime": 537.054603691}
|
||||||
|
{"t": 1790736731.2034523, "status": "running", "rtMean": 0.4861911891792873, "lag": 248.95, "uptime": 547.101045326}
|
||||||
|
{"t": 1790736741.3109553, "status": "running", "rtMean": 0.4845765517462596, "lag": 254.061, "uptime": 557.246782973}
|
||||||
|
{"t": 1790736751.4774404, "status": "running", "rtMean": 0.5333230355802153, "lag": 258.103, "uptime": 567.418066384}
|
||||||
|
{"t": 1790736761.652144, "status": "running", "rtMean": 0.49627891829609305, "lag": 264.173, "uptime": 577.572329582}
|
||||||
|
{"t": 1790736771.8544915, "status": "running", "rtMean": 0.5215276573927089, "lag": 268.2, "uptime": 587.79709649}
|
||||||
|
{"t": 1790736781.9649491, "status": "running", "rtMean": 0.5216891717973449, "lag": 273.234, "uptime": 597.898939598}
|
||||||
|
{"t": 1790736792.0599647, "status": "running", "rtMean": 0.5310205891816586, "lag": 278.266, "uptime": 607.982986102}
|
||||||
|
{"t": 1790736802.1870968, "status": "running", "rtMean": 0.49618279364312484, "lag": 283.316, "uptime": 618.117053029}
|
||||||
|
{"t": 1790736812.290842, "status": "running", "rtMean": 0.49072671618430486, "lag": 288.404, "uptime": 628.23818419}
|
||||||
|
{"t": 1790736822.4333866, "status": "running", "rtMean": 0.5402747673446865, "lag": 292.418, "uptime": 638.367153256}
|
||||||
|
{"t": 1790736832.613669, "status": "running", "rtMean": 0.8329938906374317, "lag": 294.42, "uptime": 648.537882771}
|
||||||
|
{"t": 1790736842.6835933, "status": "running", "rtMean": 0.7430173560600793, "lag": 297.448, "uptime": 658.629022047}
|
||||||
|
{"t": 1790736852.755823, "status": "running", "rtMean": 0.8578215877131159, "lag": 298.448, "uptime": 668.694834509}
|
||||||
20
infra/tests/fixtures/shadow-guard/fast-shadow-idle/checks.jsonl
vendored
Normal file
20
infra/tests/fixtures/shadow-guard/fast-shadow-idle/checks.jsonl
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
{"t": 1790736864.4256852, "status": "running", "rtMean": 0.6099898319965826, "lag": 3.091, "uptime": 11.07909019}
|
||||||
|
{"t": 1790736924.501681, "status": "running", "rtMean": 0.5411932741082821, "lag": 20.265, "uptime": 71.155545456}
|
||||||
|
{"t": 1790736984.5807962, "status": "running", "rtMean": 0.7295306018507262, "lag": 35.328, "uptime": 131.199399778}
|
||||||
|
{"t": 1790737044.6489198, "status": "running", "rtMean": 0.8067884564857175, "lag": 46.47, "uptime": 191.29805351}
|
||||||
|
{"t": 1790737104.7270966, "status": "running", "rtMean": 0.8192565712279218, "lag": 58.542, "uptime": 251.37716607}
|
||||||
|
{"t": 1790737164.7932363, "status": "running", "rtMean": 0.8487114702728498, "lag": 69.618, "uptime": 311.44889619}
|
||||||
|
{"t": 1790737224.91049, "status": "running", "rtMean": 0.42516908835738415, "lag": 101.107, "uptime": 371.522769005}
|
||||||
|
{"t": 1790737285.0996652, "status": "running", "rtMean": 0.41299332249218484, "lag": 136.493, "uptime": 431.719907398}
|
||||||
|
{"t": 1790737345.3437996, "status": "running", "rtMean": 0.4410892921905215, "lag": 171.04, "uptime": 491.980527036}
|
||||||
|
{"t": 1790737405.5281327, "status": "running", "rtMean": 0.4454430216668691, "lag": 204.353, "uptime": 552.14783058}
|
||||||
|
{"t": 1790737465.838257, "status": "running", "rtMean": 0.5991416565682315, "lag": 227.769, "uptime": 612.473422449}
|
||||||
|
{"t": 1790737525.9655414, "status": "running", "rtMean": 0.6857160494879407, "lag": 246.844, "uptime": 672.619024119}
|
||||||
|
{"t": 1790737586.045057, "status": "running", "rtMean": 0.6537634570200577, "lag": 265.963, "uptime": 732.678449214}
|
||||||
|
{"t": 1790737646.1301575, "status": "running", "rtMean": 0.6473194011694912, "lag": 290.309, "uptime": 792.775859726}
|
||||||
|
{"t": 1790737706.2470899, "status": "running", "rtMean": 0.474484017045933, "lag": 319.566, "uptime": 852.890865845}
|
||||||
|
{"t": 1790737766.4071772, "status": "running", "rtMean": 0.5316840402693012, "lag": 349.947, "uptime": 913.037081082}
|
||||||
|
{"t": 1790737826.488124, "status": "running", "rtMean": 0.7651768950839182, "lag": 371.253, "uptime": 973.141837869}
|
||||||
|
{"t": 1790737886.652113, "status": "running", "rtMean": 0.4461005912444415, "lag": 403.681, "uptime": 1033.302886448}
|
||||||
|
{"t": 1790737946.764796, "status": "running", "rtMean": 0.4610048048396617, "lag": 438.093, "uptime": 1093.383696514}
|
||||||
|
{"t": 1790738006.857649, "status": "running", "rtMean": 0.44882468186134916, "lag": 471.382, "uptime": 1153.477095415}
|
||||||
1
infra/tests/fixtures/shadow-guard/fast-shadow-idle/expect
vendored
Normal file
1
infra/tests/fixtures/shadow-guard/fast-shadow-idle/expect
vendored
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
pass
|
||||||
60
infra/tests/fixtures/shadow-guard/slow-alone/baseline.jsonl
vendored
Normal file
60
infra/tests/fixtures/shadow-guard/slow-alone/baseline.jsonl
vendored
Normal file
|
|
@ -0,0 +1,60 @@
|
||||||
|
{"t": 1790732513.9182734, "status": "running", "rtMean": 0.8924521636213212, "lag": 14.055, "uptime": 71.036299234}
|
||||||
|
{"t": 1790732524.0150237, "status": "running", "rtMean": 0.8353274823796196, "lag": 16.062, "uptime": 81.13323077}
|
||||||
|
{"t": 1790732534.1210978, "status": "running", "rtMean": 0.8500748093099013, "lag": 17.063, "uptime": 91.228242756}
|
||||||
|
{"t": 1790732544.215337, "status": "running", "rtMean": 0.8468167790642429, "lag": 19.065, "uptime": 101.324762382}
|
||||||
|
{"t": 1790732554.322073, "status": "running", "rtMean": 0.8195776032071418, "lag": 21.069, "uptime": 111.432768959}
|
||||||
|
{"t": 1790732564.4171112, "status": "running", "rtMean": 0.8132396801449534, "lag": 23.128, "uptime": 121.51184336}
|
||||||
|
{"t": 1790732574.6153316, "status": "running", "rtMean": 0.7620145427014579, "lag": 25.169, "uptime": 131.725135168}
|
||||||
|
{"t": 1790732584.921327, "status": "running", "rtMean": 0.8332397110903376, "lag": 27.171, "uptime": 142.033873438}
|
||||||
|
{"t": 1790732595.01128, "status": "running", "rtMean": 0.870312035539666, "lag": 28.172, "uptime": 152.095917692}
|
||||||
|
{"t": 1790732605.1342888, "status": "running", "rtMean": 0.8533222405905535, "lag": 29.174, "uptime": 162.233917268}
|
||||||
|
{"t": 1790732615.2172267, "status": "running", "rtMean": 0.8613640091999233, "lag": 31.183, "uptime": 172.332574842}
|
||||||
|
{"t": 1790732625.292268, "status": "running", "rtMean": 0.8522988744218247, "lag": 32.186, "uptime": 182.413805105}
|
||||||
|
{"t": 1790732635.3641157, "status": "running", "rtMean": 0.9357131448898743, "lag": 33.188, "uptime": 192.485818904}
|
||||||
|
{"t": 1790732645.4261112, "status": "running", "rtMean": 1.0206119648139633, "lag": 33.188, "uptime": 202.528181723}
|
||||||
|
{"t": 1790732655.4861393, "status": "running", "rtMean": 0.9996233335893017, "lag": 33.188, "uptime": 212.597230658}
|
||||||
|
{"t": 1790732665.5481722, "status": "running", "rtMean": 0.9988689561123472, "lag": 33.188, "uptime": 222.643138786}
|
||||||
|
{"t": 1790732675.6082208, "status": "running", "rtMean": 0.9720518244342236, "lag": 33.188, "uptime": 232.688977534}
|
||||||
|
{"t": 1790732685.6701753, "status": "running", "rtMean": 0.9535516201508779, "lag": 33.188, "uptime": 242.776975854}
|
||||||
|
{"t": 1790732695.7341325, "status": "running", "rtMean": 1.0629078918872632, "lag": 33.188, "uptime": 252.850174728}
|
||||||
|
{"t": 1790732705.8101525, "status": "running", "rtMean": 0.9727389888242601, "lag": 33.188, "uptime": 262.903659566}
|
||||||
|
{"t": 1790732715.8741817, "status": "running", "rtMean": 1.0273735099933976, "lag": 33.188, "uptime": 272.974337275}
|
||||||
|
{"t": 1790732725.938133, "status": "running", "rtMean": 1.0004052294537187, "lag": 33.188, "uptime": 283.049608446}
|
||||||
|
{"t": 1790732735.998134, "status": "running", "rtMean": 0.9949238477466771, "lag": 33.188, "uptime": 293.095921712}
|
||||||
|
{"t": 1790732746.058181, "status": "running", "rtMean": 1.001717860791771, "lag": 33.188, "uptime": 303.168958273}
|
||||||
|
{"t": 1790732756.1181643, "status": "running", "rtMean": 0.9904886517209306, "lag": 33.188, "uptime": 313.212038344}
|
||||||
|
{"t": 1790732766.1781104, "status": "running", "rtMean": 1.0019464588045806, "lag": 33.188, "uptime": 323.27335596}
|
||||||
|
{"t": 1790732776.2361557, "status": "running", "rtMean": 0.9964762908263903, "lag": 33.188, "uptime": 333.345377532}
|
||||||
|
{"t": 1790732786.2971303, "status": "running", "rtMean": 0.9919143606076284, "lag": 33.188, "uptime": 343.415231522}
|
||||||
|
{"t": 1790732796.356171, "status": "running", "rtMean": 0.9987406877370043, "lag": 33.188, "uptime": 353.453194803}
|
||||||
|
{"t": 1790732806.4211473, "status": "running", "rtMean": 0.9606955955830612, "lag": 33.188, "uptime": 363.51066889}
|
||||||
|
{"t": 1790732816.4811146, "status": "running", "rtMean": 1.0365607476649523, "lag": 33.188, "uptime": 373.577335699}
|
||||||
|
{"t": 1790732826.5412261, "status": "running", "rtMean": 0.9998410565989371, "lag": 33.188, "uptime": 383.641038325}
|
||||||
|
{"t": 1790732836.6022642, "status": "running", "rtMean": 1.0000077033831407, "lag": 33.188, "uptime": 393.71493795}
|
||||||
|
{"t": 1790732846.66412, "status": "running", "rtMean": 1.000194713414025, "lag": 33.188, "uptime": 403.778353067}
|
||||||
|
{"t": 1790732856.7631304, "status": "running", "rtMean": 0.9963137515722961, "lag": 33.188, "uptime": 413.843209009}
|
||||||
|
{"t": 1790732866.8251379, "status": "running", "rtMean": 1.0024279700647742, "lag": 33.188, "uptime": 423.939536235}
|
||||||
|
{"t": 1790732876.8881218, "status": "running", "rtMean": 0.9998292141625301, "lag": 33.188, "uptime": 434.00196051}
|
||||||
|
{"t": 1790732886.9481704, "status": "running", "rtMean": 1.000376047514638, "lag": 33.188, "uptime": 444.041568588}
|
||||||
|
{"t": 1790732897.0131807, "status": "running", "rtMean": 0.9650577242433412, "lag": 33.188, "uptime": 454.116318252}
|
||||||
|
{"t": 1790732907.0751567, "status": "running", "rtMean": 1.0144244685102852, "lag": 33.188, "uptime": 464.167010558}
|
||||||
|
{"t": 1790732917.135163, "status": "running", "rtMean": 1.0205380747863821, "lag": 33.188, "uptime": 474.251702386}
|
||||||
|
{"t": 1790732927.2051454, "status": "running", "rtMean": 1.0000612465292147, "lag": 33.188, "uptime": 484.315901269}
|
||||||
|
{"t": 1790732937.2681184, "status": "running", "rtMean": 0.9994207833538337, "lag": 33.188, "uptime": 494.376673004}
|
||||||
|
{"t": 1790732947.3331046, "status": "running", "rtMean": 1.000304521129079, "lag": 33.188, "uptime": 504.439961234}
|
||||||
|
{"t": 1790732957.3971682, "status": "running", "rtMean": 1.0002162260543621, "lag": 33.188, "uptime": 514.506681195}
|
||||||
|
{"t": 1790732967.4561813, "status": "running", "rtMean": 0.9940778699094166, "lag": 33.188, "uptime": 524.546264956}
|
||||||
|
{"t": 1790732977.5141263, "status": "running", "rtMean": 0.9996073475880696, "lag": 33.188, "uptime": 534.609522709}
|
||||||
|
{"t": 1790732987.574194, "status": "running", "rtMean": 1.0002335793712973, "lag": 33.188, "uptime": 544.681525736}
|
||||||
|
{"t": 1790732997.63819, "status": "running", "rtMean": 0.9719075938039292, "lag": 33.188, "uptime": 554.746296519}
|
||||||
|
{"t": 1790733007.6981711, "status": "running", "rtMean": 0.9642994644579728, "lag": 33.188, "uptime": 564.819180783}
|
||||||
|
{"t": 1790733017.758178, "status": "running", "rtMean": 1.018785781616432, "lag": 33.188, "uptime": 574.863920385}
|
||||||
|
{"t": 1790733027.8201568, "status": "running", "rtMean": 1.0126053016171566, "lag": 33.188, "uptime": 584.931657624}
|
||||||
|
{"t": 1790733037.8801777, "status": "running", "rtMean": 1.0288813388578921, "lag": 33.188, "uptime": 595.000913192}
|
||||||
|
{"t": 1790733047.9401584, "status": "running", "rtMean": 0.9993726786826045, "lag": 33.188, "uptime": 605.062362454}
|
||||||
|
{"t": 1790733058.0032334, "status": "running", "rtMean": 1.0003288362459641, "lag": 33.188, "uptime": 615.100685166}
|
||||||
|
{"t": 1790733068.0701303, "status": "running", "rtMean": 0.996323054395049, "lag": 33.188, "uptime": 625.182391179}
|
||||||
|
{"t": 1790733078.1311688, "status": "running", "rtMean": 0.9986121232113987, "lag": 33.188, "uptime": 635.237969741}
|
||||||
|
{"t": 1790733088.194169, "status": "running", "rtMean": 0.9998456257825143, "lag": 33.188, "uptime": 645.294446623}
|
||||||
|
{"t": 1790733098.254364, "status": "running", "rtMean": 0.9990527607429407, "lag": 33.188, "uptime": 655.371233565}
|
||||||
|
{"t": 1790733108.3171723, "status": "running", "rtMean": 0.9801059046785113, "lag": 33.188, "uptime": 665.424268239}
|
||||||
20
infra/tests/fixtures/shadow-guard/slow-alone/checks.jsonl
vendored
Normal file
20
infra/tests/fixtures/shadow-guard/slow-alone/checks.jsonl
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
{"t": 1790733119.441622, "status": "running", "rtMean": 0.999626145847037, "lag": 0.0, "uptime": 11.03453719}
|
||||||
|
{"t": 1790733179.5021126, "status": "running", "rtMean": 0.996429238965645, "lag": 0.0, "uptime": 71.109465871}
|
||||||
|
{"t": 1790733239.563163, "status": "running", "rtMean": 1.0001344530283525, "lag": 0.0, "uptime": 131.161767319}
|
||||||
|
{"t": 1790733299.6230712, "status": "running", "rtMean": 1.0051819085367752, "lag": 0.0, "uptime": 191.213566544}
|
||||||
|
{"t": 1790733359.684059, "status": "running", "rtMean": 0.9994857841966536, "lag": 0.0, "uptime": 251.305985353}
|
||||||
|
{"t": 1790733419.744106, "status": "running", "rtMean": 0.9309339263307287, "lag": 1.016, "uptime": 311.343539702}
|
||||||
|
{"t": 1790733479.8072605, "status": "running", "rtMean": 0.9914113663325995, "lag": 1.016, "uptime": 371.420558771}
|
||||||
|
{"t": 1790733539.874109, "status": "running", "rtMean": 1.0150616406858766, "lag": 1.016, "uptime": 431.469758515}
|
||||||
|
{"t": 1790733599.934255, "status": "running", "rtMean": 0.9990854925925501, "lag": 1.016, "uptime": 491.554715659}
|
||||||
|
{"t": 1790733659.998115, "status": "running", "rtMean": 0.9992033155394792, "lag": 1.016, "uptime": 551.614612008}
|
||||||
|
{"t": 1790733720.0581028, "status": "running", "rtMean": 1.0002394824346315, "lag": 1.016, "uptime": 611.653389874}
|
||||||
|
{"t": 1790733780.121188, "status": "running", "rtMean": 1.002487894172868, "lag": 1.016, "uptime": 671.727773294}
|
||||||
|
{"t": 1790733840.1851053, "status": "running", "rtMean": 1.000530724113054, "lag": 1.016, "uptime": 731.80678409}
|
||||||
|
{"t": 1790733900.2461364, "status": "running", "rtMean": 1.000644782810976, "lag": 1.016, "uptime": 791.842628622}
|
||||||
|
{"t": 1790733960.3072183, "status": "running", "rtMean": 0.999652205983927, "lag": 1.016, "uptime": 851.922688196}
|
||||||
|
{"t": 1790734020.3681173, "status": "running", "rtMean": 0.9946548155046125, "lag": 1.016, "uptime": 911.968050417}
|
||||||
|
{"t": 1790734080.4291067, "status": "running", "rtMean": 1.0009058823044212, "lag": 1.016, "uptime": 972.041325345}
|
||||||
|
{"t": 1790734140.4912531, "status": "running", "rtMean": 0.9902809817215064, "lag": 1.016, "uptime": 1032.085088126}
|
||||||
|
{"t": 1790734200.550132, "status": "running", "rtMean": 1.0136589528338944, "lag": 1.016, "uptime": 1092.153292688}
|
||||||
|
{"t": 1790734260.6101415, "status": "running", "rtMean": 0.997751864835789, "lag": 1.016, "uptime": 1152.230885469}
|
||||||
1
infra/tests/fixtures/shadow-guard/slow-alone/expect
vendored
Normal file
1
infra/tests/fixtures/shadow-guard/slow-alone/expect
vendored
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
pass
|
||||||
60
infra/tests/fixtures/shadow-guard/slow-shadow-same/baseline.jsonl
vendored
Normal file
60
infra/tests/fixtures/shadow-guard/slow-shadow-same/baseline.jsonl
vendored
Normal file
|
|
@ -0,0 +1,60 @@
|
||||||
|
{"t": 1790734381.7911441, "status": "running", "rtMean": 0.9991690302798031, "lag": 0.0, "uptime": 71.04094778}
|
||||||
|
{"t": 1790734391.863173, "status": "running", "rtMean": 0.9995511232186312, "lag": 0.0, "uptime": 81.137648009}
|
||||||
|
{"t": 1790734401.9251318, "status": "running", "rtMean": 1.004411393451764, "lag": 0.0, "uptime": 91.179846024}
|
||||||
|
{"t": 1790734411.9851615, "status": "running", "rtMean": 1.0061548832920237, "lag": 0.0, "uptime": 101.244880286}
|
||||||
|
{"t": 1790734422.045158, "status": "running", "rtMean": 1.0009389826422062, "lag": 0.0, "uptime": 111.322533823}
|
||||||
|
{"t": 1790734432.1231213, "status": "running", "rtMean": 0.9994054188236428, "lag": 0.0, "uptime": 121.386590467}
|
||||||
|
{"t": 1790734442.1821327, "status": "running", "rtMean": 1.0019091973172163, "lag": 0.0, "uptime": 131.434675409}
|
||||||
|
{"t": 1790734452.2411315, "status": "running", "rtMean": 1.0003511147658264, "lag": 0.0, "uptime": 141.510042108}
|
||||||
|
{"t": 1790734462.3011394, "status": "running", "rtMean": 0.9998128330113216, "lag": 0.0, "uptime": 151.571854176}
|
||||||
|
{"t": 1790734472.3611345, "status": "running", "rtMean": 0.9995342276541852, "lag": 0.0, "uptime": 161.611024691}
|
||||||
|
{"t": 1790734482.435045, "status": "running", "rtMean": 0.9922858838781137, "lag": 0.0, "uptime": 171.712414098}
|
||||||
|
{"t": 1790734492.4924283, "status": "running", "rtMean": 1.0077000502536002, "lag": 0.0, "uptime": 181.768296008}
|
||||||
|
{"t": 1790734502.590251, "status": "running", "rtMean": 0.688659978029653, "lag": 3.02, "uptime": 191.845836083}
|
||||||
|
{"t": 1790734512.7063384, "status": "running", "rtMean": 0.6918570039489707, "lag": 6.031, "uptime": 201.972741056}
|
||||||
|
{"t": 1790734522.8416302, "status": "running", "rtMean": 0.6636996350321189, "lag": 9.061, "uptime": 212.118463031}
|
||||||
|
{"t": 1790734532.9413493, "status": "running", "rtMean": 0.677691555064422, "lag": 13.117, "uptime": 222.217638708}
|
||||||
|
{"t": 1790734543.0511246, "status": "running", "rtMean": 0.6687714298956552, "lag": 16.132, "uptime": 232.330293687}
|
||||||
|
{"t": 1790734553.214297, "status": "running", "rtMean": 0.6610843395024606, "lag": 19.139, "uptime": 242.48895228}
|
||||||
|
{"t": 1790734563.3515842, "status": "running", "rtMean": 0.652060892547814, "lag": 23.162, "uptime": 252.608110328}
|
||||||
|
{"t": 1790734573.4900045, "status": "running", "rtMean": 0.6695512645097088, "lag": 26.172, "uptime": 262.753496555}
|
||||||
|
{"t": 1790734583.676419, "status": "running", "rtMean": 0.672729094430949, "lag": 30.189, "uptime": 272.933415929}
|
||||||
|
{"t": 1790734593.8542893, "status": "running", "rtMean": 0.6751609713074462, "lag": 33.199, "uptime": 283.119763313}
|
||||||
|
{"t": 1790734603.9855552, "status": "running", "rtMean": 0.6532184360045333, "lag": 36.247, "uptime": 293.24006575}
|
||||||
|
{"t": 1790734614.107205, "status": "running", "rtMean": 0.6660828397073446, "lag": 40.264, "uptime": 303.373977854}
|
||||||
|
{"t": 1790734624.218526, "status": "running", "rtMean": 0.6077386619823459, "lag": 44.344, "uptime": 313.467368475}
|
||||||
|
{"t": 1790734634.3447165, "status": "running", "rtMean": 0.6539609074261248, "lag": 47.354, "uptime": 323.602496592}
|
||||||
|
{"t": 1790734644.4728997, "status": "running", "rtMean": 0.6660933740022716, "lag": 50.368, "uptime": 333.740179276}
|
||||||
|
{"t": 1790734654.5995867, "status": "running", "rtMean": 0.6500636748816758, "lag": 54.395, "uptime": 343.847346535}
|
||||||
|
{"t": 1790734664.7299855, "status": "running", "rtMean": 0.6705859566600052, "lag": 57.409, "uptime": 354.005911843}
|
||||||
|
{"t": 1790734674.917639, "status": "running", "rtMean": 0.6740430368306463, "lag": 61.419, "uptime": 364.191797413}
|
||||||
|
{"t": 1790734685.0660818, "status": "running", "rtMean": 0.6643961460479318, "lag": 64.428, "uptime": 374.341795785}
|
||||||
|
{"t": 1790734695.265925, "status": "running", "rtMean": 0.6579653102367324, "lag": 68.437, "uptime": 384.519988281}
|
||||||
|
{"t": 1790734705.472841, "status": "running", "rtMean": 0.6547900490878023, "lag": 71.446, "uptime": 394.730676243}
|
||||||
|
{"t": 1790734715.6600814, "status": "running", "rtMean": 0.6530533406133286, "lag": 75.466, "uptime": 404.896364288}
|
||||||
|
{"t": 1790734725.7730033, "status": "running", "rtMean": 0.6672820515708326, "lag": 78.47, "uptime": 415.037219103}
|
||||||
|
{"t": 1790734735.8823855, "status": "running", "rtMean": 0.6604279690960906, "lag": 81.507, "uptime": 425.141484166}
|
||||||
|
{"t": 1790734746.0059605, "status": "running", "rtMean": 0.669876056664904, "lag": 85.525, "uptime": 435.241624797}
|
||||||
|
{"t": 1790734756.16065, "status": "running", "rtMean": 0.6669554325713298, "lag": 88.532, "uptime": 445.424510067}
|
||||||
|
{"t": 1790734766.2961965, "status": "running", "rtMean": 0.6789691324390087, "lag": 91.546, "uptime": 455.562624387}
|
||||||
|
{"t": 1790734776.4270732, "status": "running", "rtMean": 0.6764526659523141, "lag": 95.567, "uptime": 465.699227051}
|
||||||
|
{"t": 1790734786.5895793, "status": "running", "rtMean": 0.6530891711548452, "lag": 98.603, "uptime": 475.850685381}
|
||||||
|
{"t": 1790734796.7317367, "status": "running", "rtMean": 0.6406146952722656, "lag": 102.675, "uptime": 486.00189116}
|
||||||
|
{"t": 1790734806.8721528, "status": "running", "rtMean": 0.6453060329257198, "lag": 105.69, "uptime": 496.149729812}
|
||||||
|
{"t": 1790734817.0070937, "status": "running", "rtMean": 0.6454966448957478, "lag": 109.706, "uptime": 506.283307741}
|
||||||
|
{"t": 1790734827.1343982, "status": "running", "rtMean": 0.6448485469528062, "lag": 112.72, "uptime": 516.409124389}
|
||||||
|
{"t": 1790734837.2881198, "status": "running", "rtMean": 0.6535926679887758, "lag": 116.748, "uptime": 526.560442848}
|
||||||
|
{"t": 1790734847.4209673, "status": "running", "rtMean": 0.6425044322629614, "lag": 119.784, "uptime": 536.693837434}
|
||||||
|
{"t": 1790734857.5829508, "status": "running", "rtMean": 0.6452458464522223, "lag": 123.802, "uptime": 546.8305001}
|
||||||
|
{"t": 1790734867.7133708, "status": "running", "rtMean": 0.6302281366614498, "lag": 127.82, "uptime": 556.984448186}
|
||||||
|
{"t": 1790734877.8158286, "status": "running", "rtMean": 0.6629500748501092, "lag": 130.844, "uptime": 567.072718764}
|
||||||
|
{"t": 1790734887.943275, "status": "running", "rtMean": 0.6648674424022735, "lag": 133.854, "uptime": 577.200347159}
|
||||||
|
{"t": 1790734898.06847, "status": "running", "rtMean": 0.6593429199106378, "lag": 137.876, "uptime": 587.328798352}
|
||||||
|
{"t": 1790734908.210695, "status": "running", "rtMean": 0.662979366140112, "lag": 140.891, "uptime": 597.465073525}
|
||||||
|
{"t": 1790734918.3496716, "status": "running", "rtMean": 0.6614754105222075, "lag": 144.914, "uptime": 607.619842905}
|
||||||
|
{"t": 1790734928.486646, "status": "running", "rtMean": 0.6692348242211306, "lag": 147.924, "uptime": 617.724273337}
|
||||||
|
{"t": 1790734938.6051722, "status": "running", "rtMean": 0.6733974004623173, "lag": 150.942, "uptime": 627.874978882}
|
||||||
|
{"t": 1790734948.703509, "status": "running", "rtMean": 0.6484292959854895, "lag": 154.965, "uptime": 637.96851242}
|
||||||
|
{"t": 1790734958.9605355, "status": "running", "rtMean": 0.6326829212607562, "lag": 158.977, "uptime": 648.224285288}
|
||||||
|
{"t": 1790734969.0924904, "status": "running", "rtMean": 0.6743317584475094, "lag": 162.001, "uptime": 658.352731683}
|
||||||
|
{"t": 1790734979.512936, "status": "running", "rtMean": 0.66105927868997, "lag": 165.016, "uptime": 668.754929041}
|
||||||
20
infra/tests/fixtures/shadow-guard/slow-shadow-same/checks.jsonl
vendored
Normal file
20
infra/tests/fixtures/shadow-guard/slow-shadow-same/checks.jsonl
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
{"t": 1790734991.7640753, "status": "running", "rtMean": 0.6359105463426694, "lag": 3.008, "uptime": 11.070042764}
|
||||||
|
{"t": 1790735051.931584, "status": "running", "rtMean": 0.4413866438713924, "lag": 31.225, "uptime": 71.270223818}
|
||||||
|
{"t": 1790735112.0636158, "status": "running", "rtMean": 0.528275325797771, "lag": 56.478, "uptime": 131.388274947}
|
||||||
|
{"t": 1790735172.2191246, "status": "running", "rtMean": 0.5653650170639056, "lag": 85.705, "uptime": 191.513860632}
|
||||||
|
{"t": 1790735232.3440776, "status": "running", "rtMean": 0.598275320104138, "lag": 110.037, "uptime": 251.674657096}
|
||||||
|
{"t": 1790735292.5060995, "status": "running", "rtMean": 0.6030301486902879, "lag": 134.326, "uptime": 311.836161733}
|
||||||
|
{"t": 1790735352.646486, "status": "running", "rtMean": 0.6475849197046364, "lag": 156.459, "uptime": 371.966818709}
|
||||||
|
{"t": 1790735412.780515, "status": "running", "rtMean": 0.5770778494664259, "lag": 179.892, "uptime": 432.08998512}
|
||||||
|
{"t": 1790735472.8577662, "status": "running", "rtMean": 0.6886656579593289, "lag": 198.051, "uptime": 492.201636495}
|
||||||
|
{"t": 1790735532.9329088, "status": "running", "rtMean": 0.7616039578620443, "lag": 210.17, "uptime": 552.275859184}
|
||||||
|
{"t": 1790735592.995646, "status": "running", "rtMean": 0.8492741277663118, "lag": 225.508, "uptime": 612.316843322}
|
||||||
|
{"t": 1790735653.0601382, "status": "running", "rtMean": 0.8233088403353765, "lag": 232.541, "uptime": 672.386139571}
|
||||||
|
{"t": 1790735713.1299574, "status": "running", "rtMean": 0.8821898469526929, "lag": 239.649, "uptime": 732.468014006}
|
||||||
|
{"t": 1790735773.1924357, "status": "running", "rtMean": 0.9074726134753647, "lag": 243.655, "uptime": 792.527038261}
|
||||||
|
{"t": 1790735833.2571187, "status": "running", "rtMean": 0.899453016514728, "lag": 250.877, "uptime": 852.593245225}
|
||||||
|
{"t": 1790735893.3221343, "status": "running", "rtMean": 0.6620087337657867, "lag": 258.043, "uptime": 912.634830266}
|
||||||
|
{"t": 1790735953.5102656, "status": "running", "rtMean": 0.4740061480416233, "lag": 290.508, "uptime": 972.827598732}
|
||||||
|
{"t": 1790736013.6372716, "status": "running", "rtMean": 0.552244625226687, "lag": 321.774, "uptime": 1032.942900792}
|
||||||
|
{"t": 1790736073.7192469, "status": "running", "rtMean": 0.5496939405024359, "lag": 348.997, "uptime": 1093.015463153}
|
||||||
|
{"t": 1790736133.779931, "status": "running", "rtMean": 0.8831947829035597, "lag": 362.15, "uptime": 1153.096169148}
|
||||||
1
infra/tests/fixtures/shadow-guard/slow-shadow-same/expect
vendored
Normal file
1
infra/tests/fixtures/shadow-guard/slow-shadow-same/expect
vendored
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
trip
|
||||||
|
|
@ -510,6 +510,157 @@ if grep -E '^(ALWAYS_ON_UNITS|APP_UNITS)=' "$INFRA_DIR/07-enable.sh" "$INFRA_DIR
|
||||||
else
|
else
|
||||||
pass "07-enable.sh and verify.sh leave flyedge.service alone"
|
pass "07-enable.sh and verify.sh leave flyedge.service alone"
|
||||||
fi
|
fi
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 3b3. The shadow run (SHADOW-01, infra/units/flyshadow.service).
|
||||||
|
#
|
||||||
|
# Report-only and off by default. What would break it is statically visible: the unit ending up
|
||||||
|
# in a target or 07-enable's list; being bound to flysim (every flysim restart would take the
|
||||||
|
# shadow with it, and it must follow restarts, not die of them); restarting after a divergence
|
||||||
|
# (the verdict must stay); losing its idle scheduling (it must never take a live cycle); or
|
||||||
|
# landing on flysim's cpuset.
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
echo "--- flyshadow.service: off by default, report-only, idle, never bound to flysim ---"
|
||||||
|
SHADOW_UNIT="$INFRA_DIR/units/flyshadow.service"
|
||||||
|
if [ ! -f "$SHADOW_UNIT" ]; then
|
||||||
|
fail "units/flyshadow.service is missing"
|
||||||
|
else
|
||||||
|
grep -qE '^ExecStart=/opt/fly/current/fly-shadow run$' "$SHADOW_UNIT" \
|
||||||
|
&& pass "flyshadow.service runs the release's fly-shadow" \
|
||||||
|
|| fail "flyshadow.service ExecStart must be /opt/fly/current/fly-shadow run"
|
||||||
|
grep -qE '^ConditionPathExists=/opt/fly/current/fly-shadow$' "$SHADOW_UNIT" \
|
||||||
|
&& pass "flyshadow.service stays inactive on a release without fly-shadow" \
|
||||||
|
|| fail "flyshadow.service needs ConditionPathExists=/opt/fly/current/fly-shadow"
|
||||||
|
if grep -qE '^(Requires|BindsTo|PartOf|Requisite)=.*flysim' "$SHADOW_UNIT"; then
|
||||||
|
fail "flyshadow.service must not be bound to flysim.service: it follows flysim's restarts"
|
||||||
|
else
|
||||||
|
pass "flyshadow.service outlives flysim restarts (not bound to flysim.service)"
|
||||||
|
fi
|
||||||
|
grep -qE '^RestartPreventExitStatus=3$' "$SHADOW_UNIT" \
|
||||||
|
&& pass "flyshadow.service stays stopped after a divergence (exit 3)" \
|
||||||
|
|| fail "flyshadow.service needs RestartPreventExitStatus=3 so a diverged verdict stays"
|
||||||
|
grep -qE '^CPUSchedulingPolicy=idle$' "$SHADOW_UNIT" \
|
||||||
|
&& pass "flyshadow.service runs SCHED_IDLE" \
|
||||||
|
|| fail "flyshadow.service must be CPUSchedulingPolicy=idle: it may only use idle CPU"
|
||||||
|
grep -qE '^\[Install\]' "$SHADOW_UNIT" \
|
||||||
|
&& fail "flyshadow.service has an [Install] section; it is started by fly-shadow-run only" \
|
||||||
|
|| pass "flyshadow.service has no [Install] section (never enabled)"
|
||||||
|
fi
|
||||||
|
if target_pulls "$INFRA_DIR/units/fly.target" | grep -qx 'flyshadow.service'; then
|
||||||
|
fail "fly.target pulls flyshadow.service in; it must stay off until fly-shadow-run starts it"
|
||||||
|
else
|
||||||
|
pass "fly.target does not pull flyshadow.service in"
|
||||||
|
fi
|
||||||
|
if grep -E '^(ALWAYS_ON_UNITS|APP_UNITS)=' "$INFRA_DIR/07-enable.sh" "$INFRA_DIR/verify.sh" | grep -q 'flyshadow'; then
|
||||||
|
fail "07-enable.sh or verify.sh lists flyshadow.service as always-on"
|
||||||
|
else
|
||||||
|
pass "07-enable.sh and verify.sh leave flyshadow.service alone"
|
||||||
|
fi
|
||||||
|
for u in flyshadow-guard.timer flyshadow-guard.service; do
|
||||||
|
if [ ! -f "$INFRA_DIR/units/$u" ]; then
|
||||||
|
fail "units/$u is missing"
|
||||||
|
elif grep -qE '^\[Install\]' "$INFRA_DIR/units/$u"; then
|
||||||
|
fail "$u has an [Install] section; fly-shadow-run starts and stops it"
|
||||||
|
else
|
||||||
|
pass "$u is never enabled (started by fly-shadow-run only)"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
# The guard's rule, driven for real (python3 is on every container this repo provisions) over
|
||||||
|
# RTF traces: synthetic ones shaped on the release CT's own numbers (tests/shadow_guard_traces.py)
|
||||||
|
# and ones recorded from a real flysim with and without a shadow (tests/fixtures/shadow-guard/).
|
||||||
|
# A fly that was already below real time must never trip it; a genuine degradation must.
|
||||||
|
if command -v python3 >/dev/null 2>&1; then
|
||||||
|
g_tmp="$(mktemp -d "${TMPDIR:-/tmp}/fly-lint-guard.XXXXXX")"
|
||||||
|
guard_trace() { # name, dir with baseline.jsonl and checks.jsonl, expect (pass|trip)
|
||||||
|
local out rc=0
|
||||||
|
out="$("$INFRA_DIR/bin/fly-shadow-run" simulate "$2/baseline.jsonl" "$2/checks.jsonl")" || rc=$?
|
||||||
|
if { [ "$3" = pass ] && [ "$rc" = 0 ]; } || { [ "$3" = trip ] && [ "$rc" = 1 ]; }; then
|
||||||
|
pass "fly-shadow-run guard, $1: ${out%% (baseline*}"
|
||||||
|
else
|
||||||
|
fail "fly-shadow-run guard, $1: expected $3, got exit $rc: $out"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
while read -r name expect; do
|
||||||
|
guard_trace "$name" "$g_tmp/$name" "$expect"
|
||||||
|
done < <(python3 "$INFRA_DIR/tests/shadow_guard_traces.py" "$g_tmp")
|
||||||
|
for d in "$INFRA_DIR"/tests/fixtures/shadow-guard/*/; do
|
||||||
|
[ -f "$d/expect" ] || continue
|
||||||
|
guard_trace "recorded $(basename "$d")" "$d" "$(cat "$d/expect")"
|
||||||
|
done
|
||||||
|
# The guard's lifecycle and `check`'s preconditions (review round 3, G1-a), with a fake systemctl
|
||||||
|
# (`show` answers FAKE_SHADOW_STATE; the timer is active when FAKE_TIMER_ACTIVE=yes), a fake `id`
|
||||||
|
# (root) and a metrics URL nobody listens on (a live guard then reports "not judged" and stays).
|
||||||
|
gl_bin="$g_tmp/lifecycle-bin"; gl_dir="$g_tmp/lifecycle-shadow"
|
||||||
|
mkdir -p "$gl_bin" "$gl_dir"
|
||||||
|
cat > "$gl_bin/systemctl" <<'GLSYSTEMCTL'
|
||||||
|
#!/bin/sh
|
||||||
|
echo "$*" >> "$FAKE_SYSTEMCTL_LOG"
|
||||||
|
case "$1" in
|
||||||
|
show) printf 'ActiveState=%s\nSubState=x\n' "$FAKE_SHADOW_STATE" ;;
|
||||||
|
is-active)
|
||||||
|
case "$3" in
|
||||||
|
flyshadow.service) [ "$FAKE_SHADOW_STATE" = active ]; exit $? ;;
|
||||||
|
flyshadow-guard.timer) [ "$FAKE_TIMER_ACTIVE" = yes ]; exit $? ;;
|
||||||
|
*) exit 3 ;;
|
||||||
|
esac ;;
|
||||||
|
esac
|
||||||
|
exit 0
|
||||||
|
GLSYSTEMCTL
|
||||||
|
cat > "$gl_bin/id" <<'GLID'
|
||||||
|
#!/bin/sh
|
||||||
|
[ "$1" = -u ] && { echo 0; exit 0; }
|
||||||
|
exec /usr/bin/id "$@"
|
||||||
|
GLID
|
||||||
|
chmod +x "$gl_bin/systemctl" "$gl_bin/id"
|
||||||
|
gl_run() { # args to fly-shadow-run; env FAKE_SHADOW_STATE, FAKE_TIMER_ACTIVE from the caller
|
||||||
|
: > "$g_tmp/systemctl.log"
|
||||||
|
PATH="$gl_bin:$PATH" FAKE_SYSTEMCTL_LOG="$g_tmp/systemctl.log" FLY_SHADOW_DIR="$gl_dir" \
|
||||||
|
FLY_METRICS_URL=http://127.0.0.1:1 FLY_SHADOW_BIN="$g_tmp/none" \
|
||||||
|
"$INFRA_DIR/bin/fly-shadow-run" "$@" 2>&1
|
||||||
|
}
|
||||||
|
printf '{"rtfMean":0.66,"rtfSd":0.01,"lagRate":0.3,"samples":60,"margin":0.05}\n' > "$gl_dir/baseline.json"
|
||||||
|
printf '{}\n' > "$gl_dir/guard-state.json"
|
||||||
|
for st in activating deactivating; do
|
||||||
|
FAKE_SHADOW_STATE=$st FAKE_TIMER_ACTIVE=yes gl_run guard > "$g_tmp/out" || true
|
||||||
|
if grep -q 'stop flyshadow-guard.timer' "$g_tmp/systemctl.log"; then
|
||||||
|
fail "fly-shadow-run guard stopped its timer while flyshadow was $st (auto-restart): $(cat "$g_tmp/out")"
|
||||||
|
else
|
||||||
|
pass "fly-shadow-run guard keeps running while flyshadow is $st (crash-restart delay)"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
for st in inactive failed; do
|
||||||
|
FAKE_SHADOW_STATE=$st FAKE_TIMER_ACTIVE=yes gl_run guard > "$g_tmp/out" || true
|
||||||
|
if grep -q 'stop flyshadow-guard.timer' "$g_tmp/systemctl.log"; then
|
||||||
|
pass "fly-shadow-run guard stops its timer when flyshadow is $st"
|
||||||
|
else
|
||||||
|
fail "fly-shadow-run guard kept running with flyshadow $st: $(cat "$g_tmp/out")"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
gl_check() { # name, expected (refused|passes-gates), then the env
|
||||||
|
local out rc=0
|
||||||
|
out="$(gl_run check)" || rc=$?
|
||||||
|
case "$2:$rc" in
|
||||||
|
refused:1) pass "fly-shadow-run check, $1: ${out%%(*}" ;;
|
||||||
|
passes-gates:2) pass "fly-shadow-run check, $1: past the guard preconditions" ;;
|
||||||
|
*) fail "fly-shadow-run check, $1: expected $2, got exit $rc: $out" ;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
FAKE_SHADOW_STATE=active FAKE_TIMER_ACTIVE=yes gl_check "guarded run" passes-gates
|
||||||
|
FAKE_SHADOW_STATE=active FAKE_TIMER_ACTIVE=no gl_check "guard timer not active" refused
|
||||||
|
FAKE_SHADOW_STATE=activating FAKE_TIMER_ACTIVE=yes gl_check "shadow restarting" refused
|
||||||
|
mv "$gl_dir/baseline.json" "$gl_dir/baseline.json.off"
|
||||||
|
FAKE_SHADOW_STATE=active FAKE_TIMER_ACTIVE=yes gl_check "no baseline.json" refused
|
||||||
|
mv "$gl_dir/baseline.json.off" "$gl_dir/baseline.json"
|
||||||
|
echo '{}' > "$gl_dir/guard-tripped.json"
|
||||||
|
FAKE_SHADOW_STATE=active FAKE_TIMER_ACTIVE=yes gl_check "guard tripped" refused
|
||||||
|
rm -rf "$g_tmp"
|
||||||
|
else
|
||||||
|
fail "python3 is needed to test fly-shadow-run's guard rule"
|
||||||
|
fi
|
||||||
|
if grep -qF 'flyshadow) cpus="${page_cpus},${encoder_cpus}" ;;' "$INFRA_DIR/05-deploy.sh"; then
|
||||||
|
pass "05-deploy.sh keeps flyshadow.service off flysim's CPUs"
|
||||||
|
else
|
||||||
|
fail "05-deploy.sh must give flyshadow.service the page and encoder CPUs, never flysim's"
|
||||||
|
fi
|
||||||
if grep -qF 'FLY_FEED_VIA_EFFECTIVE="$(feed_via_normalize "${FLY_FEED_VIA:-}")"' "$INFRA_DIR/05-deploy.sh" \
|
if grep -qF 'FLY_FEED_VIA_EFFECTIVE="$(feed_via_normalize "${FLY_FEED_VIA:-}")"' "$INFRA_DIR/05-deploy.sh" \
|
||||||
&& grep -qF 'echo "FLY_FEED_VIA=${FLY_FEED_VIA_EFFECTIVE}"' "$INFRA_DIR/05-deploy.sh"; then
|
&& grep -qF 'echo "FLY_FEED_VIA=${FLY_FEED_VIA_EFFECTIVE}"' "$INFRA_DIR/05-deploy.sh"; then
|
||||||
pass "05-deploy.sh validates FLY_FEED_VIA and writes the normalized value"
|
pass "05-deploy.sh validates FLY_FEED_VIA and writes the normalized value"
|
||||||
|
|
|
||||||
136
infra/tests/shadow_guard_traces.py
Normal file
136
infra/tests/shadow_guard_traces.py
Normal file
|
|
@ -0,0 +1,136 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Synthetic live-fly RTF traces for fly-shadow-run's guard (SHADOW-01 review round 2, G1).
|
||||||
|
|
||||||
|
shadow_guard_traces.py OUTDIR
|
||||||
|
|
||||||
|
Writes <case>/baseline.jsonl and <case>/checks.jsonl in fly-shadow-run's sample format
|
||||||
|
({t, status, rtMean, lag, uptime}) and prints one line per case: `<case> <expect>`, where
|
||||||
|
<expect> is `pass` (the guard must not trip) or `trip` (it must). The baseline is 60 samples 10 s
|
||||||
|
apart (start's 10 minutes); the checks are one sample a minute for the given length.
|
||||||
|
|
||||||
|
The lag follows flysim's pacer: a fly behind real time owes (1 - rtf) seconds per second, and the
|
||||||
|
pacer books it as lag only in chunks of more than a second (`pacing::MAX_CATCHUP`).
|
||||||
|
|
||||||
|
The cases come from the release container's own numbers (the coordinator's samples, agents.log
|
||||||
|
2026-09-30 00:08Z): a flat 0.66 before the cpuset rebalance, 0.77-0.99 noisy after it, plus a fly
|
||||||
|
at real time; each alone (must pass), and each with a genuine degradation after the start (must
|
||||||
|
trip).
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
class Fly:
|
||||||
|
def __init__(self, seed):
|
||||||
|
self.rng = random.Random(seed)
|
||||||
|
self.t, self.uptime, self.lag, self.debt = 1_790_000_000.0, 3600.0, 12.0, 0.0
|
||||||
|
|
||||||
|
def run(self, seconds, rtf_of):
|
||||||
|
"""Advances `seconds` of wall time at the realtime factors `rtf_of()` gives per second."""
|
||||||
|
rtfs = []
|
||||||
|
for _ in range(int(seconds)):
|
||||||
|
rtf = rtf_of(self.rng)
|
||||||
|
rtfs.append(rtf)
|
||||||
|
self.debt += max(0.0, 1.0 - rtf)
|
||||||
|
if self.debt > 1.0:
|
||||||
|
self.lag += self.debt
|
||||||
|
self.debt = 0.0
|
||||||
|
self.t += 1
|
||||||
|
self.uptime += 1
|
||||||
|
return rtfs
|
||||||
|
|
||||||
|
def sample(self, rtf_of, status="running"):
|
||||||
|
rtfs = self.run(10, rtf_of)
|
||||||
|
return {"t": self.t, "status": status, "rtMean": sum(rtfs) / len(rtfs),
|
||||||
|
"lag": round(self.lag, 3), "uptime": self.uptime}
|
||||||
|
|
||||||
|
def restart(self):
|
||||||
|
self.uptime, self.lag, self.debt = 5.0, 0.0, 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def flat(v, jitter=0.01):
|
||||||
|
return lambda rng: v + rng.uniform(-jitter, jitter)
|
||||||
|
|
||||||
|
|
||||||
|
def noisy(lo, hi):
|
||||||
|
return lambda rng: rng.uniform(lo, hi)
|
||||||
|
|
||||||
|
|
||||||
|
def noisy_windows(lo, hi):
|
||||||
|
"""Noise at the sample level: each 10 s holds one value in [lo, hi], so the 10-s means the
|
||||||
|
guard reads spread over the whole range (the coordinator's samples)."""
|
||||||
|
state = {"n": 0, "v": None}
|
||||||
|
|
||||||
|
def pace(rng):
|
||||||
|
if state["n"] % 10 == 0:
|
||||||
|
state["v"] = rng.uniform(lo, hi)
|
||||||
|
state["n"] += 1
|
||||||
|
return state["v"]
|
||||||
|
|
||||||
|
return pace
|
||||||
|
|
||||||
|
|
||||||
|
def realtime(rng):
|
||||||
|
return min(1.0, 1.0 + rng.uniform(-0.004, 0.002))
|
||||||
|
|
||||||
|
|
||||||
|
def case(seed, before, after, checks=180, degrade_at=None, events=None):
|
||||||
|
fly = Fly(seed)
|
||||||
|
baseline = [fly.sample(before) for _ in range(60)]
|
||||||
|
fly.restart() # start's own flysim restart
|
||||||
|
rows = []
|
||||||
|
for n in range(checks):
|
||||||
|
pace = after if degrade_at is not None and n >= degrade_at else before
|
||||||
|
status = "running"
|
||||||
|
if events and n in events:
|
||||||
|
kind = events[n]
|
||||||
|
if kind == "restart":
|
||||||
|
fly.restart()
|
||||||
|
elif kind == "paused":
|
||||||
|
status = "paused"
|
||||||
|
elif kind == "hiccup":
|
||||||
|
fly.lag += 1.3 # one pacing shortfall of 1.3 s, nothing more
|
||||||
|
rows.append(fly.sample(pace, status))
|
||||||
|
fly.run(50, pace)
|
||||||
|
return baseline, rows
|
||||||
|
|
||||||
|
|
||||||
|
CASES = {
|
||||||
|
# The release CT before the rebalance: a flat 0.66, 3 hours, with a restart and a pause.
|
||||||
|
"ct-flat-0.66": (case(1, flat(0.66), None, events={40: "restart", 90: "paused", 91: "paused"}), "pass"),
|
||||||
|
# After the rebalance: 0.77-0.99 noisy, 3 hours, a restart.
|
||||||
|
"ct-noisy-0.77-0.99": (case(2, noisy(0.77, 0.99), None, events={120: "restart"}), "pass"),
|
||||||
|
"ct-noisy-0.77-0.99-seed3": (case(3, noisy(0.77, 0.99), None), "pass"),
|
||||||
|
# The same spread at the level of the 10-s samples themselves, the harder case.
|
||||||
|
"ct-samples-0.77-0.99": (case(8, noisy_windows(0.77, 0.99), None, events={60: "restart"}), "pass"),
|
||||||
|
"ct-samples-0.77-0.99-seed9": (case(9, noisy_windows(0.77, 0.99), None), "pass"),
|
||||||
|
"ct-samples-0.77-0.99-seed10": (case(10, noisy_windows(0.77, 0.99), None), "pass"),
|
||||||
|
# At real time, with single pacing hiccups: never a trip.
|
||||||
|
"realtime-hiccups": (case(4, realtime, None, events={30: "hiccup", 100: "hiccup", 150: "hiccup"}), "pass"),
|
||||||
|
# A shadow that costs the fly real time.
|
||||||
|
"ct-flat-0.66-then-0.55": (case(5, flat(0.66), flat(0.55), checks=40, degrade_at=15), "trip"),
|
||||||
|
"ct-noisy-then-0.60-0.75": (case(6, noisy(0.77, 0.99), noisy(0.60, 0.75), checks=40, degrade_at=15), "trip"),
|
||||||
|
"realtime-then-0.90": (case(7, realtime, flat(0.90), checks=40, degrade_at=15), "trip"),
|
||||||
|
"ct-samples-then-0.55-0.75": (
|
||||||
|
case(11, noisy_windows(0.77, 0.99), noisy_windows(0.55, 0.75), checks=40, degrade_at=15),
|
||||||
|
"trip",
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
out = sys.argv[1]
|
||||||
|
for name, ((baseline, checks), expect) in CASES.items():
|
||||||
|
d = os.path.join(out, name)
|
||||||
|
os.makedirs(d, exist_ok=True)
|
||||||
|
for fname, rows in (("baseline.jsonl", baseline), ("checks.jsonl", checks)):
|
||||||
|
with open(os.path.join(d, fname), "w") as f:
|
||||||
|
for r in rows:
|
||||||
|
f.write(json.dumps(r) + "\n")
|
||||||
|
print(name, expect)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
15
infra/units/flyshadow-guard.service
Normal file
15
infra/units/flyshadow-guard.service
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
# infra/units/flyshadow-guard.service — triggered by flyshadow-guard.timer.
|
||||||
|
#
|
||||||
|
# `fly-shadow-run guard` compares the live fly with the 10-minute baseline `fly-shadow-run start`
|
||||||
|
# recorded before it started the shadow: on a sustained degradation of the realtime factor or the
|
||||||
|
# lag growth rate against that baseline (3 checks in a row, 5-sample windows), it stops
|
||||||
|
# flyshadow.service, removes the trace drop-in and restarts flysim without the trace. The live
|
||||||
|
# stream never pays for the shadow. It stops itself when the shadow is not running. Root, because it installs no file but
|
||||||
|
# removes one in /etc/systemd and restarts flysim.
|
||||||
|
[Unit]
|
||||||
|
Description=fly-shadow-run guard: the live-impact check of the shadow run (SHADOW-01)
|
||||||
|
ConditionPathExists=/srv/fly/shadow/baseline.json
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=oneshot
|
||||||
|
ExecStart=/opt/fly/bin/fly-shadow-run guard
|
||||||
11
infra/units/flyshadow-guard.timer
Normal file
11
infra/units/flyshadow-guard.timer
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
# infra/units/flyshadow-guard.timer — SHADOW-01's live-impact guard, every 60 s while a shadow
|
||||||
|
# runs. Started by `fly-shadow-run start`, stopped by `fly-shadow-run stop` and by the guard
|
||||||
|
# itself when it trips. No [Install]: it is never enabled, so a reboot does not start it.
|
||||||
|
[Unit]
|
||||||
|
Description=Stop the shadow run if the live fly pays for it (SHADOW-01)
|
||||||
|
|
||||||
|
[Timer]
|
||||||
|
OnActiveSec=60s
|
||||||
|
OnUnitActiveSec=60s
|
||||||
|
AccuracySec=5s
|
||||||
|
Unit=flyshadow-guard.service
|
||||||
66
infra/units/flyshadow.service
Normal file
66
infra/units/flyshadow.service
Normal file
|
|
@ -0,0 +1,66 @@
|
||||||
|
# infra/units/flyshadow.service — pushed to /etc/systemd/system/flyshadow.service.
|
||||||
|
#
|
||||||
|
# SHADOW-01 (docs/design/session-framework/legacy-gameboy-v1.md section 18): the
|
||||||
|
# session runtime run beside the live fly. REPORT-ONLY: it presses no button,
|
||||||
|
# serves no port, and only READS flysim's stores and trace; it writes nothing
|
||||||
|
# but /srv/fly/shadow (verdict.json, divergence.json, its spool) and its
|
||||||
|
# runtime directory. DISABLED BY DEFAULT: in no target's Wants=/Requires=,
|
||||||
|
# not in 07-enable.sh. `fly-shadow-run start` (infra/bin) starts it, turns
|
||||||
|
# flysim's trace on and restarts flysim once so the shadow follows a process
|
||||||
|
# from its first frame; `fly-shadow-run stop` undoes both.
|
||||||
|
#
|
||||||
|
# Deliberately NOT bound to flysim (no Requires=/BindsTo=/PartOf=): every
|
||||||
|
# flysim restart (the unstick rule, the watchdog, fly-loop-recover, a
|
||||||
|
# milestone reset) is a new trace file the shadow follows on its own, so the
|
||||||
|
# shadow must outlive them. It stops itself on the first divergence with exit
|
||||||
|
# status 3 and a `diverged` verdict; RestartPreventExitStatus keeps it
|
||||||
|
# stopped so the verdict stays for the coordinator to read.
|
||||||
|
#
|
||||||
|
# Resources (the SHADOW-01 report, "resource plan"): a second whole brain,
|
||||||
|
# about the live fly's own CPU per frame. It must never take a cycle the live
|
||||||
|
# fly, the page or the encoder wants, so it runs SCHED_IDLE (it only gets CPU
|
||||||
|
# nobody else is using), off flysim's cpuset (05-deploy.sh writes
|
||||||
|
# AllowedCPUs= for it from the page and encoder groups). It pauses for a minute
|
||||||
|
# while flysim's lag grows faster than its pre-start baseline rate (and stops
|
||||||
|
# pausing when that does not help: then it is not the cause).
|
||||||
|
# flyshadow-guard.timer (fly-shadow-run guard) stops it and restarts flysim
|
||||||
|
# without the trace on a sustained degradation against that baseline. It is lag-tolerant: the trace and the
|
||||||
|
# spool are on disk, so running behind real time only delays the verdict (the
|
||||||
|
# 512 MiB spool covers about 15 minutes of lag for hot saves).
|
||||||
|
#
|
||||||
|
# Its heartbeat (<trace dir>/consumer, every 30 s, removed when it stops) is
|
||||||
|
# what keeps flysim tracing: a stopped, diverged or crashed shadow turns the
|
||||||
|
# live trace off within a minute of a stale heartbeat, with no root action.
|
||||||
|
[Unit]
|
||||||
|
Description=flyshadow: the session runtime shadowing the live fly (SHADOW-01, report only)
|
||||||
|
After=flysim.service
|
||||||
|
# A release that predates SHADOW-01 has no binary; stay cleanly inactive.
|
||||||
|
ConditionPathExists=/opt/fly/current/fly-shadow
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=fly
|
||||||
|
# The live service's configuration, read the way flysim reads it: the
|
||||||
|
# cartridge, the dataset, the macro mode, the speed. The store paths and the
|
||||||
|
# metrics listener are flysim.service's own Environment= lines, repeated.
|
||||||
|
EnvironmentFile=/etc/fly/fly.env
|
||||||
|
Environment=FLY_STATE_HOT=/run/fly/state
|
||||||
|
Environment=FLY_STATE=/srv/fly/state
|
||||||
|
Environment=FLY_METRICS_ADDR=0.0.0.0:9101
|
||||||
|
# What flysim writes with the shadow's drop-in (fly-shadow-run), and where the
|
||||||
|
# verdict goes. The session's sockets and artifacts live on tmpfs.
|
||||||
|
Environment=FLY_TRACE_DIR=/srv/fly/shadow/trace
|
||||||
|
Environment=FLY_SHADOW_DIR=/srv/fly/shadow
|
||||||
|
Environment=FLY_SHADOW_WORK=/run/fly-shadow
|
||||||
|
RuntimeDirectory=fly-shadow
|
||||||
|
# The shadow agent's sweep threads (the report's measurements).
|
||||||
|
Environment=FLY_SHADOW_THREADS=2
|
||||||
|
ExecStart=/opt/fly/current/fly-shadow run
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=10
|
||||||
|
RestartPreventExitStatus=3
|
||||||
|
CPUSchedulingPolicy=idle
|
||||||
|
Nice=19
|
||||||
|
CPUWeight=1
|
||||||
|
IOSchedulingClass=idle
|
||||||
|
MemoryMax=3G
|
||||||
|
|
@ -16,6 +16,11 @@ path = "src/lib.rs"
|
||||||
name = "flysim-session"
|
name = "flysim-session"
|
||||||
path = "src/bin/flysim-session.rs"
|
path = "src/bin/flysim-session.rs"
|
||||||
|
|
||||||
|
# SHADOW-01: the session runtime run beside the live fly (`infra/units/flyshadow.service`).
|
||||||
|
[[bin]]
|
||||||
|
name = "fly-shadow"
|
||||||
|
path = "src/bin/fly-shadow.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
# The session framework and its legacy workers (AGENT-01, ENV-01).
|
# The session framework and its legacy workers (AGENT-01, ENV-01).
|
||||||
fly-session = { path = "../fly-session" }
|
fly-session = { path = "../fly-session" }
|
||||||
|
|
@ -28,7 +33,7 @@ flysim = { path = "../flysim" }
|
||||||
flybrain-gb = { path = "../flybrain-gb" }
|
flybrain-gb = { path = "../flybrain-gb" }
|
||||||
flybrain-core = { path = "../flybrain-core" }
|
flybrain-core = { path = "../flybrain-core" }
|
||||||
serde_json = { workspace = true }
|
serde_json = { workspace = true }
|
||||||
tokio = { version = "1", features = ["rt", "rt-multi-thread", "sync", "time", "macros"] }
|
tokio = { version = "1", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "signal"] }
|
||||||
# The service entry point (SERVE-01), with flysim's own versions of each.
|
# The service entry point (SERVE-01), with flysim's own versions of each.
|
||||||
anyhow = "1.0"
|
anyhow = "1.0"
|
||||||
clap = { version = "4.5", features = ["derive"] }
|
clap = { version = "4.5", features = ["derive"] }
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,39 @@
|
||||||
|
//! `reward_bearing IN OUT`: a copy of a FLYSIM01 checkpoint with its adapter ledger thinned so the
|
||||||
|
//! real brain earns rewards where the fly already stands -- the current map unvisited (an `AREA`
|
||||||
|
//! payout on the first sample), its exits unfound (`boundary`), its ground unwalked
|
||||||
|
//! (`exploration`), no wild win a replay (`battle`). TASK-01's brain arm
|
||||||
|
//! (`tests/session_trace.rs`), as a file for SHADOW-01's rehearsal (`tools/shadow-rehearsal.sh`),
|
||||||
|
//! where the real service restores it. A test fixture, never a stream checkpoint.
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
let [input, output] = args.as_slice() else {
|
||||||
|
eprintln!("usage: reward_bearing IN OUT");
|
||||||
|
std::process::exit(2);
|
||||||
|
};
|
||||||
|
let bytes = std::fs::read(input).expect("the checkpoint reads");
|
||||||
|
let mut checkpoint = flysim::store::decode(&bytes).expect("FLYSIM01");
|
||||||
|
let reward = &mut checkpoint.runtime.reward;
|
||||||
|
let map = reward["location"]
|
||||||
|
.as_str()
|
||||||
|
.and_then(|l| l.split(':').next())
|
||||||
|
.unwrap_or("0")
|
||||||
|
.to_owned();
|
||||||
|
if let Some(seen) = reward["seen"].as_array_mut() {
|
||||||
|
seen.retain(|key| {
|
||||||
|
let key = key.as_str().unwrap_or("");
|
||||||
|
key != format!("map:{map}") && !key.starts_with(&format!("boundary:{map}:"))
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if let Some(tiles) = reward["tiles"].as_array_mut() {
|
||||||
|
tiles.retain(|tile| !tile.as_str().unwrap_or("").starts_with(&format!("{map}:")));
|
||||||
|
}
|
||||||
|
if let Some(counts) = reward["tileCounts"].as_object_mut() {
|
||||||
|
counts.remove(&map);
|
||||||
|
}
|
||||||
|
reward["wildWins"] = serde_json::json!({});
|
||||||
|
reward["replayBlocked"] = serde_json::json!([]);
|
||||||
|
let out = flysim::store::encode(&checkpoint.agent, &checkpoint.runtime).expect("encodes");
|
||||||
|
std::fs::write(output, out).expect("the copy writes");
|
||||||
|
eprintln!("thinned map {map}: {output}");
|
||||||
|
}
|
||||||
350
services/flysim/crates/fly-legacy-session/src/bin/fly-shadow.rs
Normal file
350
services/flysim/crates/fly-legacy-session/src/bin/fly-shadow.rs
Normal file
|
|
@ -0,0 +1,350 @@
|
||||||
|
//! `fly-shadow`: SHADOW-01, the session runtime run beside the live fly.
|
||||||
|
//!
|
||||||
|
//! ```text
|
||||||
|
//! fly-shadow run [options] follow the live trace, compare, write the verdict (the unit)
|
||||||
|
//! fly-shadow check [options] exit 0 only if the verdict allows the cutover (CUT-01's hook)
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! `run` reads the live service's own configuration the way flysim does (`/etc/fly/fly.env` through
|
||||||
|
//! the unit's `EnvironmentFile`, `FLY_STATE`, `FLY_STATE_HOT`, ...): the cartridge, the dataset, the
|
||||||
|
//! stores (read only), the macro mode, the speed and the metrics listener. Options:
|
||||||
|
//!
|
||||||
|
//! | Option | Default |
|
||||||
|
//! | --- | --- |
|
||||||
|
//! | `--trace-dir DIR` | `$FLY_TRACE_DIR` |
|
||||||
|
//! | `--out DIR` | `$FLY_SHADOW_DIR`: `verdict.json`, `divergence.json` |
|
||||||
|
//! | `--spool DIR` | `<out>/spool` |
|
||||||
|
//! | `--work DIR` | `$FLY_SHADOW_WORK`, else `<out>/work`: sockets and artifact stores |
|
||||||
|
//! | `--mode in-process\|thread\|process` | `in-process` |
|
||||||
|
//! | `--threads N` | `$FLY_SHADOW_THREADS`, else 2: the shadow agent's sweep threads |
|
||||||
|
//! | `--required-brain-seconds S` | 10800 |
|
||||||
|
//! | `--lag-guard-margin S` | 0.05 s/s; the shadow pauses 60 s while the live `fly_lag_seconds` grows faster than `fly-shadow-run`'s baseline rate (`<out>/baseline.json`) plus this margin (the baseline's own margin wins), and stops pausing for 10 minutes when a pause did not help (0 disables) |
|
||||||
|
//! | `--metrics HOST:PORT` | the live metrics listener |
|
||||||
|
//! | `--spool-max-mib N` | 512 |
|
||||||
|
//! | `--context N` | 30 transition pairs before a divergence |
|
||||||
|
//! | `--all-files` | follow every trace file present, oldest first (a rehearsal) |
|
||||||
|
//! | `--keep-traces` | keep compared trace files |
|
||||||
|
//! | `--keep-spool` | keep every spooled live checkpoint (a rehearsal replays them) |
|
||||||
|
//! | `--exit-on-pass` | exit once the verdict is `pass` |
|
||||||
|
//! | `--max-transitions N` | stop after N compared transitions |
|
||||||
|
//!
|
||||||
|
//! Exit status: 0 passed or stopped, 3 diverged, 2 the shadow's own error.
|
||||||
|
//!
|
||||||
|
//! `check --verdict FILE [--current DIR] [--binary NAME] [--compatibility STRING]
|
||||||
|
//! [--max-age-seconds N]`: the cutover rule of `fly_legacy_session::shadow::verdict`. `--current`
|
||||||
|
//! is the release link CUT-01 switches into (default `/opt/fly/current`): the verdict must be for
|
||||||
|
//! the directory it resolves to, with every shadowed binary unchanged there. `--binary` is the
|
||||||
|
//! file name of the session-runtime binary CUT-01 switches to (default `flysim-session`,
|
||||||
|
//! SERVE-01's service). `--compatibility` defaults to this build's legacy compatibility string.
|
||||||
|
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use fly_legacy_session::shadow::{self, LagGuard, ShadowConfig, StopFlag, verdict};
|
||||||
|
use fly_session::ExecutionMode;
|
||||||
|
|
||||||
|
fn usage() -> ! {
|
||||||
|
eprintln!("usage: fly-shadow run [options] | fly-shadow check --verdict FILE [options]");
|
||||||
|
std::process::exit(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn die(message: impl std::fmt::Display) -> ! {
|
||||||
|
eprintln!("fly-shadow: {message}");
|
||||||
|
std::process::exit(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Args(Vec<String>);
|
||||||
|
|
||||||
|
impl Args {
|
||||||
|
fn flag(&mut self, name: &str) -> bool {
|
||||||
|
match self.0.iter().position(|a| a == name) {
|
||||||
|
Some(i) => {
|
||||||
|
self.0.remove(i);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
None => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn value(&mut self, name: &str) -> Option<String> {
|
||||||
|
let i = self.0.iter().position(|a| a == name)?;
|
||||||
|
if i + 1 >= self.0.len() {
|
||||||
|
die(format!("{name} needs a value"));
|
||||||
|
}
|
||||||
|
let value = self.0.remove(i + 1);
|
||||||
|
self.0.remove(i);
|
||||||
|
Some(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parsed<T: std::str::FromStr>(&mut self, name: &str) -> Option<T> {
|
||||||
|
self.value(name).map(|v| {
|
||||||
|
v.parse()
|
||||||
|
.unwrap_or_else(|_| die(format!("{name}: cannot parse {v:?}")))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn done(self) {
|
||||||
|
if !self.0.is_empty() {
|
||||||
|
die(format!("unknown arguments: {:?}", self.0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn env_path(name: &str) -> Option<PathBuf> {
|
||||||
|
std::env::var_os(name)
|
||||||
|
.filter(|v| !v.is_empty())
|
||||||
|
.map(PathBuf::from)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn file_sha256(path: &std::path::Path) -> String {
|
||||||
|
let bytes = std::fs::read(path).unwrap_or_else(|e| die(format!("{}: {e}", path.display())));
|
||||||
|
shadow::sha256_hex(&bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn this_binary() -> PathBuf {
|
||||||
|
std::env::current_exe().unwrap_or_else(|e| die(format!("current_exe: {e}")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The release binaries a verdict vouches for: SERVE-01's service (`flysim-session`, what CUT-01
|
||||||
|
/// switches to), its worker program, the shadow itself, the legacy service and the edge.
|
||||||
|
const RELEASE_BINARIES: [&str; 5] = [
|
||||||
|
"flysim-session",
|
||||||
|
"fly-session",
|
||||||
|
"fly-shadow",
|
||||||
|
"flysim",
|
||||||
|
"fly-edge",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// SHA-256 of the release binaries in `dir`, by name.
|
||||||
|
fn binaries_in(dir: &std::path::Path) -> std::collections::BTreeMap<String, String> {
|
||||||
|
RELEASE_BINARIES
|
||||||
|
.iter()
|
||||||
|
.filter_map(|name| {
|
||||||
|
let path = dir.join(name);
|
||||||
|
path.is_file()
|
||||||
|
.then(|| ((*name).to_owned(), file_sha256(&path)))
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The resolved directory of this binary: the release it runs from.
|
||||||
|
fn this_release() -> PathBuf {
|
||||||
|
this_binary()
|
||||||
|
.parent()
|
||||||
|
.and_then(|d| d.canonicalize().ok())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let mut argv: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
if argv.is_empty() {
|
||||||
|
usage();
|
||||||
|
}
|
||||||
|
let command = argv.remove(0);
|
||||||
|
let mut args = Args(argv);
|
||||||
|
match command.as_str() {
|
||||||
|
"run" => run(args),
|
||||||
|
"check" => {
|
||||||
|
let verdict_path: PathBuf = args
|
||||||
|
.value("--verdict")
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.unwrap_or_else(|| usage());
|
||||||
|
// The release CUT-01 switches into (what `/opt/fly/current` resolves to now), and the
|
||||||
|
// binary in it that it switches to: SERVE-01's service.
|
||||||
|
let current = args
|
||||||
|
.value("--current")
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.unwrap_or_else(|| PathBuf::from("/opt/fly/current"));
|
||||||
|
let binary = args
|
||||||
|
.value("--binary")
|
||||||
|
.unwrap_or_else(|| "flysim-session".to_owned());
|
||||||
|
let compatibility = args.value("--compatibility");
|
||||||
|
let max_age: i64 = args.parsed("--max-age-seconds").unwrap_or(300);
|
||||||
|
args.done();
|
||||||
|
let compatibility = compatibility.unwrap_or_else(|| {
|
||||||
|
let config = flysim::config::Config::load(None).unwrap_or_else(|e| die(e));
|
||||||
|
flysim::simloop::compatibility_string(&config).unwrap_or_else(|e| die(e))
|
||||||
|
});
|
||||||
|
let text = std::fs::read_to_string(&verdict_path)
|
||||||
|
.unwrap_or_else(|e| die(format!("{}: {e}", verdict_path.display())));
|
||||||
|
let value: serde_json::Value =
|
||||||
|
serde_json::from_str(&text).unwrap_or_else(|e| die(format!("verdict: {e}")));
|
||||||
|
let now = verdict::parse_iso(&verdict::now_iso()).expect("now parses");
|
||||||
|
let dir = current
|
||||||
|
.canonicalize()
|
||||||
|
.unwrap_or_else(|e| die(format!("{}: {e}", current.display())));
|
||||||
|
let binaries = binaries_in(&dir);
|
||||||
|
let dir_text = dir.display().to_string();
|
||||||
|
let release = verdict::Release {
|
||||||
|
dir: &dir_text,
|
||||||
|
binaries: &binaries,
|
||||||
|
};
|
||||||
|
match verdict::allows_cutover(&value, &binary, &release, &compatibility, now, max_age) {
|
||||||
|
Ok(()) => println!("cutover allowed: {}", value["reason"]),
|
||||||
|
Err(reason) => {
|
||||||
|
println!("cutover refused: {reason}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => usage(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(mut args: Args) {
|
||||||
|
let config = flysim::config::Config::load(None).unwrap_or_else(|e| die(format!("{e:#}")));
|
||||||
|
let out_dir = args
|
||||||
|
.value("--out")
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.or_else(|| env_path("FLY_SHADOW_DIR"))
|
||||||
|
.unwrap_or_else(|| die("--out or FLY_SHADOW_DIR is required"));
|
||||||
|
let trace_dir = args
|
||||||
|
.value("--trace-dir")
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.or_else(|| env_path(flysim::trace::DIR_ENV))
|
||||||
|
.unwrap_or_else(|| die("--trace-dir or FLY_TRACE_DIR is required"));
|
||||||
|
let spool_dir = args
|
||||||
|
.value("--spool")
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.unwrap_or_else(|| out_dir.join("spool"));
|
||||||
|
let work_dir = args
|
||||||
|
.value("--work")
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.or_else(|| env_path("FLY_SHADOW_WORK"))
|
||||||
|
.unwrap_or_else(|| out_dir.join("work"));
|
||||||
|
let mode = match args.value("--mode").as_deref() {
|
||||||
|
None | Some("in-process") => ExecutionMode::InProcess,
|
||||||
|
Some("thread") => ExecutionMode::Thread,
|
||||||
|
Some("process") => ExecutionMode::Process,
|
||||||
|
Some(other) => die(format!("--mode {other:?}")),
|
||||||
|
};
|
||||||
|
let agent_threads: usize = args.parsed("--threads").unwrap_or_else(|| {
|
||||||
|
std::env::var("FLY_SHADOW_THREADS")
|
||||||
|
.ok()
|
||||||
|
.and_then(|v| v.parse().ok())
|
||||||
|
.unwrap_or(2)
|
||||||
|
});
|
||||||
|
let required: f64 = args
|
||||||
|
.parsed("--required-brain-seconds")
|
||||||
|
.unwrap_or(shadow::REQUIRED_BRAIN_SECONDS);
|
||||||
|
let lag_margin: f64 = args.parsed("--lag-guard-margin").unwrap_or(0.05);
|
||||||
|
let metrics = args.value("--metrics").or_else(|| {
|
||||||
|
config.control.metrics_bind.map(|addr| {
|
||||||
|
if addr.ip().is_unspecified() {
|
||||||
|
format!("127.0.0.1:{}", addr.port())
|
||||||
|
} else {
|
||||||
|
addr.to_string()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
});
|
||||||
|
let spool_mib: u64 = args.parsed("--spool-max-mib").unwrap_or(512);
|
||||||
|
let context_lines: usize = args.parsed("--context").unwrap_or(30);
|
||||||
|
let all_files = args.flag("--all-files");
|
||||||
|
let keep_traces = args.flag("--keep-traces");
|
||||||
|
let keep_spool = args.flag("--keep-spool");
|
||||||
|
let exit_on_pass = args.flag("--exit-on-pass");
|
||||||
|
let max_transitions: Option<u64> = args.parsed("--max-transitions");
|
||||||
|
// Undocumented: the toy connectome, for tests only.
|
||||||
|
let profile = match args.value("--profile") {
|
||||||
|
None => fly_session::legacy_agent::LegacyProfileKind::Production,
|
||||||
|
Some(p) => {
|
||||||
|
fly_session::legacy_agent::LegacyProfileKind::parse(&p).unwrap_or_else(|e| die(e))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
args.done();
|
||||||
|
|
||||||
|
if config.loop_.game != "pokemon-red" {
|
||||||
|
die(format!(
|
||||||
|
"the legacy composition is Pokémon Red, not {:?}",
|
||||||
|
config.loop_.game
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if u64::from(config.feed.audio_hz) != fly_session::legacy_env::DEFAULT_AUDIO_RATE {
|
||||||
|
die(format!(
|
||||||
|
"the live service's audio rate {} is not the legacy environment's {}",
|
||||||
|
config.feed.audio_hz,
|
||||||
|
fly_session::legacy_env::DEFAULT_AUDIO_RATE
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let baseline_file = out_dir.join("baseline.json");
|
||||||
|
let lag_guard = (lag_margin > 0.0)
|
||||||
|
.then_some(())
|
||||||
|
.and(metrics)
|
||||||
|
.map(|metrics_addr| LagGuard {
|
||||||
|
metrics_addr,
|
||||||
|
baseline_file: Some(baseline_file),
|
||||||
|
margin: lag_margin,
|
||||||
|
window: Duration::from_secs(60),
|
||||||
|
back_off: Duration::from_secs(60),
|
||||||
|
suppress: Duration::from_secs(600),
|
||||||
|
});
|
||||||
|
let shadow_config = ShadowConfig {
|
||||||
|
trace_dir,
|
||||||
|
hot_dir: config.paths.hot_dir.clone(),
|
||||||
|
durable_dir: config.paths.save_dir.clone(),
|
||||||
|
out_dir,
|
||||||
|
spool_dir,
|
||||||
|
work_dir,
|
||||||
|
rom_path: config.paths.rom.clone(),
|
||||||
|
dataset_dir: config.paths.dataset.clone(),
|
||||||
|
profile,
|
||||||
|
macro_mode: config.macros.mode,
|
||||||
|
speed: config.loop_.speed,
|
||||||
|
mode,
|
||||||
|
agent_threads,
|
||||||
|
required_brain_seconds: required,
|
||||||
|
all_files,
|
||||||
|
keep_traces,
|
||||||
|
keep_spool,
|
||||||
|
exit_on_pass,
|
||||||
|
max_transitions,
|
||||||
|
spool_max_bytes: spool_mib << 20,
|
||||||
|
context_lines,
|
||||||
|
poll: Duration::from_millis(100),
|
||||||
|
lag_guard,
|
||||||
|
binary_sha256: file_sha256(&this_binary()),
|
||||||
|
binaries: binaries_in(&this_release()),
|
||||||
|
release: this_release().display().to_string(),
|
||||||
|
};
|
||||||
|
eprintln!(
|
||||||
|
"fly-shadow: {} mode, {} threads, following {} (stores {} and {}, read only)",
|
||||||
|
mode.label(),
|
||||||
|
agent_threads,
|
||||||
|
shadow_config.trace_dir.display(),
|
||||||
|
shadow_config.hot_dir.display(),
|
||||||
|
shadow_config.durable_dir.display()
|
||||||
|
);
|
||||||
|
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||||
|
.worker_threads(2)
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.unwrap_or_else(|e| die(format!("tokio: {e}")));
|
||||||
|
let stop = StopFlag::default();
|
||||||
|
let ended = runtime.block_on(async {
|
||||||
|
let signals = stop.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
use tokio::signal::unix::{SignalKind, signal};
|
||||||
|
let mut term = signal(SignalKind::terminate()).expect("SIGTERM");
|
||||||
|
let mut int = signal(SignalKind::interrupt()).expect("SIGINT");
|
||||||
|
tokio::select! {
|
||||||
|
_ = term.recv() => {}
|
||||||
|
_ = int.recv() => {}
|
||||||
|
}
|
||||||
|
eprintln!("fly-shadow: stopping");
|
||||||
|
signals.request();
|
||||||
|
});
|
||||||
|
shadow::run(shadow_config, stop).await
|
||||||
|
});
|
||||||
|
match ended {
|
||||||
|
Ok((shadow::Ended::Diverged, _)) => std::process::exit(3),
|
||||||
|
Ok((ended, verdict)) => {
|
||||||
|
eprintln!(
|
||||||
|
"fly-shadow: {ended:?}; {} transitions ({:.1} brain s) identical, verdict {}",
|
||||||
|
verdict.agreement.transitions,
|
||||||
|
verdict.brain_seconds(),
|
||||||
|
verdict.status.as_str()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Err(e) => die(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -9,6 +9,8 @@
|
||||||
//! - [`driver`]: a stub readout for parity runs that must earn rewards.
|
//! - [`driver`]: a stub readout for parity runs that must earn rewards.
|
||||||
//! - [`service`]: the composition as the live service behind flysim's listeners (SERVE-01),
|
//! - [`service`]: the composition as the live service behind flysim's listeners (SERVE-01),
|
||||||
//! the `flysim-session` binary.
|
//! the `flysim-session` binary.
|
||||||
|
//! - [`shadow`]: SHADOW-01, the session runtime following the live fly's trace, the comparator and
|
||||||
|
//! the verdict CUT-01 reads.
|
||||||
//!
|
//!
|
||||||
//! `docs/design/session-framework/legacy-gameboy-v1.md` is the contract, `implementation.md`
|
//! `docs/design/session-framework/legacy-gameboy-v1.md` is the contract, `implementation.md`
|
||||||
//! TASK-01 the record.
|
//! TASK-01 the record.
|
||||||
|
|
@ -18,5 +20,6 @@ pub mod composition;
|
||||||
pub mod driver;
|
pub mod driver;
|
||||||
pub mod import;
|
pub mod import;
|
||||||
pub mod service;
|
pub mod service;
|
||||||
|
pub mod shadow;
|
||||||
pub mod task;
|
pub mod task;
|
||||||
pub mod trace;
|
pub mod trace;
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,169 @@
|
||||||
|
//! Checkpoint bytes at a live save: the shadow's own export of the same boundary, byte for byte
|
||||||
|
//! against the file the live service wrote, after the named substitutions.
|
||||||
|
//!
|
||||||
|
//! The shadow never writes to the live stores. At a boundary where the live trace records a
|
||||||
|
//! capture `g<N>`, the shadow takes its own participant-coherent capture of that boundary (in the
|
||||||
|
//! position the live one had: before or after that boundary's rollback), exports it as FLYSIM01
|
||||||
|
//! through the one encoder both runtimes share (STATE-02), and compares the bytes with the live
|
||||||
|
//! file. The host fields the shadow cannot own are the live file's: `generation`, `wallMs` and
|
||||||
|
//! `lastEventId` (declared `host-fields`). `compatibility` and `speed` are the shadow's own
|
||||||
|
//! configuration and `rankSinceMs` its own rank tracking, so a difference in any of them is a
|
||||||
|
//! divergence. A legacy milestone archive taken before that boundary's slot save
|
||||||
|
//! (`afterActions` 0 ahead of a `save-slot`) holds the pre-capture ratchet and slot: the live
|
||||||
|
//! file's `ratchet`, `ratchetGame` and `ratchetFrame` stand in for the shadow's there (declared
|
||||||
|
//! `archive-order`) and everything else must still be identical.
|
||||||
|
|
||||||
|
use fly_session::legacy_checkpoint::{self, HostHalf, TaskHalf};
|
||||||
|
use fly_session::types::id;
|
||||||
|
use flysim::store;
|
||||||
|
|
||||||
|
/// The shadow's capture of one boundary.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct ShadowCapture {
|
||||||
|
pub boundary: u64,
|
||||||
|
pub world_payload: Vec<u8>,
|
||||||
|
pub agent_payload: Vec<u8>,
|
||||||
|
pub task: TaskHalf,
|
||||||
|
/// The shadow's `rankSinceMs` at the capture.
|
||||||
|
pub rank_since_ms: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Outcome {
|
||||||
|
Identical,
|
||||||
|
/// Identical after a declared difference.
|
||||||
|
Declared,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A checkpoint that differs: the explanation and the shadow's export, kept for the review.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Mismatch {
|
||||||
|
pub detail: String,
|
||||||
|
pub shadow_bytes: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compares the live file's bytes with the shadow's export of the same boundary.
|
||||||
|
pub fn compare(
|
||||||
|
live: &[u8],
|
||||||
|
capture: &ShadowCapture,
|
||||||
|
compatibility: &str,
|
||||||
|
speed: f64,
|
||||||
|
archive_order: bool,
|
||||||
|
) -> Result<Outcome, Box<Mismatch>> {
|
||||||
|
let fail = |detail: String| {
|
||||||
|
Box::new(Mismatch {
|
||||||
|
detail,
|
||||||
|
shadow_bytes: Vec::new(),
|
||||||
|
})
|
||||||
|
};
|
||||||
|
let live_checkpoint = store::decode(live).map_err(|e| fail(format!("the live file: {e:#}")))?;
|
||||||
|
let host = HostHalf {
|
||||||
|
generation: live_checkpoint.runtime.generation,
|
||||||
|
wall_ms: live_checkpoint.runtime.wall_ms,
|
||||||
|
compatibility: compatibility.to_owned(),
|
||||||
|
speed,
|
||||||
|
rank_since_ms: capture.rank_since_ms,
|
||||||
|
last_event_id: live_checkpoint.runtime.last_event_id,
|
||||||
|
};
|
||||||
|
let mut bytes = legacy_checkpoint::export(
|
||||||
|
&capture.agent_payload,
|
||||||
|
&capture.world_payload,
|
||||||
|
&id(crate::task::SLOT),
|
||||||
|
&capture.task,
|
||||||
|
&host,
|
||||||
|
)
|
||||||
|
.map_err(fail)?;
|
||||||
|
if archive_order {
|
||||||
|
let mut shadow =
|
||||||
|
store::decode(&bytes).map_err(|e| fail(format!("the shadow export: {e:#}")))?;
|
||||||
|
shadow.runtime.ratchet = live_checkpoint.runtime.ratchet;
|
||||||
|
shadow.runtime.ratchet_game = live_checkpoint.runtime.ratchet_game.clone();
|
||||||
|
shadow.runtime.ratchet_frame = live_checkpoint.runtime.ratchet_frame.clone();
|
||||||
|
bytes =
|
||||||
|
store::encode(&shadow.agent, &shadow.runtime).map_err(|e| fail(format!("{e:#}")))?;
|
||||||
|
}
|
||||||
|
if bytes == live {
|
||||||
|
return Ok(if archive_order {
|
||||||
|
Outcome::Declared
|
||||||
|
} else {
|
||||||
|
Outcome::Identical
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Err(Box::new(Mismatch {
|
||||||
|
detail: explain(&live_checkpoint, &bytes),
|
||||||
|
shadow_bytes: bytes,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Which members differ, for the divergence report.
|
||||||
|
fn explain(live: &store::Checkpoint, shadow_bytes: &[u8]) -> String {
|
||||||
|
let shadow = match store::decode(shadow_bytes) {
|
||||||
|
Ok(shadow) => shadow,
|
||||||
|
Err(e) => return format!("the shadow export does not decode: {e:#}"),
|
||||||
|
};
|
||||||
|
let (l, s) = (&live.runtime, &shadow.runtime);
|
||||||
|
let mut fields = Vec::new();
|
||||||
|
macro_rules! field {
|
||||||
|
($name:literal, $a:expr, $b:expr) => {
|
||||||
|
if $a != $b {
|
||||||
|
fields.push($name);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
field!("romSha256", l.rom_sha256, s.rom_sha256);
|
||||||
|
field!("emulatorFrame", l.emulator_frame, s.emulator_frame);
|
||||||
|
field!("compatibility", l.compatibility, s.compatibility);
|
||||||
|
field!("speed", l.speed, s.speed);
|
||||||
|
field!("buttons", l.buttons, s.buttons);
|
||||||
|
field!("rankSinceMs", l.rank_since_ms, s.rank_since_ms);
|
||||||
|
field!("reward", l.reward, s.reward);
|
||||||
|
field!("ratchet", l.ratchet, s.ratchet);
|
||||||
|
field!("reinforcements", l.reinforcements, s.reinforcements);
|
||||||
|
field!("emulator", l.emulator, s.emulator);
|
||||||
|
field!("framebuffer", l.framebuffer, s.framebuffer);
|
||||||
|
field!("ratchetGame", l.ratchet_game, s.ratchet_game);
|
||||||
|
field!("ratchetFrame", l.ratchet_frame, s.ratchet_frame);
|
||||||
|
let agent_same = store::encode(&shadow.agent, &live.runtime)
|
||||||
|
.ok()
|
||||||
|
.zip(store::encode(&live.agent, &live.runtime).ok())
|
||||||
|
.is_some_and(|(a, b)| a == b);
|
||||||
|
if !agent_same {
|
||||||
|
fields.push("agent");
|
||||||
|
}
|
||||||
|
let mut detail = format!(
|
||||||
|
"generation {}: the shadow's export differs from the live file in {}",
|
||||||
|
live.runtime.generation,
|
||||||
|
if fields.is_empty() {
|
||||||
|
"the encoding only".to_owned()
|
||||||
|
} else {
|
||||||
|
fields.join(", ")
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if fields.contains(&"rankSinceMs") {
|
||||||
|
detail.push_str(&format!(
|
||||||
|
" (rankSinceMs live {} shadow {})",
|
||||||
|
l.rank_since_ms, s.rank_since_ms
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if fields.contains(&"emulator") {
|
||||||
|
let first = l.emulator.iter().zip(&s.emulator).position(|(a, b)| a != b);
|
||||||
|
let count = l
|
||||||
|
.emulator
|
||||||
|
.iter()
|
||||||
|
.zip(&s.emulator)
|
||||||
|
.filter(|(a, b)| a != b)
|
||||||
|
.count();
|
||||||
|
detail.push_str(&format!(
|
||||||
|
" (emulator: {} vs {} bytes, {count} differ, first at {first:?})",
|
||||||
|
l.emulator.len(),
|
||||||
|
s.emulator.len()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if fields.contains(&"ratchet") {
|
||||||
|
detail.push_str(&format!(
|
||||||
|
" (ratchet live {:?} shadow {:?})",
|
||||||
|
l.ratchet, s.ratchet
|
||||||
|
));
|
||||||
|
}
|
||||||
|
detail
|
||||||
|
}
|
||||||
154
services/flysim/crates/fly-legacy-session/src/shadow/follow.rs
Normal file
154
services/flysim/crates/fly-legacy-session/src/shadow/follow.rs
Normal file
|
|
@ -0,0 +1,154 @@
|
||||||
|
//! Following the live service's `FLY_TRACE_DIR`: one file per flysim process, named
|
||||||
|
//! `trace-<start wall ms>-<pid>.jsonl`, so the names sort in start order. A file is a *segment*:
|
||||||
|
//! the process that wrote it restored one checkpoint (its startup save names it), ran, and ended
|
||||||
|
//! where the next file begins.
|
||||||
|
//!
|
||||||
|
//! The live recorder buffers about a megabyte, so lines arrive in bursts some seconds late and the
|
||||||
|
//! last line of a file may be incomplete until the next burst. A reader therefore hands out only
|
||||||
|
//! complete lines. A file has ended when it has no more complete lines *and* a newer file exists:
|
||||||
|
//! systemd starts the next process only after the previous one exited, and a process flushes its
|
||||||
|
//! trace on the way out. A process killed hard loses its unflushed tail; those transitions are
|
||||||
|
//! simply not compared.
|
||||||
|
|
||||||
|
use std::fs::File;
|
||||||
|
use std::io::{BufRead, BufReader};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
/// The trace files in `dir`, in start order.
|
||||||
|
pub fn trace_files(dir: &Path) -> std::io::Result<Vec<PathBuf>> {
|
||||||
|
let mut files: Vec<PathBuf> = std::fs::read_dir(dir)?
|
||||||
|
.filter_map(|entry| entry.ok().map(|e| e.path()))
|
||||||
|
.filter(|path| {
|
||||||
|
path.file_name()
|
||||||
|
.and_then(|n| n.to_str())
|
||||||
|
.is_some_and(|n| n.starts_with("trace-") && n.ends_with(".jsonl"))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
files.sort();
|
||||||
|
Ok(files)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first trace file in `dir` that sorts after `after` (or the first of all).
|
||||||
|
pub fn next_file(dir: &Path, after: Option<&Path>) -> std::io::Result<Option<PathBuf>> {
|
||||||
|
Ok(trace_files(dir)?
|
||||||
|
.into_iter()
|
||||||
|
.find(|path| after.is_none_or(|after| path.file_name() > after.file_name())))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a file newer than `path` exists in its directory.
|
||||||
|
pub fn superseded(path: &Path) -> bool {
|
||||||
|
let Some(dir) = path.parent() else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
matches!(next_file(dir, Some(path)), Ok(Some(_)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// About how many live transitions are written but not yet compared: the bytes beyond `consumed`
|
||||||
|
/// in `path` and every byte of the newer files, over the mean line length read so far.
|
||||||
|
pub fn backlog(path: &Path, consumed: u64, lines: u64) -> u64 {
|
||||||
|
if lines == 0 {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
let mean = (consumed / lines).max(1);
|
||||||
|
let here = std::fs::metadata(path)
|
||||||
|
.map(|m| m.len())
|
||||||
|
.unwrap_or(consumed)
|
||||||
|
.saturating_sub(consumed);
|
||||||
|
let newer: u64 = path
|
||||||
|
.parent()
|
||||||
|
.and_then(|dir| trace_files(dir).ok())
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.filter(|p| p.file_name() > path.file_name())
|
||||||
|
.filter_map(|p| std::fs::metadata(p).ok().map(|m| m.len()))
|
||||||
|
.sum();
|
||||||
|
(here + newer) / mean
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A reader of one growing file that returns complete lines only.
|
||||||
|
pub struct Follower {
|
||||||
|
path: PathBuf,
|
||||||
|
reader: BufReader<File>,
|
||||||
|
partial: Vec<u8>,
|
||||||
|
pub lines: u64,
|
||||||
|
/// Bytes of complete lines handed out.
|
||||||
|
pub consumed: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Follower {
|
||||||
|
pub fn open(path: &Path) -> std::io::Result<Follower> {
|
||||||
|
Ok(Follower {
|
||||||
|
path: path.to_owned(),
|
||||||
|
reader: BufReader::with_capacity(1 << 20, File::open(path)?),
|
||||||
|
partial: Vec::new(),
|
||||||
|
lines: 0,
|
||||||
|
consumed: 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn path(&self) -> &Path {
|
||||||
|
&self.path
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The next complete line, if one has been written; `None` when the reader is at the end of
|
||||||
|
/// what exists so far (an incomplete last line is kept for the next call).
|
||||||
|
pub fn next_line(&mut self) -> std::io::Result<Option<String>> {
|
||||||
|
let read = self.reader.read_until(b'\n', &mut self.partial)?;
|
||||||
|
if read == 0 || self.partial.last() != Some(&b'\n') {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
self.consumed += self.partial.len() as u64;
|
||||||
|
self.partial.pop();
|
||||||
|
let line = String::from_utf8(std::mem::take(&mut self.partial))
|
||||||
|
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
|
||||||
|
self.lines += 1;
|
||||||
|
Ok(Some(line))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bytes of an incomplete last line held back.
|
||||||
|
pub fn pending_bytes(&self) -> usize {
|
||||||
|
self.partial.len()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::io::Write;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn complete_lines_only_and_files_in_start_order() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let a = dir.path().join("trace-0000000000100-7.jsonl");
|
||||||
|
let b = dir.path().join("trace-0000000000200-9.jsonl");
|
||||||
|
std::fs::write(dir.path().join("other.txt"), b"x").unwrap();
|
||||||
|
let mut file = File::create(&a).unwrap();
|
||||||
|
file.write_all(b"{\"format\":1}\n{\"half").unwrap();
|
||||||
|
file.flush().unwrap();
|
||||||
|
let mut follower = Follower::open(&a).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
follower.next_line().unwrap().as_deref(),
|
||||||
|
Some("{\"format\":1}")
|
||||||
|
);
|
||||||
|
assert_eq!(follower.next_line().unwrap(), None);
|
||||||
|
assert_eq!(follower.pending_bytes(), 6);
|
||||||
|
assert!(!superseded(&a));
|
||||||
|
file.write_all(b"\":2}\n").unwrap();
|
||||||
|
file.flush().unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
follower.next_line().unwrap().as_deref(),
|
||||||
|
Some("{\"half\":2}")
|
||||||
|
);
|
||||||
|
assert_eq!(follower.next_line().unwrap(), None);
|
||||||
|
std::fs::write(&b, b"").unwrap();
|
||||||
|
assert!(superseded(&a));
|
||||||
|
assert!(!superseded(&b));
|
||||||
|
assert_eq!(trace_files(dir.path()).unwrap(), vec![a.clone(), b.clone()]);
|
||||||
|
assert_eq!(next_file(dir.path(), None).unwrap(), Some(a.clone()));
|
||||||
|
assert_eq!(next_file(dir.path(), Some(&a)).unwrap(), Some(b.clone()));
|
||||||
|
assert_eq!(next_file(dir.path(), Some(&b)).unwrap(), None);
|
||||||
|
// The backlog counts what is left here and everything in newer files.
|
||||||
|
std::fs::write(&b, b"01234567890\n01234567890\n").unwrap();
|
||||||
|
assert_eq!(backlog(&a, follower.consumed, follower.lines), 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
1401
services/flysim/crates/fly-legacy-session/src/shadow/mod.rs
Normal file
1401
services/flysim/crates/fly-legacy-session/src/shadow/mod.rs
Normal file
File diff suppressed because it is too large
Load diff
251
services/flysim/crates/fly-legacy-session/src/shadow/spool.rs
Normal file
251
services/flysim/crates/fly-legacy-session/src/shadow/spool.rs
Normal file
|
|
@ -0,0 +1,251 @@
|
||||||
|
//! The spool: copies of the live stores' checkpoint generations, taken as they appear.
|
||||||
|
//!
|
||||||
|
//! The live service keeps two generations per store (`keep_generations`) and writes a hot one
|
||||||
|
//! every five seconds, so a hot file lives about ten seconds, while the trace line that names it
|
||||||
|
//! arrives some seconds after the capture (the recorder buffers) and the shadow may be further
|
||||||
|
//! behind still. The spool thread therefore polls both store directories and copies every new
|
||||||
|
//! `<gen>.checkpoint` into the spool at once. Store commits write `<gen>.checkpoint.tmp` and rename
|
||||||
|
//! it, so a file under its final name is complete; one rotated away mid-copy is skipped.
|
||||||
|
//!
|
||||||
|
//! The spool is bounded: generations below the shadow's floor (already compared, or of a finished
|
||||||
|
//! segment) are deleted, and above `max_bytes` the oldest pending ones go first; a capture whose
|
||||||
|
//! file is gone is reported as unavailable, never as a divergence. The spool only reads the live
|
||||||
|
//! stores; it never writes, renames or deletes anything in them.
|
||||||
|
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||||
|
use std::time::{Duration, SystemTime};
|
||||||
|
|
||||||
|
/// The generation of a store file name, `<gen>.checkpoint`.
|
||||||
|
pub fn generation_of(name: &str) -> Option<u64> {
|
||||||
|
name.strip_suffix(".checkpoint")?.parse().ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spool_name(generation: u64) -> String {
|
||||||
|
format!("g{generation}.checkpoint")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shared between the copying thread and the shadow.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Spool {
|
||||||
|
dir: PathBuf,
|
||||||
|
sources: Vec<PathBuf>,
|
||||||
|
max_bytes: u64,
|
||||||
|
floor: Arc<AtomicU64>,
|
||||||
|
stop: Arc<AtomicBool>,
|
||||||
|
evicted: Arc<AtomicU64>,
|
||||||
|
/// Keep every copy (a rehearsal that replays the run again afterwards): no floor, no bound.
|
||||||
|
keep: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Spool {
|
||||||
|
pub fn new(dir: &Path, sources: Vec<PathBuf>, max_bytes: u64) -> std::io::Result<Spool> {
|
||||||
|
std::fs::create_dir_all(dir)?;
|
||||||
|
Ok(Spool {
|
||||||
|
dir: dir.to_owned(),
|
||||||
|
sources,
|
||||||
|
max_bytes,
|
||||||
|
floor: Arc::new(AtomicU64::new(0)),
|
||||||
|
stop: Arc::new(AtomicBool::new(false)),
|
||||||
|
evicted: Arc::new(AtomicU64::new(0)),
|
||||||
|
keep: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keep every copy: the floor and the byte bound delete nothing.
|
||||||
|
pub fn keep_all(mut self) -> Spool {
|
||||||
|
self.keep = true;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generations below `floor` are no longer needed.
|
||||||
|
pub fn set_floor(&self, floor: u64) {
|
||||||
|
self.floor.fetch_max(floor, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pending generations dropped for space.
|
||||||
|
pub fn evicted(&self) -> u64 {
|
||||||
|
self.evicted.load(Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where generation `generation` can be read: the spool's copy, else a live store's file.
|
||||||
|
pub fn path(&self, generation: u64) -> Option<PathBuf> {
|
||||||
|
let spooled = self.dir.join(spool_name(generation));
|
||||||
|
if spooled.is_file() {
|
||||||
|
return Some(spooled);
|
||||||
|
}
|
||||||
|
self.sources
|
||||||
|
.iter()
|
||||||
|
.map(|dir| dir.join(format!("{generation}.checkpoint")))
|
||||||
|
.find(|path| path.is_file())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads generation `generation`, from the spool or a live store (a file rotated away between
|
||||||
|
/// the lookup and the read is `None`).
|
||||||
|
pub fn read(&self, generation: u64) -> Option<Vec<u8>> {
|
||||||
|
let spooled = self.dir.join(spool_name(generation));
|
||||||
|
if let Ok(bytes) = std::fs::read(&spooled) {
|
||||||
|
return Some(bytes);
|
||||||
|
}
|
||||||
|
self.sources
|
||||||
|
.iter()
|
||||||
|
.find_map(|dir| std::fs::read(dir.join(format!("{generation}.checkpoint"))).ok())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stop(&self) {
|
||||||
|
self.stop.store(true, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts the copying thread. The first scan copies only files modified within `window`
|
||||||
|
/// (the stores' permanent milestone archives are old and not needed); later scans copy every
|
||||||
|
/// new generation.
|
||||||
|
pub fn spawn(&self, period: Duration, window: Duration) -> std::thread::JoinHandle<()> {
|
||||||
|
let spool = self.clone();
|
||||||
|
std::thread::Builder::new()
|
||||||
|
.name("fly-shadow-spool".to_owned())
|
||||||
|
.spawn(move || {
|
||||||
|
let mut state = ScanState::default();
|
||||||
|
let mut first = true;
|
||||||
|
while !spool.stop.load(Ordering::Relaxed) {
|
||||||
|
spool.scan(&mut state, first.then_some(window));
|
||||||
|
first = false;
|
||||||
|
std::thread::sleep(period);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.expect("the spool thread starts")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One pass: copy what is new, delete what is below the floor, keep within the byte bound.
|
||||||
|
pub fn scan(&self, state: &mut ScanState, only_newer_than: Option<Duration>) {
|
||||||
|
let floor = self.floor.load(Ordering::Relaxed);
|
||||||
|
let now = SystemTime::now();
|
||||||
|
for source in &self.sources {
|
||||||
|
let Ok(entries) = std::fs::read_dir(source) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let name = entry.file_name();
|
||||||
|
let Some(generation) = name.to_str().and_then(generation_of) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if (generation < floor && !self.keep) || state.seen.contains(&generation) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Some(window) = only_newer_than {
|
||||||
|
let recent = entry
|
||||||
|
.metadata()
|
||||||
|
.and_then(|m| m.modified())
|
||||||
|
.ok()
|
||||||
|
.and_then(|t| now.duration_since(t).ok())
|
||||||
|
.is_some_and(|age| age <= window);
|
||||||
|
if !recent {
|
||||||
|
state.seen.insert(generation);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let target = self.dir.join(spool_name(generation));
|
||||||
|
let tmp = self.dir.join(format!("{}.tmp", spool_name(generation)));
|
||||||
|
match std::fs::copy(entry.path(), &tmp) {
|
||||||
|
Ok(bytes) => {
|
||||||
|
if std::fs::rename(&tmp, &target).is_ok() {
|
||||||
|
state.held.insert(generation, bytes);
|
||||||
|
}
|
||||||
|
state.seen.insert(generation);
|
||||||
|
}
|
||||||
|
// Rotated away mid-copy: gone for good; the next scan will not see it either.
|
||||||
|
Err(_) => {
|
||||||
|
let _ = std::fs::remove_file(&tmp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.keep {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let below: Vec<u64> = state.held.range(..floor).map(|(g, _)| *g).collect();
|
||||||
|
for generation in below {
|
||||||
|
let _ = std::fs::remove_file(self.dir.join(spool_name(generation)));
|
||||||
|
state.held.remove(&generation);
|
||||||
|
}
|
||||||
|
while state.held.values().sum::<u64>() > self.max_bytes {
|
||||||
|
let Some((&generation, _)) = state.held.iter().next() else {
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
let _ = std::fs::remove_file(self.dir.join(spool_name(generation)));
|
||||||
|
state.held.remove(&generation);
|
||||||
|
self.evicted.fetch_add(1, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes every spooled file (the shadow is done).
|
||||||
|
pub fn clear(&self) {
|
||||||
|
if self.keep {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if let Ok(entries) = std::fs::read_dir(&self.dir) {
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let name = entry.file_name();
|
||||||
|
if name
|
||||||
|
.to_str()
|
||||||
|
.is_some_and(|n| n.starts_with('g') && n.contains(".checkpoint"))
|
||||||
|
{
|
||||||
|
let _ = std::fs::remove_file(entry.path());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What one spool thread has copied and seen.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct ScanState {
|
||||||
|
seen: BTreeSet<u64>,
|
||||||
|
held: BTreeMap<u64, u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn copies_new_generations_releases_below_the_floor_and_stays_bounded() {
|
||||||
|
let live = tempfile::tempdir().unwrap();
|
||||||
|
let hot = live.path().join("hot");
|
||||||
|
let durable = live.path().join("durable");
|
||||||
|
std::fs::create_dir_all(&hot).unwrap();
|
||||||
|
std::fs::create_dir_all(&durable).unwrap();
|
||||||
|
let spool_dir = live.path().join("spool");
|
||||||
|
let spool = Spool::new(&spool_dir, vec![hot.clone(), durable.clone()], 25).unwrap();
|
||||||
|
std::fs::write(hot.join("5.checkpoint"), [1u8; 10]).unwrap();
|
||||||
|
std::fs::write(durable.join("6.checkpoint"), [2u8; 10]).unwrap();
|
||||||
|
std::fs::write(durable.join("manifest.json"), b"{}").unwrap();
|
||||||
|
std::fs::write(hot.join("7.checkpoint.tmp"), [3u8; 10]).unwrap();
|
||||||
|
let mut state = ScanState::default();
|
||||||
|
spool.scan(&mut state, Some(Duration::from_secs(3600)));
|
||||||
|
assert!(spool_dir.join("g5.checkpoint").is_file());
|
||||||
|
assert!(spool_dir.join("g6.checkpoint").is_file());
|
||||||
|
assert!(!spool_dir.join("g7.checkpoint").exists());
|
||||||
|
// The live store rotates 5 away: the spool still has it.
|
||||||
|
std::fs::remove_file(hot.join("5.checkpoint")).unwrap();
|
||||||
|
assert_eq!(spool.read(5), Some(vec![1u8; 10]));
|
||||||
|
// A third file overflows the 25-byte bound: the oldest pending goes.
|
||||||
|
std::fs::write(hot.join("8.checkpoint"), [4u8; 10]).unwrap();
|
||||||
|
spool.scan(&mut state, None);
|
||||||
|
assert_eq!(spool.evicted(), 1);
|
||||||
|
assert_eq!(spool.read(5), None);
|
||||||
|
assert!(spool.path(8).is_some());
|
||||||
|
// Below the floor is released.
|
||||||
|
spool.set_floor(8);
|
||||||
|
spool.scan(&mut state, None);
|
||||||
|
assert!(!spool_dir.join("g6.checkpoint").exists());
|
||||||
|
// Still readable from the live store while it is there.
|
||||||
|
assert_eq!(spool.read(6), Some(vec![2u8; 10]));
|
||||||
|
// The live stores were never touched.
|
||||||
|
assert!(durable.join("manifest.json").is_file());
|
||||||
|
assert!(hot.join("8.checkpoint").is_file());
|
||||||
|
spool.clear();
|
||||||
|
assert!(!spool_dir.join("g8.checkpoint").exists());
|
||||||
|
}
|
||||||
|
}
|
||||||
601
services/flysim/crates/fly-legacy-session/src/shadow/verdict.rs
Normal file
601
services/flysim/crates/fly-legacy-session/src/shadow/verdict.rs
Normal file
|
|
@ -0,0 +1,601 @@
|
||||||
|
//! The verdict file, `fly-shadow-verdict-v1`: the contract CUT-01's automatic cutover reads.
|
||||||
|
//!
|
||||||
|
//! The shadow rewrites `verdict.json` in its output directory atomically (temporary file, rename)
|
||||||
|
//! every few seconds and at every change of status. The fields CUT-01 relies on:
|
||||||
|
//!
|
||||||
|
//! | Field | Meaning |
|
||||||
|
//! | --- | --- |
|
||||||
|
//! | `format` | `fly-shadow-verdict-v1` |
|
||||||
|
//! | `status` | `running`, `pass`, `diverged`, `stopped` or `error` |
|
||||||
|
//! | `candidate` | what was shadowed: `binarySha256` of the shadow binary; `binaries`, the SHA-256 of every release binary beside it by name (`fly-shadow`, `fly-session`, `flysim`, `fly-edge`: the session-runtime service CUT-01 switches to is built from the same tree in the same release); `release`, that directory; `compatibility` and its `compatibilitySha256`; `executionMode`; `agentThreads` |
|
||||||
|
//! | `required.brainSeconds` | the window the decision names: 10,800 s (3 h) of live brain time |
|
||||||
|
//! | `compared.brainSeconds`, `compared.transitions` | how much of the live fly was compared, transition by transition, with zero divergence |
|
||||||
|
//! | `passedAt` | when `compared.brainSeconds` first reached `required.brainSeconds` with no divergence |
|
||||||
|
//! | `firstDivergence` | `null`, or the first difference with its context (also `divergence.json`) |
|
||||||
|
//! | `declaredDifferences` | the named exclusions the comparison applied |
|
||||||
|
//!
|
||||||
|
//! `pass` is sticky only while nothing diverges: a shadow that keeps running after it passed and
|
||||||
|
//! then finds a difference turns the verdict to `diverged`. `stopped` is a shadow that exited
|
||||||
|
//! before it passed (a `pass` stays `pass` when the shadow stops). `error` is the shadow's own
|
||||||
|
//! failure (it could not read its inputs), which proves nothing either way.
|
||||||
|
//!
|
||||||
|
//! **The cutover rule (for CUT-01), [`allows_cutover`].** Cut over only if, read at the moment of
|
||||||
|
//! cutting over, every one of these holds; anything else keeps the legacy fly:
|
||||||
|
//!
|
||||||
|
//! - `format` is `fly-shadow-verdict-v1`, `status` is `pass`, `firstDivergence` is `null`, and
|
||||||
|
//! `compared.brainSeconds` reaches `required.brainSeconds` and never less than the operator's
|
||||||
|
//! 10,800 s (`REQUIRED_BRAIN_SECONDS`), whatever window the shadow was run with;
|
||||||
|
//! - *the release*: `candidate.release` is the directory `/opt/fly/current` resolves to now,
|
||||||
|
//! every binary in `candidate.binaries` still has its recorded SHA-256 there, and the binary
|
||||||
|
//! being switched to (`flysim-session`, SERVE-01's service) is one of them -- the shadow
|
||||||
|
//! vouches for the release it ran in and nothing else;
|
||||||
|
//! - `candidate.compatibility` is the live service's `--print-compatibility`;
|
||||||
|
//! - *saves were compared*: at least one live save per [`BRAIN_SECONDS_PER_SAVE`] brain seconds
|
||||||
|
//! compared byte for byte, and no more than [`MAX_UNAVAILABLE_FRACTION`] of the saves the trace
|
||||||
|
//! named were unavailable (a shadow starved past its spool must not pass on transitions alone);
|
||||||
|
//! - *nothing was skipped for a reason inside the session runtime*: every `skipped` entry's `kind`
|
||||||
|
//! is one of [`SKIP_KINDS`] (the live side's own events); a session-side failure is a
|
||||||
|
//! divergence, never a skip;
|
||||||
|
//! - *the shadow is caught up and alive*: `updatedAt` is no older than `max_age_s`, and
|
||||||
|
//! `lagTransitions` is at most [`MAX_LAG_TRANSITIONS`].
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
use crate::trace::{Agreement, Difference};
|
||||||
|
|
||||||
|
pub const FORMAT: &str = "fly-shadow-verdict-v1";
|
||||||
|
|
||||||
|
/// Skips that are the live side's own events, not the session runtime's failures: the operator
|
||||||
|
/// reward pulse (declared), a startup save rotated away before the shadow reached it, a trace
|
||||||
|
/// stopped at its byte cap or for want of a consumer, and a process that ran no transition.
|
||||||
|
pub const SKIP_KINDS: [&str; 4] = [
|
||||||
|
"operator-reward-pulse",
|
||||||
|
"startup-save-gone",
|
||||||
|
"trace-cap",
|
||||||
|
"no-transition",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// At least one live save compared byte for byte per this many brain seconds (the live loop
|
||||||
|
/// saves every 5 s; 600 leaves room for a lagging shadow's spool evictions).
|
||||||
|
pub const BRAIN_SECONDS_PER_SAVE: f64 = 600.0;
|
||||||
|
|
||||||
|
/// At most this fraction of the saves the trace named may have been unavailable.
|
||||||
|
pub const MAX_UNAVAILABLE_FRACTION: f64 = 0.1;
|
||||||
|
|
||||||
|
/// The shadow at most about a minute behind the live trace.
|
||||||
|
pub const MAX_LAG_TRANSITIONS: u64 = 3_600;
|
||||||
|
|
||||||
|
/// The declared differences the comparison applies, by name (`legacy-gameboy-v1`).
|
||||||
|
pub const DECLARED: [(&str, &str); 5] = [
|
||||||
|
(
|
||||||
|
"archive-order",
|
||||||
|
"a legacy milestone archive holds the pre-capture ratchet and slot (sections 4, 16): the \
|
||||||
|
live file's ratchet, ratchetGame and ratchetFrame stand in for the shadow's in that capture",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"decision-list-order",
|
||||||
|
"the decision is compared as gameboy-channels-v1: buttons down and the first bound channel \
|
||||||
|
held (section 6)",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"host-fields",
|
||||||
|
"generation, wallMs and lastEventId are the live file's: the session runtime has no feed \
|
||||||
|
event log before EDGE-01 and allocates no generations as a shadow",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"admission-replay",
|
||||||
|
"sugar is replayed from the live trace's admissions, not re-decided: admission reads a \
|
||||||
|
one-commit-stale pulse by the operator's decision (section 15)",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"operator-reward-pulse",
|
||||||
|
"a live POST /reward pulse cannot be reproduced (section 15 amendment): the rest of that \
|
||||||
|
segment is reported uncompared, not diverged",
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Status {
|
||||||
|
Running,
|
||||||
|
Pass,
|
||||||
|
Diverged,
|
||||||
|
Stopped,
|
||||||
|
Error,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Status {
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Status::Running => "running",
|
||||||
|
Status::Pass => "pass",
|
||||||
|
Status::Diverged => "diverged",
|
||||||
|
Status::Stopped => "stopped",
|
||||||
|
Status::Error => "error",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the checkpoint comparisons found.
|
||||||
|
#[derive(Clone, Debug, Default)]
|
||||||
|
pub struct Checkpoints {
|
||||||
|
/// Byte-identical after the host fields.
|
||||||
|
pub identical: u64,
|
||||||
|
/// Byte-identical after the host fields and a declared difference.
|
||||||
|
pub declared: u64,
|
||||||
|
/// Named in the trace but rotated away before the spool copied it.
|
||||||
|
pub unavailable: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A segment the shadow did not (fully) compare, and why.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Skipped {
|
||||||
|
pub trace: String,
|
||||||
|
pub transitions_compared: u64,
|
||||||
|
/// One of [`SKIP_KINDS`], or `trace-malformed`.
|
||||||
|
pub kind: String,
|
||||||
|
pub reason: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first divergence and its context.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Divergence {
|
||||||
|
/// `transition`, `ledgers`, `checkpoint`, `boot` or `session-error`.
|
||||||
|
pub kind: String,
|
||||||
|
pub trace: String,
|
||||||
|
pub step: Option<u64>,
|
||||||
|
pub difference: Option<Difference>,
|
||||||
|
pub detail: String,
|
||||||
|
/// The last transition lines before it, live and shadow, oldest first.
|
||||||
|
pub context: Vec<(Value, Value)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Divergence {
|
||||||
|
pub fn to_json(&self) -> Value {
|
||||||
|
json!({
|
||||||
|
"kind": self.kind,
|
||||||
|
"trace": self.trace,
|
||||||
|
"step": self.step.map(|s| s.to_string()),
|
||||||
|
"field": self.difference.as_ref().map(|d| d.field.clone()),
|
||||||
|
"live": self.difference.as_ref().map(|d| d.legacy.clone()),
|
||||||
|
"shadow": self.difference.as_ref().map(|d| d.session.clone()),
|
||||||
|
"detail": self.detail,
|
||||||
|
"context": self.context.iter().map(|(live, shadow)| json!({"live": live, "shadow": shadow})).collect::<Vec<_>>(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The per-frame cost of the shadow, wall time.
|
||||||
|
#[derive(Clone, Debug, Default)]
|
||||||
|
pub struct Cost {
|
||||||
|
samples: Vec<f64>,
|
||||||
|
pub total_ms: f64,
|
||||||
|
pub frames: u64,
|
||||||
|
pub throttled_ms: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Cost {
|
||||||
|
/// Keeps the last 36,000 frames (10 minutes) for the percentiles.
|
||||||
|
pub fn record(&mut self, ms: f64) {
|
||||||
|
self.total_ms += ms;
|
||||||
|
self.frames += 1;
|
||||||
|
if self.samples.len() == 36_000 {
|
||||||
|
self.samples.remove(0);
|
||||||
|
}
|
||||||
|
self.samples.push(ms);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_json(&self) -> Value {
|
||||||
|
let mut sorted = self.samples.clone();
|
||||||
|
sorted.sort_by(f64::total_cmp);
|
||||||
|
let pct = |p: f64| {
|
||||||
|
if sorted.is_empty() {
|
||||||
|
return Value::Null;
|
||||||
|
}
|
||||||
|
let i = ((sorted.len() - 1) as f64 * p).round() as usize;
|
||||||
|
json!((sorted[i] * 1000.0).round() / 1000.0)
|
||||||
|
};
|
||||||
|
json!({
|
||||||
|
"framesTimed": self.frames,
|
||||||
|
"msPerFrameMean": if self.frames == 0 { Value::Null } else { json!(((self.total_ms / self.frames as f64) * 1000.0).round() / 1000.0) },
|
||||||
|
"msPerFrameP50": pct(0.5),
|
||||||
|
"msPerFrameP99": pct(0.99),
|
||||||
|
"throttledSeconds": (self.throttled_ms / 1000.0).round(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Everything the verdict file says.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Verdict {
|
||||||
|
pub status: Status,
|
||||||
|
pub reason: String,
|
||||||
|
pub binary_sha256: String,
|
||||||
|
/// SHA-256 of the release binaries beside the shadow, by file name.
|
||||||
|
pub binaries: std::collections::BTreeMap<String, String>,
|
||||||
|
/// The directory they are in.
|
||||||
|
pub release: String,
|
||||||
|
pub compatibility: String,
|
||||||
|
pub execution_mode: String,
|
||||||
|
pub agent_threads: usize,
|
||||||
|
pub required_brain_seconds: f64,
|
||||||
|
pub agreement: Agreement,
|
||||||
|
pub brain_ms: f64,
|
||||||
|
pub ledger_checks: u64,
|
||||||
|
pub checkpoints: Checkpoints,
|
||||||
|
pub segments_compared: u64,
|
||||||
|
pub skipped: Vec<Skipped>,
|
||||||
|
pub divergence: Option<Divergence>,
|
||||||
|
pub started_at: String,
|
||||||
|
pub passed_at: Option<String>,
|
||||||
|
pub current_trace: Option<String>,
|
||||||
|
/// Complete live lines not yet compared in the current segment, when known.
|
||||||
|
pub lag_transitions: u64,
|
||||||
|
pub live_lag_seconds: Option<f64>,
|
||||||
|
pub spool_evicted: u64,
|
||||||
|
pub cost: Cost,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn now_iso() -> String {
|
||||||
|
let ms = std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.map_or(0, |d| d.as_millis() as i64);
|
||||||
|
iso(ms)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// UTC `YYYY-MM-DDTHH:MM:SS.mmmZ` from Unix milliseconds (civil-from-days).
|
||||||
|
pub fn iso(ms: i64) -> String {
|
||||||
|
let secs = ms.div_euclid(1000);
|
||||||
|
let millis = ms.rem_euclid(1000);
|
||||||
|
let days = secs.div_euclid(86_400);
|
||||||
|
let rem = secs.rem_euclid(86_400);
|
||||||
|
let z = days + 719_468;
|
||||||
|
let era = z.div_euclid(146_097);
|
||||||
|
let doe = z - era * 146_097;
|
||||||
|
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||||
|
let y = yoe + era * 400;
|
||||||
|
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||||
|
let mp = (5 * doy + 2) / 153;
|
||||||
|
let d = doy - (153 * mp + 2) / 5 + 1;
|
||||||
|
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||||
|
let y = if m <= 2 { y + 1 } else { y };
|
||||||
|
format!(
|
||||||
|
"{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.{millis:03}Z",
|
||||||
|
rem / 3600,
|
||||||
|
(rem % 3600) / 60,
|
||||||
|
rem % 60
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Verdict {
|
||||||
|
pub fn brain_seconds(&self) -> f64 {
|
||||||
|
self.brain_ms / 1000.0
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_json(&self) -> Value {
|
||||||
|
let a = &self.agreement;
|
||||||
|
json!({
|
||||||
|
"format": FORMAT,
|
||||||
|
"status": self.status.as_str(),
|
||||||
|
"reason": self.reason,
|
||||||
|
"candidate": {
|
||||||
|
"binarySha256": self.binary_sha256,
|
||||||
|
"binaries": self.binaries,
|
||||||
|
"release": self.release,
|
||||||
|
"compatibility": self.compatibility,
|
||||||
|
"compatibilitySha256": crate::shadow::sha256_hex(self.compatibility.as_bytes()),
|
||||||
|
"executionMode": self.execution_mode,
|
||||||
|
"agentThreads": self.agent_threads,
|
||||||
|
},
|
||||||
|
"required": {"brainSeconds": self.required_brain_seconds},
|
||||||
|
"compared": {
|
||||||
|
"brainSeconds": (self.brain_seconds() * 1000.0).round() / 1000.0,
|
||||||
|
"transitions": a.transitions,
|
||||||
|
"segments": self.segments_compared,
|
||||||
|
"sugar": a.sugar,
|
||||||
|
"rewards": a.rewards,
|
||||||
|
"rewardKinds": a.reward_kinds,
|
||||||
|
"macroEvents": a.macro_events,
|
||||||
|
"pressed": a.pressed,
|
||||||
|
"slotSaves": a.saves,
|
||||||
|
"rollbacks": a.rollbacks,
|
||||||
|
"spikes": a.spikes,
|
||||||
|
"ledgerChecks": self.ledger_checks,
|
||||||
|
"checkpoints": {
|
||||||
|
"identical": self.checkpoints.identical,
|
||||||
|
"declared": self.checkpoints.declared,
|
||||||
|
"unavailable": self.checkpoints.unavailable,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"skipped": self.skipped.iter().map(|s| json!({
|
||||||
|
"trace": s.trace, "transitionsCompared": s.transitions_compared, "kind": s.kind, "reason": s.reason,
|
||||||
|
})).collect::<Vec<_>>(),
|
||||||
|
"declaredDifferences": DECLARED.iter().map(|(name, what)| json!({"name": name, "what": what})).collect::<Vec<_>>(),
|
||||||
|
"firstDivergence": self.divergence.as_ref().map(|d| {
|
||||||
|
let mut v = d.to_json();
|
||||||
|
if let Some(o) = v.as_object_mut() { o.remove("context"); }
|
||||||
|
v
|
||||||
|
}),
|
||||||
|
"startedAt": self.started_at,
|
||||||
|
"updatedAt": now_iso(),
|
||||||
|
"passedAt": self.passed_at,
|
||||||
|
"currentTrace": self.current_trace,
|
||||||
|
"lagTransitions": self.lag_transitions,
|
||||||
|
"liveLagSeconds": self.live_lag_seconds,
|
||||||
|
"spoolEvicted": self.spool_evicted,
|
||||||
|
"cost": self.cost.to_json(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes `value` to `path` atomically.
|
||||||
|
pub fn write_json(path: &Path, value: &Value) -> std::io::Result<()> {
|
||||||
|
let tmp = path.with_extension("json.tmp");
|
||||||
|
let mut text = serde_json::to_string_pretty(value).expect("JSON serializes");
|
||||||
|
text.push('\n');
|
||||||
|
std::fs::write(&tmp, text)?;
|
||||||
|
std::fs::rename(&tmp, path)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the saves compared are enough for the brain time compared ([`BRAIN_SECONDS_PER_SAVE`],
|
||||||
|
/// [`MAX_UNAVAILABLE_FRACTION`]).
|
||||||
|
pub fn saves_suffice(brain_seconds: f64, compared: u64, unavailable: u64) -> Result<(), String> {
|
||||||
|
let needed = (brain_seconds / BRAIN_SECONDS_PER_SAVE).floor().max(1.0) as u64;
|
||||||
|
if compared < needed {
|
||||||
|
return Err(format!(
|
||||||
|
"{compared} live saves compared over {brain_seconds:.0} brain s; {needed} needed"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if unavailable as f64 > MAX_UNAVAILABLE_FRACTION * (compared + unavailable) as f64 {
|
||||||
|
return Err(format!(
|
||||||
|
"{unavailable} of {} live saves were unavailable to compare",
|
||||||
|
compared + unavailable
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The release the cutover would switch into: its resolved directory and the SHA-256 of the
|
||||||
|
/// binaries in it, by file name.
|
||||||
|
pub struct Release<'a> {
|
||||||
|
pub dir: &'a str,
|
||||||
|
pub binaries: &'a std::collections::BTreeMap<String, String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How far ahead of the clock a verdict's `updatedAt` may be before it is refused.
|
||||||
|
const MAX_CLOCK_SKEW_S: i64 = 60;
|
||||||
|
|
||||||
|
/// Reads a verdict file and says whether it allows the cutover, by the rule in the module notes.
|
||||||
|
/// `binary` is the file name of the session-runtime binary CUT-01 switches to, inside `release`
|
||||||
|
/// (what `/opt/fly/current` resolves to now), and `compatibility` the live service's;
|
||||||
|
/// `max_age_s` bounds `updatedAt`.
|
||||||
|
pub fn allows_cutover(
|
||||||
|
verdict: &Value,
|
||||||
|
binary: &str,
|
||||||
|
release: &Release<'_>,
|
||||||
|
compatibility: &str,
|
||||||
|
now_ms: i64,
|
||||||
|
max_age_s: i64,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
if verdict["format"] != FORMAT {
|
||||||
|
return Err(format!("not {FORMAT}"));
|
||||||
|
}
|
||||||
|
if verdict["status"] != "pass" {
|
||||||
|
return Err(format!("status is {}", verdict["status"]));
|
||||||
|
}
|
||||||
|
if !verdict["firstDivergence"].is_null() {
|
||||||
|
return Err("a divergence is recorded".to_owned());
|
||||||
|
}
|
||||||
|
let candidate = &verdict["candidate"];
|
||||||
|
if candidate["release"] != release.dir {
|
||||||
|
return Err(format!(
|
||||||
|
"the verdict is for the release {}, not {}",
|
||||||
|
candidate["release"], release.dir
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let shadowed = candidate["binaries"]
|
||||||
|
.as_object()
|
||||||
|
.ok_or("the verdict names no binaries")?;
|
||||||
|
if !shadowed.contains_key(binary) {
|
||||||
|
return Err(format!("{binary} was not in the shadowed release"));
|
||||||
|
}
|
||||||
|
for (name, sha) in shadowed {
|
||||||
|
if release.binaries.get(name).map(String::as_str) != sha.as_str() {
|
||||||
|
return Err(format!(
|
||||||
|
"{name} in {} is not the binary the shadow ran beside",
|
||||||
|
release.dir
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if candidate["compatibility"] != compatibility {
|
||||||
|
return Err("the verdict is for another compatibility string".to_owned());
|
||||||
|
}
|
||||||
|
let compared = verdict["compared"]["brainSeconds"].as_f64().unwrap_or(0.0);
|
||||||
|
// The operator's window is a floor the verdict cannot lower: a shadow run with a shorter
|
||||||
|
// `--required-brain-seconds` (a rehearsal, a test) never arms the cutover.
|
||||||
|
let required = verdict["required"]["brainSeconds"]
|
||||||
|
.as_f64()
|
||||||
|
.unwrap_or(f64::INFINITY)
|
||||||
|
.max(crate::shadow::REQUIRED_BRAIN_SECONDS);
|
||||||
|
if compared < required {
|
||||||
|
return Err(format!("{compared} of {required} brain seconds compared"));
|
||||||
|
}
|
||||||
|
let saves = &verdict["compared"]["checkpoints"];
|
||||||
|
saves_suffice(
|
||||||
|
compared,
|
||||||
|
saves["identical"].as_u64().unwrap_or(0) + saves["declared"].as_u64().unwrap_or(0),
|
||||||
|
saves["unavailable"].as_u64().unwrap_or(u64::MAX / 2),
|
||||||
|
)?;
|
||||||
|
for skip in verdict["skipped"].as_array().into_iter().flatten() {
|
||||||
|
let kind = skip["kind"].as_str().unwrap_or("");
|
||||||
|
if !SKIP_KINDS.contains(&kind) {
|
||||||
|
return Err(format!(
|
||||||
|
"a segment was skipped for {kind:?}: {}",
|
||||||
|
skip["reason"]
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let lag = verdict["lagTransitions"].as_u64().unwrap_or(u64::MAX);
|
||||||
|
if lag > MAX_LAG_TRANSITIONS {
|
||||||
|
return Err(format!(
|
||||||
|
"the shadow is {lag} transitions behind the live trace"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let updated = verdict["updatedAt"]
|
||||||
|
.as_str()
|
||||||
|
.and_then(parse_iso)
|
||||||
|
.ok_or("no updatedAt")?;
|
||||||
|
// A verdict from the future (beyond a small skew) is refused: after a backward clock step an
|
||||||
|
// old pass would otherwise stay "fresh" for the size of the step plus `max_age_s`.
|
||||||
|
if updated - now_ms > MAX_CLOCK_SKEW_S * 1000 {
|
||||||
|
return Err(format!(
|
||||||
|
"the verdict is dated {} s in the future",
|
||||||
|
(updated - now_ms) / 1000
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if now_ms - updated > max_age_s * 1000 {
|
||||||
|
return Err(format!(
|
||||||
|
"the verdict is {} s old",
|
||||||
|
(now_ms - updated) / 1000
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses [`iso`]'s format back to Unix milliseconds.
|
||||||
|
pub fn parse_iso(text: &str) -> Option<i64> {
|
||||||
|
let b = text.as_bytes();
|
||||||
|
if b.len() != 24 || b[23] != b'Z' {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let n = |r: std::ops::Range<usize>| -> Option<i64> { text.get(r)?.parse().ok() };
|
||||||
|
let (y, m, d) = (n(0..4)?, n(5..7)?, n(8..10)?);
|
||||||
|
let (hh, mm, ss, ms) = (n(11..13)?, n(14..16)?, n(17..19)?, n(20..23)?);
|
||||||
|
let y = if m <= 2 { y - 1 } else { y };
|
||||||
|
let era = y.div_euclid(400);
|
||||||
|
let yoe = y - era * 400;
|
||||||
|
let mp = if m > 2 { m - 3 } else { m + 9 };
|
||||||
|
let doy = (153 * mp + 2) / 5 + d - 1;
|
||||||
|
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
|
||||||
|
let days = era * 146_097 + doe - 719_468;
|
||||||
|
Some(((days * 86_400 + hh * 3600 + mm * 60 + ss) * 1000) + ms)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn iso_round_trips() {
|
||||||
|
for ms in [0i64, 951_782_400_123, 1_790_000_000_999, 4_102_444_800_000] {
|
||||||
|
assert_eq!(parse_iso(&iso(ms)), Some(ms), "{}", iso(ms));
|
||||||
|
}
|
||||||
|
assert_eq!(iso(0), "1970-01-01T00:00:00.000Z");
|
||||||
|
assert_eq!(iso(951_782_400_123), "2000-02-29T00:00:00.123Z");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verdict(status: Status, brain_ms: f64) -> Value {
|
||||||
|
Verdict {
|
||||||
|
status,
|
||||||
|
reason: String::new(),
|
||||||
|
binary_sha256: "b".repeat(64),
|
||||||
|
binaries: [("flysim-session".to_owned(), "b".repeat(64))].into(),
|
||||||
|
release: "/opt/fly/releases/test".to_owned(),
|
||||||
|
compatibility: "c".to_owned(),
|
||||||
|
execution_mode: "in-process".to_owned(),
|
||||||
|
agent_threads: 2,
|
||||||
|
required_brain_seconds: 10_800.0,
|
||||||
|
agreement: Agreement::default(),
|
||||||
|
brain_ms,
|
||||||
|
ledger_checks: 0,
|
||||||
|
checkpoints: Checkpoints {
|
||||||
|
identical: 2_000,
|
||||||
|
declared: 1,
|
||||||
|
unavailable: 5,
|
||||||
|
},
|
||||||
|
segments_compared: 1,
|
||||||
|
skipped: Vec::new(),
|
||||||
|
divergence: None,
|
||||||
|
started_at: now_iso(),
|
||||||
|
passed_at: None,
|
||||||
|
current_trace: None,
|
||||||
|
lag_transitions: 0,
|
||||||
|
live_lag_seconds: None,
|
||||||
|
spool_evicted: 0,
|
||||||
|
cost: Cost::default(),
|
||||||
|
}
|
||||||
|
.to_json()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_cutover_rule() {
|
||||||
|
let now = parse_iso(&now_iso()).unwrap();
|
||||||
|
let binaries: std::collections::BTreeMap<String, String> =
|
||||||
|
[("flysim-session".to_owned(), "b".repeat(64))].into();
|
||||||
|
let release = Release {
|
||||||
|
dir: "/opt/fly/releases/test",
|
||||||
|
binaries: &binaries,
|
||||||
|
};
|
||||||
|
let ok = |v: &Value| allows_cutover(v, "flysim-session", &release, "c", now, 300);
|
||||||
|
let pass = verdict(Status::Pass, 10_800_000.0);
|
||||||
|
assert_eq!(ok(&pass), Ok(()));
|
||||||
|
// Another binary, another release, a changed file in it.
|
||||||
|
assert!(allows_cutover(&pass, "fly-other", &release, "c", now, 300).is_err());
|
||||||
|
let moved = Release {
|
||||||
|
dir: "/opt/fly/releases/other",
|
||||||
|
binaries: &binaries,
|
||||||
|
};
|
||||||
|
assert!(allows_cutover(&pass, "flysim-session", &moved, "c", now, 300).is_err());
|
||||||
|
let changed: std::collections::BTreeMap<String, String> =
|
||||||
|
[("flysim-session".to_owned(), "a".repeat(64))].into();
|
||||||
|
let rebuilt = Release {
|
||||||
|
dir: "/opt/fly/releases/test",
|
||||||
|
binaries: &changed,
|
||||||
|
};
|
||||||
|
assert!(allows_cutover(&pass, "flysim-session", &rebuilt, "c", now, 300).is_err());
|
||||||
|
assert!(allows_cutover(&pass, "flysim-session", &release, "other", now, 300).is_err());
|
||||||
|
assert!(
|
||||||
|
allows_cutover(&pass, "flysim-session", &release, "c", now + 301_000, 300).is_err()
|
||||||
|
);
|
||||||
|
// A clock stepped back: a verdict dated well ahead of now is refused, a small skew is not.
|
||||||
|
assert!(
|
||||||
|
allows_cutover(&pass, "flysim-session", &release, "c", now - 120_000, 300).is_err()
|
||||||
|
);
|
||||||
|
assert!(allows_cutover(&pass, "flysim-session", &release, "c", now - 30_000, 300).is_ok());
|
||||||
|
assert!(ok(&verdict(Status::Pass, 10_799_000.0)).is_err());
|
||||||
|
// A verdict that asked for less than the operator's 3 h never passes the check.
|
||||||
|
let mut short_window = verdict(Status::Pass, 67_000.0);
|
||||||
|
short_window["required"]["brainSeconds"] = json!(60.0);
|
||||||
|
assert!(ok(&short_window).is_err());
|
||||||
|
for status in [
|
||||||
|
Status::Running,
|
||||||
|
Status::Diverged,
|
||||||
|
Status::Stopped,
|
||||||
|
Status::Error,
|
||||||
|
] {
|
||||||
|
assert!(ok(&verdict(status, 10_800_000.0)).is_err());
|
||||||
|
}
|
||||||
|
let mut diverged = pass.clone();
|
||||||
|
diverged["firstDivergence"] = json!({"kind": "transition"});
|
||||||
|
assert!(ok(&diverged).is_err());
|
||||||
|
// Saves: none compared, or too many unavailable.
|
||||||
|
let mut starved = pass.clone();
|
||||||
|
starved["compared"]["checkpoints"] =
|
||||||
|
json!({"identical": 0, "declared": 0, "unavailable": 0});
|
||||||
|
assert!(ok(&starved).is_err());
|
||||||
|
starved["compared"]["checkpoints"] =
|
||||||
|
json!({"identical": 100, "declared": 0, "unavailable": 50});
|
||||||
|
assert!(ok(&starved).is_err());
|
||||||
|
// Skips: the live side's own are fine, anything else is not.
|
||||||
|
let mut skipped = pass.clone();
|
||||||
|
skipped["skipped"] = json!([{"kind": "startup-save-gone", "reason": "x"}]);
|
||||||
|
assert_eq!(ok(&skipped), Ok(()));
|
||||||
|
skipped["skipped"] = json!([{"kind": "trace-malformed", "reason": "x"}]);
|
||||||
|
assert!(ok(&skipped).is_err());
|
||||||
|
// Behind the live trace.
|
||||||
|
let mut behind = pass.clone();
|
||||||
|
behind["lagTransitions"] = json!(MAX_LAG_TRANSITIONS + 1);
|
||||||
|
assert!(ok(&behind).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -144,23 +144,7 @@ pub fn ledgers_of(
|
||||||
ratchet: &Ratchet,
|
ratchet: &Ratchet,
|
||||||
macros: Option<&MacroLayer>,
|
macros: Option<&MacroLayer>,
|
||||||
) -> String {
|
) -> String {
|
||||||
let executor = match macros {
|
flysim::frame::ledgers_string(adapter, ratchet, macros)
|
||||||
Some(layer) => json!({
|
|
||||||
"scene": layer.scene_name(),
|
|
||||||
"bound": layer.bound_channels(),
|
|
||||||
"running": layer.running(),
|
|
||||||
"counts": format!("{:?}", layer.counts()),
|
|
||||||
"nearer": layer.nearer_the_objective(),
|
|
||||||
}),
|
|
||||||
None => Value::Null,
|
|
||||||
};
|
|
||||||
json!({
|
|
||||||
"adapter": adapter.export_state(),
|
|
||||||
"ratchet": serde_json::to_value(ratchet.state).expect("serializes"),
|
|
||||||
"slot": ratchet.snapshot.is_some(),
|
|
||||||
"executor": executor,
|
|
||||||
})
|
|
||||||
.to_string()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What one transition gave the feed (SERVE-01), in the order the legacy loop emits it: the
|
/// What one transition gave the feed (SERVE-01), in the order the legacy loop emits it: the
|
||||||
|
|
|
||||||
|
|
@ -165,6 +165,91 @@ pub struct Agreement {
|
||||||
pub spikes: u64,
|
pub spikes: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The first field two transition lines disagree on, with both values.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct Difference {
|
||||||
|
pub field: String,
|
||||||
|
pub legacy: Value,
|
||||||
|
pub session: Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for Difference {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
write!(
|
||||||
|
f,
|
||||||
|
"{}:\n legacy {}\n session {}",
|
||||||
|
self.field, self.legacy, self.session
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One transition, field by field over the union of both lines' keys, the decision as
|
||||||
|
/// [`channels`] of the session's bound set for that transition.
|
||||||
|
pub fn compare_line(
|
||||||
|
legacy: &Value,
|
||||||
|
session: &Value,
|
||||||
|
bound: &[String],
|
||||||
|
) -> Result<(), Box<Difference>> {
|
||||||
|
let (Some(a_map), Some(b_map)) = (legacy.as_object(), session.as_object()) else {
|
||||||
|
return Err(Box::new(Difference {
|
||||||
|
field: "(line)".to_owned(),
|
||||||
|
legacy: legacy.clone(),
|
||||||
|
session: session.clone(),
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
let keys: BTreeSet<&String> = a_map.keys().chain(b_map.keys()).collect();
|
||||||
|
for key in keys {
|
||||||
|
let (x, y) = (&legacy[key.as_str()], &session[key.as_str()]);
|
||||||
|
let same = if key == "decision" {
|
||||||
|
channels(x, bound) == channels(y, bound)
|
||||||
|
} else {
|
||||||
|
x == y
|
||||||
|
};
|
||||||
|
if !same {
|
||||||
|
return Err(Box::new(Difference {
|
||||||
|
field: key.clone(),
|
||||||
|
legacy: x.clone(),
|
||||||
|
session: y.clone(),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Agreement {
|
||||||
|
/// Counts one agreed transition line.
|
||||||
|
pub fn count(&mut self, line: &Value) {
|
||||||
|
self.transitions += 1;
|
||||||
|
for admission in line["admissions"].as_array().into_iter().flatten() {
|
||||||
|
match admission["kind"].as_str() {
|
||||||
|
Some("sugar") => self.sugar += 1,
|
||||||
|
Some("reward") => self.reward_pulses += 1,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for reward in line["rewards"].as_array().into_iter().flatten() {
|
||||||
|
self.rewards += 1;
|
||||||
|
if let Some(kind) = reward["kind"].as_str()
|
||||||
|
&& !self.reward_kinds.iter().any(|k| k == kind)
|
||||||
|
{
|
||||||
|
self.reward_kinds.push(kind.to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.macro_events += line["macroEvents"].as_array().map_or(0, |v| v.len() as u64);
|
||||||
|
if line["mask"].as_u64().unwrap_or(0) != 0 {
|
||||||
|
self.pressed += 1;
|
||||||
|
}
|
||||||
|
for action in line["boundaryActions"].as_array().into_iter().flatten() {
|
||||||
|
match action["kind"].as_str() {
|
||||||
|
Some("save-slot") => self.saves += 1,
|
||||||
|
Some("rollback") => self.rollbacks += 1,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.spikes += line["spikeCount"].as_u64().unwrap_or(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Every transition identical, field by field; the decision as [`channels`] of the session's bound
|
/// Every transition identical, field by field; the decision as [`channels`] of the session's bound
|
||||||
/// set for that transition. The first difference is the error, with both values.
|
/// set for that transition. The first difference is the error, with both values.
|
||||||
pub fn compare(
|
pub fn compare(
|
||||||
|
|
@ -184,52 +269,9 @@ pub fn compare(
|
||||||
}
|
}
|
||||||
let mut agreement = Agreement::default();
|
let mut agreement = Agreement::default();
|
||||||
for (n, (a, b)) in legacy.iter().zip(session).enumerate() {
|
for (n, (a, b)) in legacy.iter().zip(session).enumerate() {
|
||||||
let (Some(a_map), Some(b_map)) = (a.as_object(), b.as_object()) else {
|
compare_line(a, b, &bounds[n])
|
||||||
return Err(format!("transition {n}: not an object"));
|
.map_err(|d| format!("transition {n} (step {}) {d}", a["step"]))?;
|
||||||
};
|
agreement.count(a);
|
||||||
let keys: BTreeSet<&String> = a_map.keys().chain(b_map.keys()).collect();
|
|
||||||
for key in keys {
|
|
||||||
let (x, y) = (&a[key.as_str()], &b[key.as_str()]);
|
|
||||||
let same = if key == "decision" {
|
|
||||||
channels(x, &bounds[n]) == channels(y, &bounds[n])
|
|
||||||
} else {
|
|
||||||
x == y
|
|
||||||
};
|
|
||||||
if !same {
|
|
||||||
return Err(format!(
|
|
||||||
"transition {n} (step {}) {key}:\n legacy {x}\n session {y}",
|
|
||||||
a["step"]
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
agreement.transitions += 1;
|
|
||||||
for admission in a["admissions"].as_array().into_iter().flatten() {
|
|
||||||
match admission["kind"].as_str() {
|
|
||||||
Some("sugar") => agreement.sugar += 1,
|
|
||||||
Some("reward") => agreement.reward_pulses += 1,
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for reward in a["rewards"].as_array().into_iter().flatten() {
|
|
||||||
agreement.rewards += 1;
|
|
||||||
if let Some(kind) = reward["kind"].as_str()
|
|
||||||
&& !agreement.reward_kinds.iter().any(|k| k == kind)
|
|
||||||
{
|
|
||||||
agreement.reward_kinds.push(kind.to_owned());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
agreement.macro_events += a["macroEvents"].as_array().map_or(0, |v| v.len() as u64);
|
|
||||||
if a["mask"].as_u64().unwrap_or(0) != 0 {
|
|
||||||
agreement.pressed += 1;
|
|
||||||
}
|
|
||||||
for action in a["boundaryActions"].as_array().into_iter().flatten() {
|
|
||||||
match action["kind"].as_str() {
|
|
||||||
Some("save-slot") => agreement.saves += 1,
|
|
||||||
Some("rollback") => agreement.rollbacks += 1,
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
agreement.spikes += a["spikeCount"].as_u64().unwrap_or(0);
|
|
||||||
}
|
}
|
||||||
Ok(agreement)
|
Ok(agreement)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
561
services/flysim/crates/fly-legacy-session/tests/shadow.rs
Normal file
561
services/flysim/crates/fly-legacy-session/tests/shadow.rs
Normal file
|
|
@ -0,0 +1,561 @@
|
||||||
|
//! SHADOW-01 end to end, on the committed toy connectome in raw mode (an explicit ROM job:
|
||||||
|
//! `FLY_ROM`, and the workspace's `flysim` binary beside this test's).
|
||||||
|
//!
|
||||||
|
//! The *real* `flysim` service runs with the shadow's trace switches (`FLY_TRACE_DIR`,
|
||||||
|
//! `FLY_TRACE_LEDGERS=1`, a hot save every second), takes sugar through its control API and is
|
||||||
|
//! restarted once; the shadow (`fly_legacy_session::shadow::run`) follows it from its first frame.
|
||||||
|
//! Every transition, ledger digest and live save must agree, across both processes.
|
||||||
|
//!
|
||||||
|
//! Then the negative controls, on copies of the same trace and spool: a work-RAM digest flipped,
|
||||||
|
//! a sugar removed, a ledger digest flipped and a live save's bytes changed must each stop a
|
||||||
|
//! fresh shadow with a `diverged` verdict naming the right kind, field and step.
|
||||||
|
//!
|
||||||
|
//! The FAFB rehearsal of the same pipeline, at stream scale, is `tools/shadow-rehearsal.sh`.
|
||||||
|
|
||||||
|
use std::io::{Read, Write};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::{Child, Command, Stdio};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
use fly_legacy_session::shadow::{self, Ended, ShadowConfig, StopFlag, verdict::Status};
|
||||||
|
use fly_session::ExecutionMode;
|
||||||
|
use fly_session::legacy_agent::LegacyProfileKind;
|
||||||
|
use fly_session::legacy_parity;
|
||||||
|
use flysim::snapshot::MacroMode;
|
||||||
|
|
||||||
|
/// The `flysim` binary built from *this* tree, in this test's own target directory and profile.
|
||||||
|
///
|
||||||
|
/// `cargo test -p fly-legacy-session` does not build `flysim`'s binary, so a binary found beside the
|
||||||
|
/// test can be stale -- built from another tree that shared the target directory -- and a stale
|
||||||
|
/// flysim that predates `FLY_TRACE_DIR` writes no trace at all (the "one trace file per process"
|
||||||
|
/// failure, 0 files, seen on a build box whose target directory other trees shared). So the test
|
||||||
|
/// builds it: `cargo build -p flysim --bin flysim` with the same target directory, profile and
|
||||||
|
/// flags, a no-op when it is current. `None` (skip) only when cargo is not reachable.
|
||||||
|
fn flysim_binary() -> Option<PathBuf> {
|
||||||
|
let exe = std::env::current_exe().ok()?;
|
||||||
|
let profile_dir = exe.parent()?.parent()?; // <target>/<profile>/deps/<test>
|
||||||
|
let target = profile_dir.parent()?;
|
||||||
|
let release = profile_dir.file_name()? == "release";
|
||||||
|
let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
|
||||||
|
let mut build = Command::new(cargo);
|
||||||
|
build
|
||||||
|
.args(["build", "-p", "flysim", "--bin", "flysim"])
|
||||||
|
.env("CARGO_TARGET_DIR", target)
|
||||||
|
.current_dir(env!("CARGO_MANIFEST_DIR"));
|
||||||
|
if release {
|
||||||
|
build.arg("--release");
|
||||||
|
}
|
||||||
|
match build.status() {
|
||||||
|
Ok(status) => assert!(
|
||||||
|
status.success(),
|
||||||
|
"building the flysim binary under test failed"
|
||||||
|
),
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("skipping: cargo is not reachable to build flysim ({e})");
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let path = profile_dir.join("flysim");
|
||||||
|
assert!(
|
||||||
|
path.is_file(),
|
||||||
|
"no flysim binary at {} after the build",
|
||||||
|
path.display()
|
||||||
|
);
|
||||||
|
Some(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn free_port() -> u16 {
|
||||||
|
std::net::TcpListener::bind("127.0.0.1:0")
|
||||||
|
.expect("an ephemeral port")
|
||||||
|
.local_addr()
|
||||||
|
.expect("its address")
|
||||||
|
.port()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn http(port: u16, method: &str, path: &str, body: Option<&str>) -> Option<(u16, String)> {
|
||||||
|
let mut stream = std::net::TcpStream::connect(("127.0.0.1", port)).ok()?;
|
||||||
|
stream.set_read_timeout(Some(Duration::from_secs(5))).ok()?;
|
||||||
|
let body = body.unwrap_or("");
|
||||||
|
write!(
|
||||||
|
stream,
|
||||||
|
"{method} {path} HTTP/1.0\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}",
|
||||||
|
body.len()
|
||||||
|
)
|
||||||
|
.ok()?;
|
||||||
|
let mut text = String::new();
|
||||||
|
stream.read_to_string(&mut text).ok()?;
|
||||||
|
let status = text.split_whitespace().nth(1)?.parse().ok()?;
|
||||||
|
let body = text
|
||||||
|
.split_once("\r\n\r\n")
|
||||||
|
.map_or("", |(_, b)| b)
|
||||||
|
.to_owned();
|
||||||
|
Some((status, body))
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Live {
|
||||||
|
child: Child,
|
||||||
|
control: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct LiveDirs {
|
||||||
|
hot: PathBuf,
|
||||||
|
durable: PathBuf,
|
||||||
|
trace: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start_live(binary: &Path, rom: &Path, dirs: &LiveDirs, log: &Path) -> Live {
|
||||||
|
start_live_traced(binary, rom, dirs, log, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `traced = false` starts the service with no `FLY_TRACE_DIR`: a live process that leaves no
|
||||||
|
/// trace, as one whose trace cannot be created would.
|
||||||
|
fn start_live_traced(binary: &Path, rom: &Path, dirs: &LiveDirs, log: &Path, traced: bool) -> Live {
|
||||||
|
let trace_dir = if traced {
|
||||||
|
dirs.trace.clone()
|
||||||
|
} else {
|
||||||
|
PathBuf::new()
|
||||||
|
};
|
||||||
|
let control = free_port();
|
||||||
|
let child = Command::new(binary)
|
||||||
|
.env("FLY_ROM", rom)
|
||||||
|
.env("FLY_DATASET", legacy_parity::toy::dir())
|
||||||
|
.env("FLY_STATE", &dirs.durable)
|
||||||
|
.env("FLY_STATE_HOT", &dirs.hot)
|
||||||
|
.env("FLY_FEED_BIND", format!("127.0.0.1:{}", free_port()))
|
||||||
|
.env("FLY_CONTROL_BIND", format!("127.0.0.1:{control}"))
|
||||||
|
.env("FLY_METRICS_ADDR", format!("127.0.0.1:{}", free_port()))
|
||||||
|
.env("FLY_MACRO_MODE", "raw")
|
||||||
|
.env("FLY_CHAT_ENABLED", "false")
|
||||||
|
.env("FLYSIM_LOOP_GAME", "pokemon-red")
|
||||||
|
.env("FLYSIM_LOOP_SPEED", "0")
|
||||||
|
.env("FLYSIM_LOOP_HOT_SECONDS", "1")
|
||||||
|
.env("FLYSIM_LOOP_CHECKPOINT_SECONDS", "4")
|
||||||
|
.env("RAYON_NUM_THREADS", "1")
|
||||||
|
.env("FLY_TRACE_DIR", &trace_dir)
|
||||||
|
.env("FLY_TRACE_LEDGERS", "1")
|
||||||
|
.env_remove("FLY_TRACE")
|
||||||
|
.env_remove("NOTIFY_SOCKET")
|
||||||
|
.stdin(Stdio::null())
|
||||||
|
.stdout(Stdio::null())
|
||||||
|
.stderr(std::fs::File::create(log).expect("a log"))
|
||||||
|
.spawn()
|
||||||
|
.expect("flysim starts");
|
||||||
|
let live = Live { child, control };
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(240);
|
||||||
|
while live.brain_ms().is_none() {
|
||||||
|
assert!(Instant::now() < deadline, "flysim never ran");
|
||||||
|
std::thread::sleep(Duration::from_millis(200));
|
||||||
|
}
|
||||||
|
live
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Live {
|
||||||
|
fn brain_ms(&self) -> Option<f64> {
|
||||||
|
let (status, body) = http(self.control, "GET", "/status", None)?;
|
||||||
|
let v: Value = serde_json::from_str(&body).ok()?;
|
||||||
|
(status == 200 && v["status"] == "running").then(|| v["brainMs"].as_f64())?
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sugar(&self, ms: u32) {
|
||||||
|
let body = format!(r#"{{"durationMs":{ms},"by":"shadow-test","source":"operator"}}"#);
|
||||||
|
let (status, text) =
|
||||||
|
http(self.control, "POST", "/stimulate", Some(&body)).expect("the control API");
|
||||||
|
assert!(
|
||||||
|
(200..300).contains(&status),
|
||||||
|
"sugar refused: {status} {text}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_for(&self, brain_ms: f64) {
|
||||||
|
let start = self.brain_ms().expect("running");
|
||||||
|
while self.brain_ms().unwrap_or(start) < start + brain_ms {
|
||||||
|
std::thread::sleep(Duration::from_millis(100));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stop(mut self) {
|
||||||
|
let _ = Command::new("kill")
|
||||||
|
.args(["-TERM", &self.child.id().to_string()])
|
||||||
|
.status();
|
||||||
|
let _ = self.child.wait();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn config(
|
||||||
|
rom: &Path,
|
||||||
|
root: &Path,
|
||||||
|
trace: &Path,
|
||||||
|
sources: (&Path, &Path),
|
||||||
|
spool: &Path,
|
||||||
|
) -> ShadowConfig {
|
||||||
|
ShadowConfig {
|
||||||
|
trace_dir: trace.to_owned(),
|
||||||
|
hot_dir: sources.0.to_owned(),
|
||||||
|
durable_dir: sources.1.to_owned(),
|
||||||
|
out_dir: root.join("out"),
|
||||||
|
spool_dir: spool.to_owned(),
|
||||||
|
work_dir: root.join("work"),
|
||||||
|
rom_path: rom.to_owned(),
|
||||||
|
dataset_dir: legacy_parity::toy::dir(),
|
||||||
|
profile: LegacyProfileKind::Toy,
|
||||||
|
macro_mode: MacroMode::Raw,
|
||||||
|
speed: 0.0,
|
||||||
|
mode: ExecutionMode::InProcess,
|
||||||
|
agent_threads: 1,
|
||||||
|
required_brain_seconds: 30.0,
|
||||||
|
all_files: true,
|
||||||
|
keep_traces: true,
|
||||||
|
keep_spool: true,
|
||||||
|
exit_on_pass: false,
|
||||||
|
max_transitions: None,
|
||||||
|
spool_max_bytes: 1 << 30,
|
||||||
|
context_lines: 5,
|
||||||
|
poll: Duration::from_millis(20),
|
||||||
|
lag_guard: None,
|
||||||
|
binary_sha256: "test".to_owned(),
|
||||||
|
binaries: Default::default(),
|
||||||
|
release: String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn transitions(trace: &Path) -> Vec<(PathBuf, usize)> {
|
||||||
|
shadow::follow::trace_files(trace)
|
||||||
|
.unwrap()
|
||||||
|
.into_iter()
|
||||||
|
.map(|path| {
|
||||||
|
let n = std::fs::read_to_string(&path)
|
||||||
|
.unwrap()
|
||||||
|
.lines()
|
||||||
|
.filter(|l| l.contains("\"behaviour\""))
|
||||||
|
.count();
|
||||||
|
(path, n)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verdict_of(out: &Path) -> Value {
|
||||||
|
std::fs::read_to_string(out.join("verdict.json"))
|
||||||
|
.ok()
|
||||||
|
.and_then(|t| serde_json::from_str(&t).ok())
|
||||||
|
.unwrap_or(Value::Null)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Copies `trace` into a new directory, applying `edit` to the first file's lines.
|
||||||
|
fn tampered(trace: &Path, to: &Path, edit: impl Fn(usize, &mut Value) -> bool) -> u64 {
|
||||||
|
std::fs::create_dir_all(to).unwrap();
|
||||||
|
let mut step = None;
|
||||||
|
for (i, (path, _)) in transitions(trace).into_iter().enumerate() {
|
||||||
|
let text = std::fs::read_to_string(&path).unwrap();
|
||||||
|
let mut out = String::new();
|
||||||
|
let mut n = 0;
|
||||||
|
for line in text.lines() {
|
||||||
|
let mut v: Value = serde_json::from_str(line).unwrap();
|
||||||
|
if i == 0 && v.get("behaviour").is_some() {
|
||||||
|
if step.is_none() && edit(n, &mut v) {
|
||||||
|
step = v["behaviour"]["step"].as_str().and_then(|s| s.parse().ok());
|
||||||
|
}
|
||||||
|
n += 1;
|
||||||
|
}
|
||||||
|
out.push_str(&v.to_string());
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
std::fs::write(to.join(path.file_name().unwrap()), out).unwrap();
|
||||||
|
}
|
||||||
|
step.expect("the edit applied")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The shadow on a thread of its own with its own runtime (the session's future is not `Send`).
|
||||||
|
fn spawn_shadow(
|
||||||
|
config: ShadowConfig,
|
||||||
|
stop: StopFlag,
|
||||||
|
) -> std::thread::JoinHandle<Result<(Ended, shadow::verdict::Verdict), String>> {
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
tokio::runtime::Builder::new_multi_thread()
|
||||||
|
.worker_threads(2)
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.expect("a runtime")
|
||||||
|
.block_on(shadow::run(config, stop))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn diverges(
|
||||||
|
rom: &Path,
|
||||||
|
root: &Path,
|
||||||
|
trace: &Path,
|
||||||
|
spool: &Path,
|
||||||
|
empty: &Path,
|
||||||
|
) -> shadow::verdict::Verdict {
|
||||||
|
diverges_with(rom, root, trace, spool, empty, |_| {})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn diverges_with(
|
||||||
|
rom: &Path,
|
||||||
|
root: &Path,
|
||||||
|
trace: &Path,
|
||||||
|
spool: &Path,
|
||||||
|
empty: &Path,
|
||||||
|
edit: impl FnOnce(&mut ShadowConfig),
|
||||||
|
) -> shadow::verdict::Verdict {
|
||||||
|
let _ = std::fs::remove_dir_all(root.join("out"));
|
||||||
|
let mut config = config(rom, root, trace, (empty, empty), spool);
|
||||||
|
edit(&mut config);
|
||||||
|
let stop = StopFlag::default();
|
||||||
|
let handle = spawn_shadow(config, stop.clone());
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(600);
|
||||||
|
while !handle.is_finished() {
|
||||||
|
if Instant::now() > deadline {
|
||||||
|
stop.request();
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(100));
|
||||||
|
}
|
||||||
|
let (ended, verdict) = handle.join().unwrap().expect("the shadow ran");
|
||||||
|
assert_eq!(ended, Ended::Diverged, "{:?}", verdict.reason);
|
||||||
|
verdict
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_shadow_follows_the_real_service_and_catches_every_planted_difference() {
|
||||||
|
let Some(rom) = std::env::var_os("FLY_ROM").map(PathBuf::from) else {
|
||||||
|
eprintln!("skipping: FLY_ROM is not set (source bin/rom-env.sh)");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Some(binary) = flysim_binary() else {
|
||||||
|
eprintln!("skipping: no flysim binary beside this test (cargo test --workspace builds it)");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
// `FLY_SHADOW_TEST_DIR` keeps everything for a look afterwards.
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let kept = std::env::var_os("FLY_SHADOW_TEST_DIR").map(PathBuf::from);
|
||||||
|
if let Some(dir) = &kept {
|
||||||
|
let _ = std::fs::remove_dir_all(dir);
|
||||||
|
std::fs::create_dir_all(dir).unwrap();
|
||||||
|
}
|
||||||
|
let root_path = kept.unwrap_or_else(|| tmp.path().to_owned());
|
||||||
|
let root = &root_path;
|
||||||
|
let dirs = LiveDirs {
|
||||||
|
hot: root.join("live/hot"),
|
||||||
|
durable: root.join("live/durable"),
|
||||||
|
trace: root.join("live/trace"),
|
||||||
|
};
|
||||||
|
let spool = root.join("shadow/spool");
|
||||||
|
let shadow_root = root.join("shadow");
|
||||||
|
let config = config(
|
||||||
|
&rom,
|
||||||
|
&shadow_root,
|
||||||
|
&dirs.trace,
|
||||||
|
(&dirs.hot, &dirs.durable),
|
||||||
|
&spool,
|
||||||
|
);
|
||||||
|
let out = config.out_dir.clone();
|
||||||
|
let stop = StopFlag::default();
|
||||||
|
let handle = spawn_shadow(config, stop.clone());
|
||||||
|
// The live recorder starts no trace without the shadow's heartbeat.
|
||||||
|
let heartbeat = dirs.trace.join(flysim::trace::CONSUMER_FILE);
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(60);
|
||||||
|
while !heartbeat.is_file() {
|
||||||
|
assert!(Instant::now() < deadline, "the shadow wrote no heartbeat");
|
||||||
|
std::thread::sleep(Duration::from_millis(50));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process one: a fresh fly (the stores are empty), two sugars, 25 brain seconds.
|
||||||
|
let live = start_live(&binary, &rom, &dirs, &root.join("flysim-1.log"));
|
||||||
|
live.sugar(300);
|
||||||
|
live.run_for(8_000.0);
|
||||||
|
live.sugar(700);
|
||||||
|
live.run_for(17_000.0);
|
||||||
|
live.stop();
|
||||||
|
// Process two: restores its own latest save, a sugar, 15 brain seconds.
|
||||||
|
let live = start_live(&binary, &rom, &dirs, &root.join("flysim-2.log"));
|
||||||
|
live.run_for(5_000.0);
|
||||||
|
live.sugar(450);
|
||||||
|
live.run_for(10_000.0);
|
||||||
|
live.stop();
|
||||||
|
|
||||||
|
let files = transitions(&dirs.trace);
|
||||||
|
assert_eq!(
|
||||||
|
files.len(),
|
||||||
|
2,
|
||||||
|
"one trace file per process; the shadow's verdict: {}; divergence: {}",
|
||||||
|
verdict_of(&out),
|
||||||
|
std::fs::read_to_string(out.join("divergence.json")).unwrap_or_default()
|
||||||
|
);
|
||||||
|
let total: usize = files.iter().map(|(_, n)| n).sum();
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(600);
|
||||||
|
loop {
|
||||||
|
let v = verdict_of(&out);
|
||||||
|
if v["compared"]["transitions"].as_u64() == Some(total as u64) || handle.is_finished() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
Instant::now() < deadline,
|
||||||
|
"the shadow did not catch up: {v}"
|
||||||
|
);
|
||||||
|
std::thread::sleep(Duration::from_millis(200));
|
||||||
|
}
|
||||||
|
let passed = verdict_of(&out);
|
||||||
|
eprintln!(
|
||||||
|
"shadow after both processes: {}",
|
||||||
|
serde_json::to_string_pretty(&passed).unwrap()
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
passed["status"], "pass",
|
||||||
|
"40 brain seconds against a 30 s window"
|
||||||
|
);
|
||||||
|
assert!(passed["firstDivergence"].is_null());
|
||||||
|
|
||||||
|
// Process three runs untraced while the shadow follows: it can never be compared, so the
|
||||||
|
// shadow must fail its verdict (coverage), not keep a pass built on the traced processes.
|
||||||
|
let live = start_live_traced(&binary, &rom, &dirs, &root.join("flysim-3.log"), false);
|
||||||
|
live.run_for(3_000.0);
|
||||||
|
live.stop();
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(120);
|
||||||
|
while !handle.is_finished() {
|
||||||
|
if Instant::now() > deadline {
|
||||||
|
stop.request();
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(200));
|
||||||
|
}
|
||||||
|
let (ended, verdict) = handle.join().unwrap().expect("the shadow ran");
|
||||||
|
assert_eq!(
|
||||||
|
ended,
|
||||||
|
Ended::Diverged,
|
||||||
|
"an untraced live process fails the verdict"
|
||||||
|
);
|
||||||
|
let coverage = verdict.divergence.as_ref().expect("a divergence");
|
||||||
|
assert_eq!(coverage.kind, "coverage", "{}", coverage.detail);
|
||||||
|
assert_eq!(verdict.status, Status::Diverged);
|
||||||
|
assert_eq!(
|
||||||
|
transitions(&dirs.trace).len(),
|
||||||
|
2,
|
||||||
|
"process three left no trace"
|
||||||
|
);
|
||||||
|
assert_eq!(verdict.agreement.transitions, total as u64);
|
||||||
|
assert_eq!(verdict.segments_compared, 2);
|
||||||
|
assert!(verdict.skipped.is_empty(), "{:?}", verdict.skipped);
|
||||||
|
assert_eq!(verdict.agreement.sugar, 3);
|
||||||
|
assert_eq!(
|
||||||
|
verdict.ledger_checks, total as u64,
|
||||||
|
"a ledger digest every boundary"
|
||||||
|
);
|
||||||
|
// At least the fresh fly's startup save and both shutdown saves; the hot saves, one a wall
|
||||||
|
// second, add as many more as the box's speed gives.
|
||||||
|
assert!(
|
||||||
|
verdict.checkpoints.identical >= 3,
|
||||||
|
"live saves compared byte for byte: {:?}",
|
||||||
|
verdict.checkpoints
|
||||||
|
);
|
||||||
|
|
||||||
|
// The negative controls, each on a copy.
|
||||||
|
let empty = root.join("empty");
|
||||||
|
std::fs::create_dir_all(&empty).unwrap();
|
||||||
|
let neg = root.join("neg");
|
||||||
|
|
||||||
|
let at = tampered(&dirs.trace, &neg.join("wram/trace"), |n, v| {
|
||||||
|
(n == 700)
|
||||||
|
.then(|| v["behaviour"]["wramDigest"] = Value::String("0".repeat(64)))
|
||||||
|
.is_some()
|
||||||
|
});
|
||||||
|
let got = diverges(
|
||||||
|
&rom,
|
||||||
|
&neg.join("wram"),
|
||||||
|
&neg.join("wram/trace"),
|
||||||
|
&spool,
|
||||||
|
&empty,
|
||||||
|
);
|
||||||
|
let d = got.divergence.expect("a divergence");
|
||||||
|
assert_eq!((d.kind.as_str(), d.step), ("transition", Some(at)));
|
||||||
|
assert_eq!(d.difference.unwrap().field, "wramDigest");
|
||||||
|
assert!(!d.context.is_empty());
|
||||||
|
assert_eq!(got.status, Status::Diverged);
|
||||||
|
|
||||||
|
let at = tampered(&dirs.trace, &neg.join("ledgers/trace"), |n, v| {
|
||||||
|
(n == 900)
|
||||||
|
.then(|| v["behaviour"]["ledgersDigest"] = Value::String("0".repeat(64)))
|
||||||
|
.is_some()
|
||||||
|
});
|
||||||
|
let got = diverges(
|
||||||
|
&rom,
|
||||||
|
&neg.join("ledgers"),
|
||||||
|
&neg.join("ledgers/trace"),
|
||||||
|
&spool,
|
||||||
|
&empty,
|
||||||
|
);
|
||||||
|
let d = got.divergence.expect("a divergence");
|
||||||
|
assert_eq!((d.kind.as_str(), d.step), ("ledgers", Some(at)));
|
||||||
|
|
||||||
|
// A sugar the live loop applied, missing from the shadow's inputs: the brain differs from
|
||||||
|
// that transition on, and the comparison says where.
|
||||||
|
let at = tampered(&dirs.trace, &neg.join("sugar/trace"), |_, v| {
|
||||||
|
let had = v["behaviour"]["admissions"]
|
||||||
|
.as_array()
|
||||||
|
.is_some_and(|a| !a.is_empty());
|
||||||
|
if had {
|
||||||
|
v["behaviour"]["admissions"] = Value::Array(Vec::new());
|
||||||
|
// The admissions field itself would differ first; hold it to the tampered value.
|
||||||
|
}
|
||||||
|
had
|
||||||
|
});
|
||||||
|
let got = diverges(
|
||||||
|
&rom,
|
||||||
|
&neg.join("sugar"),
|
||||||
|
&neg.join("sugar/trace"),
|
||||||
|
&spool,
|
||||||
|
&empty,
|
||||||
|
);
|
||||||
|
let d = got.divergence.expect("a divergence");
|
||||||
|
eprintln!(
|
||||||
|
"sugar removed at step {at}: diverged at {:?} on {:?}",
|
||||||
|
d.step, d.difference
|
||||||
|
);
|
||||||
|
assert_eq!(d.kind, "transition");
|
||||||
|
assert!(d.step.is_some_and(|s| s >= at));
|
||||||
|
|
||||||
|
// A live save whose bytes differ (its rankSinceMs moved by one ms).
|
||||||
|
let copy = neg.join("save/spool");
|
||||||
|
std::fs::create_dir_all(©).unwrap();
|
||||||
|
for entry in std::fs::read_dir(&spool).unwrap().flatten() {
|
||||||
|
std::fs::copy(entry.path(), copy.join(entry.file_name())).unwrap();
|
||||||
|
}
|
||||||
|
let (first, _) = transitions(&dirs.trace).remove(0);
|
||||||
|
let text = std::fs::read_to_string(&first).unwrap();
|
||||||
|
let (generation, at) = text
|
||||||
|
.lines()
|
||||||
|
.filter_map(|l| serde_json::from_str::<Value>(l).ok())
|
||||||
|
.filter(|v| v.get("behaviour").is_some())
|
||||||
|
.find_map(|v| {
|
||||||
|
let capture = v["operational"]["captures"].as_array()?.first()?.clone();
|
||||||
|
let generation: u64 = capture["checkpointId"]
|
||||||
|
.as_str()?
|
||||||
|
.strip_prefix('g')?
|
||||||
|
.parse()
|
||||||
|
.ok()?;
|
||||||
|
let step: u64 = v["behaviour"]["step"].as_str()?.parse().ok()?;
|
||||||
|
Some((generation, step))
|
||||||
|
})
|
||||||
|
.expect("a live save during the run");
|
||||||
|
let path = copy.join(format!("g{generation}.checkpoint"));
|
||||||
|
let mut checkpoint = flysim::store::load(&path).unwrap();
|
||||||
|
checkpoint.runtime.rank_since_ms += 1.0;
|
||||||
|
std::fs::write(
|
||||||
|
&path,
|
||||||
|
flysim::store::encode(&checkpoint.agent, &checkpoint.runtime).unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let got = diverges(&rom, &neg.join("save"), &dirs.trace, ©, &empty);
|
||||||
|
let d = got.divergence.expect("a divergence");
|
||||||
|
assert_eq!((d.kind.as_str(), d.step), ("checkpoint", Some(at)));
|
||||||
|
assert!(d.detail.contains("rankSinceMs"), "{}", d.detail);
|
||||||
|
|
||||||
|
// A session-side failure is a divergence, never a skip: a candidate whose restore gate
|
||||||
|
// refuses the live startup save (another dataset profile, so another compatibility string).
|
||||||
|
let got = diverges_with(&rom, &neg.join("gate"), &dirs.trace, &spool, &empty, |c| {
|
||||||
|
c.profile = LegacyProfileKind::Production;
|
||||||
|
});
|
||||||
|
let d = got.divergence.expect("a divergence");
|
||||||
|
assert_eq!(d.kind, "boot", "{}", d.detail);
|
||||||
|
assert!(d.detail.contains("restore gate"), "{}", d.detail);
|
||||||
|
assert!(got.skipped.is_empty());
|
||||||
|
}
|
||||||
|
|
@ -54,6 +54,38 @@ pub struct Parts<'a> {
|
||||||
pub macros: Option<&'a mut MacroLayer>,
|
pub macros: Option<&'a mut MacroLayer>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The ledgers after a boundary as one canonical string: the adapter's export (its lifetime
|
||||||
|
/// ledgers), the ratchet's state and whether it holds a snapshot, and the macro layer's observable
|
||||||
|
/// state -- scene, bound channels, running macro, outcome counts, "nearer the objective".
|
||||||
|
///
|
||||||
|
/// This is the one definition both runtimes use: `FLY_TRACE_LEDGERS` digests it here, and the
|
||||||
|
/// session runtime's task (`fly-legacy-session::task::ledgers_of`) computes it from its own parts,
|
||||||
|
/// which is how the shadow run holds the executor's ledgers -- which no checkpoint carries -- to
|
||||||
|
/// the live loop's (SHADOW-01). Reading it changes nothing.
|
||||||
|
pub fn ledgers_string(
|
||||||
|
adapter: &dyn GameAdapter,
|
||||||
|
ratchet: &Ratchet,
|
||||||
|
macros: Option<&MacroLayer>,
|
||||||
|
) -> String {
|
||||||
|
let executor = match macros {
|
||||||
|
Some(layer) => serde_json::json!({
|
||||||
|
"scene": layer.scene_name(),
|
||||||
|
"bound": layer.bound_channels(),
|
||||||
|
"running": layer.running(),
|
||||||
|
"counts": format!("{:?}", layer.counts()),
|
||||||
|
"nearer": layer.nearer_the_objective(),
|
||||||
|
}),
|
||||||
|
None => serde_json::Value::Null,
|
||||||
|
};
|
||||||
|
serde_json::json!({
|
||||||
|
"adapter": adapter.export_state(),
|
||||||
|
"ratchet": serde_json::to_value(ratchet.state).expect("a ratchet state serializes"),
|
||||||
|
"slot": ratchet.snapshot.is_some(),
|
||||||
|
"executor": executor,
|
||||||
|
})
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
/// Where a host may look in, or time a phase. Every method defaults to nothing.
|
/// Where a host may look in, or time a phase. Every method defaults to nothing.
|
||||||
///
|
///
|
||||||
/// The stream's loop uses [`FrameObserver::after`] for its per-phase profile and nothing else. A
|
/// The stream's loop uses [`FrameObserver::after`] for its per-phase profile and nothing else. A
|
||||||
|
|
@ -654,6 +686,15 @@ impl LegacyFrame {
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
if let Some(trace) = self.trace.as_mut()
|
||||||
|
&& trace.wants_ledgers()
|
||||||
|
{
|
||||||
|
trace.ledgers(&ledgers_string(
|
||||||
|
&*parts.adapter,
|
||||||
|
parts.ratchet,
|
||||||
|
parts.macros.as_deref(),
|
||||||
|
));
|
||||||
|
}
|
||||||
Ok(Boundary {
|
Ok(Boundary {
|
||||||
captured: saved,
|
captured: saved,
|
||||||
rollback,
|
rollback,
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,28 @@
|
||||||
//! Wall time is never written, so a run with the periodic checkpoint intervals pushed out of the
|
//! Wall time is never written, so a run with the periodic checkpoint intervals pushed out of the
|
||||||
//! way produces the same file twice. Off by default; when off, nothing here is constructed and the
|
//! way produces the same file twice. Off by default; when off, nothing here is constructed and the
|
||||||
//! loop pays one `Option` test per hook.
|
//! loop pays one `Option` test per hook.
|
||||||
|
//!
|
||||||
|
//! **The shadow run's input (SHADOW-01).** The trace is also what the shadow run
|
||||||
|
//! (`fly-legacy-session::shadow`) follows beside the live service, so three switches serve it.
|
||||||
|
//! None changes a line's behaviour fields or anything the fly does:
|
||||||
|
//!
|
||||||
|
//! - `FLY_TRACE_DIR=<dir>` writes one file per process, `trace-<wall ms, 13 digits>-<pid>.jsonl`,
|
||||||
|
//! instead of the one `FLY_TRACE` path a restart would truncate. File names sort in start order;
|
||||||
|
//! a process's file ends where the next one begins.
|
||||||
|
//! - `FLY_TRACE_MAX_BYTES` caps one file (default 4 GiB in directory mode, none otherwise). At the
|
||||||
|
//! cap the recorder writes `{"truncated":true}` and stops; the loop runs on untouched.
|
||||||
|
//! - *A consumer must be alive* (directory mode). The shadow touches `<dir>/consumer` every 30 s.
|
||||||
|
//! A process starts no trace when that file is missing or older than
|
||||||
|
//! `FLY_TRACE_CONSUMER_STALE_SECONDS` (default 600), and a running one checks it once a minute
|
||||||
|
//! of frames and stops the same way as at the cap, with `"reason":"no-consumer"`. A dead or
|
||||||
|
//! diverged shadow therefore turns the trace off by itself, with no root action and no restart.
|
||||||
|
//! - *The directory is bounded* (directory mode). Before a process creates its file it deletes
|
||||||
|
//! the oldest `trace-*.jsonl` until the ones left and the new file's cap fit in
|
||||||
|
//! `FLY_TRACE_DIR_MAX_BYTES` (default 8 GiB). The shadow deletes each file once compared.
|
||||||
|
//! - `FLY_TRACE_LEDGERS=<n>` adds `ledgersDigest` to every transition whose `step` is a multiple
|
||||||
|
//! of `n`: the SHA-256 of [`crate::frame::ledgers_string`] after the boundary (adapter export,
|
||||||
|
//! ratchet, slot, executor scene/bound/running/counts/nearer). `1` is every transition. The
|
||||||
|
//! header then carries `ledgersEvery`.
|
||||||
|
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
use std::io::{BufWriter, Write};
|
use std::io::{BufWriter, Write};
|
||||||
|
|
@ -48,6 +70,79 @@ pub const FORMAT: &str = "flysim-legacy-frame-trace-v1";
|
||||||
/// The environment variable that turns the trace on.
|
/// The environment variable that turns the trace on.
|
||||||
pub const ENV: &str = "FLY_TRACE";
|
pub const ENV: &str = "FLY_TRACE";
|
||||||
|
|
||||||
|
/// One file per process in this directory (SHADOW-01).
|
||||||
|
pub const DIR_ENV: &str = "FLY_TRACE_DIR";
|
||||||
|
|
||||||
|
/// The per-file byte cap.
|
||||||
|
pub const MAX_BYTES_ENV: &str = "FLY_TRACE_MAX_BYTES";
|
||||||
|
|
||||||
|
/// The ledger digest's period in transitions.
|
||||||
|
pub const LEDGERS_ENV: &str = "FLY_TRACE_LEDGERS";
|
||||||
|
|
||||||
|
/// The default per-file cap in directory mode: about 23 hours of stream.
|
||||||
|
pub const DEFAULT_DIR_MAX_BYTES: u64 = 4 << 30;
|
||||||
|
|
||||||
|
/// The consumer's heartbeat file in [`DIR_ENV`] mode.
|
||||||
|
pub const CONSUMER_FILE: &str = "consumer";
|
||||||
|
|
||||||
|
/// How old the heartbeat may be (seconds).
|
||||||
|
pub const CONSUMER_STALE_ENV: &str = "FLY_TRACE_CONSUMER_STALE_SECONDS";
|
||||||
|
pub const DEFAULT_CONSUMER_STALE_SECONDS: u64 = 600;
|
||||||
|
|
||||||
|
/// The cap over every trace file in the directory.
|
||||||
|
pub const DIR_MAX_BYTES_ENV: &str = "FLY_TRACE_DIR_MAX_BYTES";
|
||||||
|
pub const DEFAULT_DIR_TOTAL_BYTES: u64 = 8 << 30;
|
||||||
|
|
||||||
|
/// Transitions between two heartbeat checks: about a minute of frames.
|
||||||
|
const CONSUMER_CHECK_EVERY: u64 = 3_600;
|
||||||
|
|
||||||
|
/// Whether `dir`'s consumer heartbeat is at most `stale` old.
|
||||||
|
pub fn consumer_alive(dir: &Path, stale: std::time::Duration) -> bool {
|
||||||
|
std::fs::metadata(dir.join(CONSUMER_FILE))
|
||||||
|
.and_then(|m| m.modified())
|
||||||
|
.ok()
|
||||||
|
// A heartbeat dated ahead of this clock (a clock stepped back) is fresh, not missing.
|
||||||
|
.map(|t| {
|
||||||
|
std::time::SystemTime::now()
|
||||||
|
.duration_since(t)
|
||||||
|
.unwrap_or_default()
|
||||||
|
})
|
||||||
|
.is_some_and(|age| age <= stale)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deletes the oldest trace files in `dir` until those left total at most `keep` bytes.
|
||||||
|
pub fn prune_dir(dir: &Path, keep: u64) {
|
||||||
|
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let mut files: Vec<(std::path::PathBuf, u64)> = entries
|
||||||
|
.flatten()
|
||||||
|
.filter(|e| {
|
||||||
|
e.file_name()
|
||||||
|
.to_str()
|
||||||
|
.is_some_and(|n| n.starts_with("trace-") && n.ends_with(".jsonl"))
|
||||||
|
})
|
||||||
|
.filter_map(|e| Some((e.path(), e.metadata().ok()?.len())))
|
||||||
|
.collect();
|
||||||
|
files.sort();
|
||||||
|
let mut total: u64 = files.iter().map(|(_, len)| len).sum();
|
||||||
|
for (path, len) in files {
|
||||||
|
if total <= keep {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if std::fs::remove_file(&path).is_ok() {
|
||||||
|
tracing::warn!(path = %path.display(), "removed an old frame trace to bound its directory");
|
||||||
|
total -= len;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The per-process file name in [`DIR_ENV`] mode: start wall time (13 digits, so names sort in
|
||||||
|
/// start order) and pid.
|
||||||
|
pub fn dir_file_name(wall_ms: u64, pid: u32) -> String {
|
||||||
|
format!("trace-{wall_ms:013}-{pid}.jsonl")
|
||||||
|
}
|
||||||
|
|
||||||
/// The ratchet's one slot, as the legacy composition declares it (legacy-gameboy-v1 section 9).
|
/// The ratchet's one slot, as the legacy composition declares it (legacy-gameboy-v1 section 9).
|
||||||
pub const SLOT: &str = "best";
|
pub const SLOT: &str = "best";
|
||||||
|
|
||||||
|
|
@ -122,6 +217,7 @@ struct Record {
|
||||||
rank: u32,
|
rank: u32,
|
||||||
boundary_actions: Vec<Value>,
|
boundary_actions: Vec<Value>,
|
||||||
captures: Vec<Value>,
|
captures: Vec<Value>,
|
||||||
|
ledgers: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The recorder. The loop calls it at fixed points of the frame order; it holds the transition
|
/// The recorder. The loop calls it at fixed points of the frame order; it holds the transition
|
||||||
|
|
@ -137,21 +233,100 @@ pub struct FrameTrace {
|
||||||
admissions: Vec<Value>,
|
admissions: Vec<Value>,
|
||||||
/// Brain clock before this transition's ticks, the lower edge of its spike window.
|
/// Brain clock before this transition's ticks, the lower edge of its spike window.
|
||||||
ms_before: f64,
|
ms_before: f64,
|
||||||
|
/// Bytes written so far, and the cap (`FLY_TRACE_MAX_BYTES`).
|
||||||
|
written: u64,
|
||||||
|
max_bytes: Option<u64>,
|
||||||
|
/// Set once the cap was reached: nothing more is written.
|
||||||
|
stopped: bool,
|
||||||
|
/// `FLY_TRACE_LEDGERS`: a ledger digest every this many transitions.
|
||||||
|
ledgers_every: Option<u64>,
|
||||||
|
/// Directory mode: the directory whose consumer heartbeat keeps the trace on, and its limit.
|
||||||
|
consumer: Option<(std::path::PathBuf, std::time::Duration)>,
|
||||||
|
transitions: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FrameTrace {
|
impl FrameTrace {
|
||||||
/// `FLY_TRACE`, if it is set and non-empty. A path that cannot be created is an error rather
|
/// `FLY_TRACE`, if it is set and non-empty. A path that cannot be created is an error rather
|
||||||
/// than a silent run without the trace that was asked for.
|
/// than a silent run without the trace that was asked for.
|
||||||
|
///
|
||||||
|
/// `FLY_TRACE_DIR` (one file per process) wins over `FLY_TRACE`; `FLY_TRACE_MAX_BYTES` and
|
||||||
|
/// `FLY_TRACE_LEDGERS` apply to either.
|
||||||
pub fn from_env() -> std::io::Result<Option<Self>> {
|
pub fn from_env() -> std::io::Result<Option<Self>> {
|
||||||
match std::env::var_os(ENV) {
|
let var = |name: &str| std::env::var_os(name).filter(|value| !value.is_empty());
|
||||||
Some(path) if !path.is_empty() => Self::create(Path::new(&path)).map(Some),
|
let number = |name: &str| -> std::io::Result<Option<u64>> {
|
||||||
_ => Ok(None),
|
match var(name) {
|
||||||
|
None => Ok(None),
|
||||||
|
Some(value) => value
|
||||||
|
.to_str()
|
||||||
|
.and_then(|v| v.trim().parse::<u64>().ok())
|
||||||
|
.filter(|v| *v > 0)
|
||||||
|
.map(Some)
|
||||||
|
.ok_or_else(|| {
|
||||||
|
std::io::Error::new(
|
||||||
|
std::io::ErrorKind::InvalidInput,
|
||||||
|
format!("{name} must be a positive integer"),
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let ledgers_every = number(LEDGERS_ENV)?;
|
||||||
|
let max_bytes = number(MAX_BYTES_ENV)?;
|
||||||
|
if let Some(dir) = var(DIR_ENV) {
|
||||||
|
let dir = Path::new(&dir);
|
||||||
|
let stale = std::time::Duration::from_secs(
|
||||||
|
number(CONSUMER_STALE_ENV)?.unwrap_or(DEFAULT_CONSUMER_STALE_SECONDS),
|
||||||
|
);
|
||||||
|
if !consumer_alive(dir, stale) {
|
||||||
|
tracing::warn!(
|
||||||
|
dir = %dir.display(),
|
||||||
|
"FLY_TRACE_DIR is set but no consumer is alive there: no frame trace this run"
|
||||||
|
);
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
let cap = max_bytes.unwrap_or(DEFAULT_DIR_MAX_BYTES);
|
||||||
|
let total = number(DIR_MAX_BYTES_ENV)?.unwrap_or(DEFAULT_DIR_TOTAL_BYTES);
|
||||||
|
prune_dir(dir, total.saturating_sub(cap));
|
||||||
|
let wall_ms = std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.map_or(0, |d| d.as_millis() as u64);
|
||||||
|
let path = dir.join(dir_file_name(wall_ms, std::process::id()));
|
||||||
|
// A trace the live service cannot create (a full disk, a missing directory, its
|
||||||
|
// permissions) never stops the live fly from starting: it runs untraced, and the
|
||||||
|
// shadow, which checks every boot header in the sugar journal against the trace
|
||||||
|
// files, reports that process as a coverage gap and fails its verdict.
|
||||||
|
let mut trace = match Self::create_with(&path, Some(cap), ledgers_every) {
|
||||||
|
Ok(trace) => trace,
|
||||||
|
Err(error) => {
|
||||||
|
tracing::error!(%error, path = %path.display(), "could not create the frame trace: this run is untraced");
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
trace.consumer = Some((dir.to_owned(), stale));
|
||||||
|
return Ok(Some(trace));
|
||||||
|
}
|
||||||
|
match var(ENV) {
|
||||||
|
Some(path) => Self::create_with(Path::new(&path), max_bytes, ledgers_every).map(Some),
|
||||||
|
None => Ok(None),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn create(path: &Path) -> std::io::Result<Self> {
|
pub fn create(path: &Path) -> std::io::Result<Self> {
|
||||||
|
Self::create_with(path, None, None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A trace with a byte cap and a ledger digest period (see the module notes).
|
||||||
|
pub fn create_with(
|
||||||
|
path: &Path,
|
||||||
|
max_bytes: Option<u64>,
|
||||||
|
ledgers_every: Option<u64>,
|
||||||
|
) -> std::io::Result<Self> {
|
||||||
let mut out = BufWriter::with_capacity(1 << 20, File::create(path)?);
|
let mut out = BufWriter::with_capacity(1 << 20, File::create(path)?);
|
||||||
writeln!(out, "{}", json!({ "format": FORMAT }))?;
|
let header = match ledgers_every {
|
||||||
|
Some(every) => json!({ "format": FORMAT, "ledgersEvery": every }),
|
||||||
|
None => json!({ "format": FORMAT }),
|
||||||
|
};
|
||||||
|
let header = header.to_string();
|
||||||
|
writeln!(out, "{header}")?;
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
out,
|
out,
|
||||||
initial: Vec::new(),
|
initial: Vec::new(),
|
||||||
|
|
@ -159,13 +334,63 @@ impl FrameTrace {
|
||||||
open: None,
|
open: None,
|
||||||
admissions: Vec::new(),
|
admissions: Vec::new(),
|
||||||
ms_before: 0.0,
|
ms_before: 0.0,
|
||||||
|
written: header.len() as u64 + 1,
|
||||||
|
max_bytes,
|
||||||
|
stopped: false,
|
||||||
|
ledgers_every,
|
||||||
|
consumer: None,
|
||||||
|
transitions: 0,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write(&mut self, value: &Value) {
|
/// Stops the trace: one marker line, then nothing more. The loop is unaffected.
|
||||||
if let Err(error) = writeln!(self.out, "{value}") {
|
fn stop(&mut self, reason: &str) {
|
||||||
|
if self.stopped {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.stopped = true;
|
||||||
|
if let Err(error) = writeln!(
|
||||||
|
self.out,
|
||||||
|
"{}",
|
||||||
|
json!({ "truncated": true, "reason": reason })
|
||||||
|
) {
|
||||||
tracing::warn!(%error, "could not write the frame trace");
|
tracing::warn!(%error, "could not write the frame trace");
|
||||||
}
|
}
|
||||||
|
let _ = self.out.flush();
|
||||||
|
tracing::warn!(reason, "the frame trace stopped");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write(&mut self, value: &Value) {
|
||||||
|
if self.stopped {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let line = value.to_string();
|
||||||
|
let len = line.len() as u64 + 1;
|
||||||
|
if let Some(cap) = self.max_bytes
|
||||||
|
&& self.written + len > cap
|
||||||
|
{
|
||||||
|
self.stop("byte-cap");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.written += len;
|
||||||
|
if let Err(error) = writeln!(self.out, "{line}") {
|
||||||
|
tracing::warn!(%error, "could not write the frame trace");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the open transition takes a ledger digest (`FLY_TRACE_LEDGERS`).
|
||||||
|
pub fn wants_ledgers(&self) -> bool {
|
||||||
|
match (self.ledgers_every, self.open.as_ref()) {
|
||||||
|
(Some(every), Some(record)) => !self.stopped && record.step % every == 0,
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ledgers after the boundary, as [`crate::frame::ledgers_string`] writes them.
|
||||||
|
pub fn ledgers(&mut self, ledgers: &str) {
|
||||||
|
if let Some(record) = self.open.as_mut() {
|
||||||
|
record.ledgers = Some(sha256_hex(ledgers.as_bytes()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sugar admitted at the top of the frame, before the brain ticks.
|
/// Sugar admitted at the top of the frame, before the brain ticks.
|
||||||
|
|
@ -198,6 +423,15 @@ impl FrameTrace {
|
||||||
/// Transition `step -> step + 1` begins: the previous one is complete.
|
/// Transition `step -> step + 1` begins: the previous one is complete.
|
||||||
pub fn begin(&mut self, step: u64, ms_before: f64) {
|
pub fn begin(&mut self, step: u64, ms_before: f64) {
|
||||||
self.flush_open();
|
self.flush_open();
|
||||||
|
self.transitions += 1;
|
||||||
|
let consumer_gone = self.transitions.is_multiple_of(CONSUMER_CHECK_EVERY)
|
||||||
|
&& self
|
||||||
|
.consumer
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|(dir, stale)| !consumer_alive(dir, *stale));
|
||||||
|
if consumer_gone {
|
||||||
|
self.stop("no-consumer");
|
||||||
|
}
|
||||||
if let Some(start) = self.initial_step.take() {
|
if let Some(start) = self.initial_step.take() {
|
||||||
let initial = std::mem::take(&mut self.initial);
|
let initial = std::mem::take(&mut self.initial);
|
||||||
self.write(&json!({
|
self.write(&json!({
|
||||||
|
|
@ -309,7 +543,7 @@ impl FrameTrace {
|
||||||
let Some(record) = self.open.take() else {
|
let Some(record) = self.open.take() else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
let line = json!({
|
let mut line = json!({
|
||||||
"behaviour": {
|
"behaviour": {
|
||||||
"step": record.step.to_string(),
|
"step": record.step.to_string(),
|
||||||
"admissions": record.admissions,
|
"admissions": record.admissions,
|
||||||
|
|
@ -331,6 +565,9 @@ impl FrameTrace {
|
||||||
},
|
},
|
||||||
"operational": { "captures": record.captures },
|
"operational": { "captures": record.captures },
|
||||||
});
|
});
|
||||||
|
if let Some(digest) = record.ledgers {
|
||||||
|
line["behaviour"]["ledgersDigest"] = Value::String(digest);
|
||||||
|
}
|
||||||
self.write(&line);
|
self.write(&line);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -353,6 +590,122 @@ impl Drop for FrameTrace {
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
fn lines(path: &Path) -> Vec<Value> {
|
||||||
|
std::fs::read_to_string(path)
|
||||||
|
.unwrap()
|
||||||
|
.lines()
|
||||||
|
.map(|l| serde_json::from_str(l).unwrap())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_directory_is_bounded_and_needs_a_live_consumer() {
|
||||||
|
let dir = std::env::temp_dir().join(format!("fly-trace-dir-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
let minute = std::time::Duration::from_secs(60);
|
||||||
|
assert!(!consumer_alive(&dir, minute), "no heartbeat file");
|
||||||
|
std::fs::write(dir.join(CONSUMER_FILE), b"x").unwrap();
|
||||||
|
assert!(consumer_alive(&dir, minute));
|
||||||
|
for (name, len) in [
|
||||||
|
("trace-1-1.jsonl", 100),
|
||||||
|
("trace-2-1.jsonl", 100),
|
||||||
|
("trace-3-1.jsonl", 100),
|
||||||
|
] {
|
||||||
|
std::fs::write(dir.join(name), vec![b'x'; len]).unwrap();
|
||||||
|
}
|
||||||
|
std::fs::write(dir.join("other.txt"), vec![b'x'; 1000]).unwrap();
|
||||||
|
prune_dir(&dir, 150);
|
||||||
|
assert!(!dir.join("trace-1-1.jsonl").exists());
|
||||||
|
assert!(!dir.join("trace-2-1.jsonl").exists());
|
||||||
|
assert!(dir.join("trace-3-1.jsonl").exists());
|
||||||
|
assert!(
|
||||||
|
dir.join("other.txt").exists(),
|
||||||
|
"only trace files are pruned"
|
||||||
|
);
|
||||||
|
std::fs::remove_dir_all(&dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_running_trace_stops_when_its_consumer_goes_away() {
|
||||||
|
let dir = std::env::temp_dir().join(format!("fly-trace-gone-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
std::fs::write(dir.join(CONSUMER_FILE), b"x").unwrap();
|
||||||
|
let path = dir.join("t.jsonl");
|
||||||
|
let mut trace = FrameTrace::create_with(&path, None, None).unwrap();
|
||||||
|
trace.consumer = Some((dir.clone(), std::time::Duration::from_secs(600)));
|
||||||
|
for step in 0..CONSUMER_CHECK_EVERY {
|
||||||
|
trace.begin(step, 0.0);
|
||||||
|
}
|
||||||
|
assert!(!trace.stopped, "a live consumer keeps it on");
|
||||||
|
std::fs::remove_file(dir.join(CONSUMER_FILE)).unwrap();
|
||||||
|
for step in CONSUMER_CHECK_EVERY..3 * CONSUMER_CHECK_EVERY {
|
||||||
|
trace.begin(step, 0.0);
|
||||||
|
}
|
||||||
|
trace.finish();
|
||||||
|
drop(trace);
|
||||||
|
let all = lines(&path);
|
||||||
|
assert_eq!(all.last().unwrap()["reason"], "no-consumer");
|
||||||
|
assert!(all.len() < (2 * CONSUMER_CHECK_EVERY) as usize + 3);
|
||||||
|
std::fs::remove_dir_all(&dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn directory_files_sort_in_start_order() {
|
||||||
|
assert!(dir_file_name(999, 70_000) < dir_file_name(1000, 5));
|
||||||
|
assert_eq!(dir_file_name(1, 2), "trace-0000000000001-2.jsonl");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_byte_cap_ends_the_file_with_a_marker_and_nothing_after() {
|
||||||
|
let dir = std::env::temp_dir().join(format!("fly-trace-cap-{}", std::process::id()));
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
let path = dir.join("t.jsonl");
|
||||||
|
let mut trace = FrameTrace::create_with(&path, Some(1500), None).unwrap();
|
||||||
|
for step in 0..40 {
|
||||||
|
trace.begin(step, 0.0);
|
||||||
|
}
|
||||||
|
trace.finish();
|
||||||
|
drop(trace);
|
||||||
|
let all = lines(&path);
|
||||||
|
assert_eq!(all.first().unwrap()["format"], FORMAT);
|
||||||
|
assert_eq!(all.last().unwrap()["truncated"], true);
|
||||||
|
assert_eq!(all.last().unwrap()["reason"], "byte-cap");
|
||||||
|
assert!(all.len() > 2 && all.len() < 40);
|
||||||
|
let size = std::fs::metadata(&path).unwrap().len();
|
||||||
|
assert!(size <= 1500 + 20, "{size}");
|
||||||
|
std::fs::remove_dir_all(&dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ledger_digests_every_nth_step() {
|
||||||
|
let dir = std::env::temp_dir().join(format!("fly-trace-ledgers-{}", std::process::id()));
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
let path = dir.join("t.jsonl");
|
||||||
|
let mut trace = FrameTrace::create_with(&path, None, Some(2)).unwrap();
|
||||||
|
for step in 10..14 {
|
||||||
|
trace.begin(step, 0.0);
|
||||||
|
if trace.wants_ledgers() {
|
||||||
|
trace.ledgers("the ledgers");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
trace.finish();
|
||||||
|
drop(trace);
|
||||||
|
let all = lines(&path);
|
||||||
|
assert_eq!(all[0]["ledgersEvery"], 2);
|
||||||
|
let digests: Vec<bool> = all[1..]
|
||||||
|
.iter()
|
||||||
|
.map(|l| l["behaviour"].get("ledgersDigest").is_some())
|
||||||
|
.collect();
|
||||||
|
assert_eq!(digests, vec![true, false, true, false]);
|
||||||
|
assert_eq!(
|
||||||
|
all[1]["behaviour"]["ledgersDigest"],
|
||||||
|
sha256_hex(b"the ledgers").as_str()
|
||||||
|
);
|
||||||
|
std::fs::remove_dir_all(&dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn every_legacy_remainder_is_exact_nanoseconds() {
|
fn every_legacy_remainder_is_exact_nanoseconds() {
|
||||||
// The first twelve legacy frames' remainders, from the clock the fixture records.
|
// The first twelve legacy frames' remainders, from the clock the fixture records.
|
||||||
|
|
|
||||||
169
tools/shadow-rehearsal.sh
Executable file
169
tools/shadow-rehearsal.sh
Executable file
|
|
@ -0,0 +1,169 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# tools/shadow-rehearsal.sh -- SHADOW-01's offline rehearsal: the real `flysim` service and the
|
||||||
|
# real `fly-shadow` side by side on one machine, exactly as the release container runs them, from
|
||||||
|
# one FLYSIM01 checkpoint, with sugar posted to the control API and service restarts.
|
||||||
|
#
|
||||||
|
# FLY_ROM=<cartridge> tools/shadow-rehearsal.sh --checkpoint FILE [options]
|
||||||
|
#
|
||||||
|
# Options:
|
||||||
|
# --checkpoint FILE the live checkpoint the fly starts from (required)
|
||||||
|
# --brain-minutes N stop the live service after N brain minutes (default 30)
|
||||||
|
# --restart-at LIST restart flysim at these brain minutes, comma separated (default: none)
|
||||||
|
# --sugar-every S POST /stimulate about every S wall seconds (default 20; 0 = never)
|
||||||
|
# --speed X flysim loop.speed (default 0 = unthrottled; 1 = real time)
|
||||||
|
# --live-threads N flysim RAYON_NUM_THREADS (default 3, the release value)
|
||||||
|
# --mode M --threads N the shadow's execution mode and agent threads (in-process, 2)
|
||||||
|
# --ledgers N FLY_TRACE_LEDGERS (default 1: every boundary)
|
||||||
|
# --out DIR where everything goes (default: a new temporary directory)
|
||||||
|
# --bin DIR flysim, fly-shadow (and fly-session for --mode process); default
|
||||||
|
# $CARGO_TARGET_DIR/release or services/flysim/target/release
|
||||||
|
# --port N first of three local ports (default 17400)
|
||||||
|
# --guard S the shadow's --lag-guard-margin against the live metrics (0.05, as
|
||||||
|
# on the container; 0 disables)
|
||||||
|
#
|
||||||
|
# Environment: FLY_ROM (required); FLYSIM_PATHS_DATASET (default data/fafb-v783);
|
||||||
|
# FLY_ACCEPT_ADAPTERS passes through. Nothing here touches a host: every path is under --out.
|
||||||
|
#
|
||||||
|
# Result: <out>/shadow/verdict.json (and divergence.json on a divergence) and <out>/summary.txt:
|
||||||
|
# live and shadow CPU seconds per wall second, live frames per wall second, the verdict.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
die() { echo "shadow-rehearsal: $*" >&2; exit 2; }
|
||||||
|
repo="$(cd "$(dirname "$0")/.." && pwd)"
|
||||||
|
checkpoint=""; brain_minutes=30; restart_at=""; sugar_every=20; speed=0; live_threads=3
|
||||||
|
mode=in-process; threads=2; ledgers=1; out=""; bin=""; port=17400; guard=0.05
|
||||||
|
while [ $# -gt 0 ]; do
|
||||||
|
case "$1" in
|
||||||
|
--checkpoint) checkpoint="$2"; shift 2 ;;
|
||||||
|
--brain-minutes) brain_minutes="$2"; shift 2 ;;
|
||||||
|
--restart-at) restart_at="$2"; shift 2 ;;
|
||||||
|
--sugar-every) sugar_every="$2"; shift 2 ;;
|
||||||
|
--speed) speed="$2"; shift 2 ;;
|
||||||
|
--live-threads) live_threads="$2"; shift 2 ;;
|
||||||
|
--mode) mode="$2"; shift 2 ;;
|
||||||
|
--threads) threads="$2"; shift 2 ;;
|
||||||
|
--ledgers) ledgers="$2"; shift 2 ;;
|
||||||
|
--out) out="$2"; shift 2 ;;
|
||||||
|
--bin) bin="$2"; shift 2 ;;
|
||||||
|
--port) port="$2"; shift 2 ;;
|
||||||
|
--guard) guard="$2"; shift 2 ;;
|
||||||
|
*) die "unknown option $1" ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
[ -n "$checkpoint" ] && [ -f "$checkpoint" ] || die "--checkpoint FILE is required"
|
||||||
|
: "${FLY_ROM:?FLY_ROM must name the cartridge}"
|
||||||
|
[ -n "$bin" ] || bin="${CARGO_TARGET_DIR:-$repo/services/flysim/target}/release"
|
||||||
|
for b in flysim fly-shadow; do [ -x "$bin/$b" ] || die "no $bin/$b (cargo build --release --bins)"; done
|
||||||
|
dataset="${FLYSIM_PATHS_DATASET:-$repo/data/fafb-v783}"
|
||||||
|
[ -n "$out" ] || out="$(mktemp -d "${TMPDIR:-/tmp}/shadow-rehearsal.XXXXXX")"
|
||||||
|
live="$out/live"; shadow_dir="$out/shadow"
|
||||||
|
mkdir -p "$live/hot" "$live/durable" "$live/trace" "$shadow_dir"
|
||||||
|
cp "$checkpoint" "$live/durable/1.checkpoint"
|
||||||
|
printf '{"generation":1,"latest":1,"previous":null,"archives":{}}\n' > "$live/durable/manifest.json"
|
||||||
|
|
||||||
|
# The live service's configuration; the shadow reads the same (Config::load, as on the container).
|
||||||
|
export FLYSIM_PATHS_ROM="$FLY_ROM" FLYSIM_PATHS_DATASET="$dataset" FLYSIM_LOOP_GAME=pokemon-red
|
||||||
|
export FLY_STATE="$live/durable" FLY_STATE_HOT="$live/hot" FLY_MACRO_MODE=macros
|
||||||
|
export FLY_FEED_BIND="127.0.0.1:$port" FLY_CONTROL_BIND="127.0.0.1:$((port + 1))"
|
||||||
|
export FLY_METRICS_ADDR="127.0.0.1:$((port + 2))" FLY_CHAT_ENABLED=false
|
||||||
|
export FLYSIM_LOOP_SPEED="$speed"
|
||||||
|
control="http://127.0.0.1:$((port + 1))"
|
||||||
|
|
||||||
|
cpu_seconds() { # utime+stime of a pid and its children that have been reaped, in seconds
|
||||||
|
awk -v hz="$(getconf CLK_TCK)" '{ print ($14 + $15 + $16 + $17) / hz }' "/proc/$1/stat" 2>/dev/null || echo 0
|
||||||
|
}
|
||||||
|
status_ms() { # brain ms of a running (not booting) service, else empty
|
||||||
|
curl -fsS --max-time 2 "$control/status" 2>/dev/null | python3 -c '
|
||||||
|
import json, sys
|
||||||
|
v = json.load(sys.stdin)
|
||||||
|
if v.get("status") == "running" and v.get("brainMs"):
|
||||||
|
print(int(v["brainMs"]))' 2>/dev/null || true; }
|
||||||
|
|
||||||
|
live_pid=""; live_n=0; live_cpu=0
|
||||||
|
start_live() {
|
||||||
|
live_n=$((live_n + 1))
|
||||||
|
RAYON_NUM_THREADS="$live_threads" FLY_TRACE_DIR="$live/trace" FLY_TRACE_LEDGERS="$ledgers" \
|
||||||
|
"$bin/flysim" > "$live/flysim-$live_n.log" 2>&1 &
|
||||||
|
live_pid=$!
|
||||||
|
for _ in $(seq 1 600); do
|
||||||
|
[ -n "$(status_ms)" ] && return 0
|
||||||
|
kill -0 "$live_pid" 2>/dev/null || { tail -20 "$live/flysim-$live_n.log" >&2; die "flysim exited"; }
|
||||||
|
sleep 0.5
|
||||||
|
done
|
||||||
|
die "flysim did not come up"
|
||||||
|
}
|
||||||
|
stop_live() {
|
||||||
|
local c; c=$(cpu_seconds "$live_pid"); live_cpu=$(awk -v a="$live_cpu" -v b="$c" 'BEGIN{print a+b}')
|
||||||
|
kill -TERM "$live_pid"; wait "$live_pid" || true
|
||||||
|
}
|
||||||
|
|
||||||
|
wall0=$(date +%s.%N)
|
||||||
|
"$bin/fly-shadow" run --out "$shadow_dir" --trace-dir "$live/trace" --all-files --keep-traces --keep-spool \
|
||||||
|
--mode "$mode" --threads "$threads" --lag-guard-margin "$guard" \
|
||||||
|
--required-brain-seconds "$((brain_minutes * 60))" > "$out/shadow.log" 2>&1 &
|
||||||
|
shadow_pid=$!
|
||||||
|
# flysim starts no trace without the shadow's heartbeat.
|
||||||
|
for _ in $(seq 1 120); do [ -f "$live/trace/consumer" ] && break; sleep 0.5; done
|
||||||
|
[ -f "$live/trace/consumer" ] || die "fly-shadow wrote no heartbeat"
|
||||||
|
start_live
|
||||||
|
echo "shadow-rehearsal: $out (flysim $live_pid, fly-shadow $shadow_pid)"
|
||||||
|
|
||||||
|
brain_done=0; seg_start="$(status_ms)"; seg_last="$seg_start"; next_sugar=$(date +%s); sugar_posted=0
|
||||||
|
IFS=',' read -r -a restarts <<< "$restart_at"
|
||||||
|
restart_i=0
|
||||||
|
while :; do
|
||||||
|
sleep 1
|
||||||
|
ms="$(status_ms)"; [ -n "$ms" ] && seg_last="$ms"
|
||||||
|
elapsed=$(( brain_done + seg_last - seg_start ))
|
||||||
|
kill -0 "$shadow_pid" 2>/dev/null || { echo "shadow-rehearsal: fly-shadow exited early" >&2; break; }
|
||||||
|
if [ "$sugar_every" != 0 ] && [ "$(date +%s)" -ge "$next_sugar" ]; then
|
||||||
|
duration=$(( 200 + RANDOM % 800 ))
|
||||||
|
code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 2 -X POST "$control/stimulate" \
|
||||||
|
-H 'content-type: application/json' \
|
||||||
|
-d "{\"durationMs\":$duration,\"by\":\"rehearsal\",\"source\":\"operator\"}" || true)
|
||||||
|
case "$code" in 2*) sugar_posted=$((sugar_posted + 1)) ;; esac
|
||||||
|
next_sugar=$(( $(date +%s) + sugar_every / 2 + RANDOM % (sugar_every + 1) ))
|
||||||
|
fi
|
||||||
|
if [ "$restart_i" -lt "${#restarts[@]}" ] && [ -n "${restarts[$restart_i]}" ] \
|
||||||
|
&& [ "$elapsed" -ge $(( ${restarts[$restart_i]} * 60000 )) ]; then
|
||||||
|
echo "shadow-rehearsal: restarting flysim at brain $((elapsed / 1000)) s"
|
||||||
|
stop_live; brain_done=$elapsed
|
||||||
|
start_live; seg_start="$(status_ms)"; seg_last="$seg_start"
|
||||||
|
restart_i=$((restart_i + 1))
|
||||||
|
fi
|
||||||
|
[ "$elapsed" -ge $(( brain_minutes * 60000 )) ] && break
|
||||||
|
done
|
||||||
|
stop_live
|
||||||
|
live_wall=$(awk -v a="$wall0" -v b="$(date +%s.%N)" 'BEGIN{print b-a}')
|
||||||
|
total=$(cat "$live"/trace/trace-*.jsonl | grep -c '"behaviour"' || true)
|
||||||
|
echo "shadow-rehearsal: live stopped after $((elapsed / 1000)) brain s, $total transitions traced; waiting for the shadow"
|
||||||
|
while kill -0 "$shadow_pid" 2>/dev/null; do
|
||||||
|
compared=$(python3 -c 'import json,sys; v=json.load(open(sys.argv[1])); print(v["compared"]["transitions"] + sum(s["transitionsCompared"] for s in v["skipped"]))' "$shadow_dir/verdict.json" 2>/dev/null || echo 0)
|
||||||
|
[ "$compared" -ge "$total" ] && break
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
shadow_cpu=$(cpu_seconds "$shadow_pid")
|
||||||
|
shadow_wall=$(awk -v a="$wall0" -v b="$(date +%s.%N)" 'BEGIN{print b-a}')
|
||||||
|
kill -TERM "$shadow_pid" 2>/dev/null || true
|
||||||
|
rc=0; wait "$shadow_pid" || rc=$?
|
||||||
|
{
|
||||||
|
echo "checkpoint: $(basename "$checkpoint")"
|
||||||
|
echo "live: $live_n process(es), $total transitions, $((elapsed / 1000)) brain s, ${live_wall%.*} wall s, sugar posted $sugar_posted"
|
||||||
|
awk -v c="$live_cpu" -v w="$live_wall" -v t="$total" 'BEGIN{printf "live: %.2f cores, %.1f frames per wall second\n", c/w, t/w}'
|
||||||
|
awk -v c="$shadow_cpu" -v w="$shadow_wall" -v t="$total" 'BEGIN{printf "shadow (%s, %s threads): %.2f cores over %.0f wall s, %.1f frames per wall second\n", "'"$mode"'", "'"$threads"'", c/w, w, t/w}'
|
||||||
|
echo "shadow exit: $rc"
|
||||||
|
python3 - "$shadow_dir/verdict.json" <<'PY'
|
||||||
|
import json, sys
|
||||||
|
v = json.load(open(sys.argv[1]))
|
||||||
|
c = v["compared"]
|
||||||
|
print(f"verdict: {v['status']} ({v['reason']})")
|
||||||
|
print(f"compared: {c['transitions']} transitions, {c['brainSeconds']} brain s, {c['segments']} segments, "
|
||||||
|
f"{c['sugar']} sugar, {c['rewards']} rewards {c['rewardKinds']}, {c['macroEvents']} macro events, "
|
||||||
|
f"{c['slotSaves']} slot saves, {c['rollbacks']} rollbacks, {c['ledgerChecks']} ledger checks, "
|
||||||
|
f"checkpoints {c['checkpoints']}")
|
||||||
|
print(f"skipped: {v['skipped']}")
|
||||||
|
print(f"cost: {v['cost']}")
|
||||||
|
if v["firstDivergence"]:
|
||||||
|
print(f"FIRST DIVERGENCE: {json.dumps(v['firstDivergence'])}")
|
||||||
|
PY
|
||||||
|
} | tee "$out/summary.txt"
|
||||||
Loading…
Add table
Reference in a new issue