Merge port/task-01 (TASK-01) into v0.7.0 release candidate
This commit is contained in:
commit
6b77b87991
33 changed files with 6926 additions and 163 deletions
|
|
@ -344,6 +344,103 @@ CUT-01 shadow need.
|
||||||
the executor over `ImageReader::new(&O[k], &cartridge)` in Phase B and over O[k+1] in Phase C,
|
the executor over `ImageReader::new(&O[k], &cartridge)` in Phase B and over O[k+1] in Phase C,
|
||||||
retaining O[k] until then. The `Cartridge` comes from `Cartridge::verified(rom, contentDigest)`.
|
retaining O[k] until then. The `Cartridge` comes from `Cartridge::verified(rom, contentDigest)`.
|
||||||
|
|
||||||
|
### TASK-01 — The `pokered-macros-v1` task and executor (port slice)
|
||||||
|
|
||||||
|
**2026-09-29: built** on `port/task-01` off `port/integration` (main v0.6.5 + AGENT-01 + MEM-01 +
|
||||||
|
ENV-01) and awaiting review. It changes no live behaviour: `flysim` is only a library dependency of
|
||||||
|
the new crate, nothing in the service calls it, and the compatibility string is unchanged. With it
|
||||||
|
the live fly's whole composition -- agent, world, task and executor -- runs on the session
|
||||||
|
framework, from a fresh start or from a FLYSIM01 checkpoint.
|
||||||
|
|
||||||
|
- **The object** (`fly-legacy-session::task::PokeredTask`). The task and the executor are one
|
||||||
|
object with two faces, `Task` and `ActionExecutor`, which the coordinator holds where it holds
|
||||||
|
any task and executor (legacy-gameboy-v1 section 10). Phase B runs flysim's `MacroLayer::decide`
|
||||||
|
over `ImageReader(O[k], cartridge)` at the agent's brain time. Phase C runs
|
||||||
|
`PokemonRedReward::sample`, `MacroLayer::observe`, the location, the progress and the ratchet's
|
||||||
|
decision over `ImageReader(O[k+1])`. A rollback runs `clear_transient`, `cancel` and `observe`
|
||||||
|
over `ImageReader(O'[k+1])`. These are the legacy engine's own calls in `LegacyFrame`'s order;
|
||||||
|
there is no port of a rule. The cartridge is `Cartridge::verified(rom, contentDigest)`, and O[k] is
|
||||||
|
retained until Phase C has read it.
|
||||||
|
- **The coordinator** (fly-session). A task declares the inspection attachments it reads, and the
|
||||||
|
coordinator holds them and hands over their bytes (`task::Inspection`). The executor's clock is the
|
||||||
|
agent's brain time after Prepare. `Evaluation.slot_saves` asks for `Environment.SaveSlot`. A
|
||||||
|
declared rollback policy now runs itself: `Ready(e, k) -> RollingBack(e', k) -> Ready(e', k)`, with
|
||||||
|
`RestoreSlot`, then `Task::rollback`, then `Agent.Rollback` on every agent. Composition setters
|
||||||
|
cover the backend and task config, the media, the decision schema, the world's state format and
|
||||||
|
per-agent model versions. The admission queue (`AdmissionQueue`) is cut into each Prepare's
|
||||||
|
`preStepStimulations` and reports every admission applied or aborted. `Coordinator::import`
|
||||||
|
installs a checkpoint of another format as a session's start. Step details (`StepDetails`) are
|
||||||
|
kept for a parity run.
|
||||||
|
- **FLYSIM01 as the start** (`fly-legacy-session::import`, on STATE-02's
|
||||||
|
`legacy_checkpoint::{halves, agent_payload, world_payload}`). The world, agent and task halves
|
||||||
|
go into each participant's own capture format, and the ordinary group restore installs them:
|
||||||
|
stage, validate, activate, `Paused(k)`, resume. The world is replaced by a fresh one first,
|
||||||
|
because ENV-01 stages only on a replacement. The context the agent resumes with is computed
|
||||||
|
from the checkpoint's own memory image, and the coordinator holds the task to it after the
|
||||||
|
install (`Task::restored`). The task ledger is STATE-02's `{reward, ratchet, slotFilled}`.
|
||||||
|
- **The store and the boot** (`fly-legacy-session::composition`, on STATE-02's
|
||||||
|
`LegacyCheckpointer`).
|
||||||
|
- `boot` is `Sim::boot`. It restores from the live hot and durable stores in the legacy
|
||||||
|
candidate order, holding each candidate to the legacy gate. Any refusal falls to the next
|
||||||
|
candidate; each attempt runs on a session of its own, because a refused install fences its
|
||||||
|
session. It is a fresh start when the stores are empty. After either, the startup durable
|
||||||
|
save is written and the intervals start.
|
||||||
|
- `advance` keeps the declared boundary order: the slot save (inside the step), the milestone
|
||||||
|
archive on a rank climb, the rollback (deferred by the coordinator until the host has
|
||||||
|
captured), a durable save after a rollback, then the interval saves.
|
||||||
|
- `shutdown_save` is the legacy shutdown's durable save.
|
||||||
|
- The session runtime writes no sugar journal yet: its admission is the coordinator's, and the
|
||||||
|
journal's boot header needs the edge.
|
||||||
|
- `lastEventId` carries the restored file's watermark; the runtime has no feed event log
|
||||||
|
before EDGE-01.
|
||||||
|
- **Sugar** (`fly-legacy-session::admission`). flysim's `RateLimiter` and clamp run unchanged,
|
||||||
|
against the last commit's `stimulusRemainingMs` (one commit stale). An admission waits for the
|
||||||
|
next cut.
|
||||||
|
- **The operator reward pulse is refused.** See the legacy-gameboy-v1 section 15 amendment.
|
||||||
|
|
||||||
|
**Parity** (`fly-legacy-session/tests/session_trace.rs`, rom-env). A whole new-runtime session
|
||||||
|
writes its own `FLY_TRACE` line per transition (`fly-legacy-session::trace`). Each line is built
|
||||||
|
from what crossed its boundaries: `Agent.Prepare`, `Agent.Commit`'s rates and spike bitset, the
|
||||||
|
executor's batch, the view, the image and the boundary actions. It is compared field by field with
|
||||||
|
the legacy loop's. The decision is compared as a set, because `gameboy-channels-v1` carries no list
|
||||||
|
order. Where the legacy side runs in the test, the ledgers are compared after every boundary as
|
||||||
|
well: adapter export, ratchet state, and the executor's scene, bound channels, running macro,
|
||||||
|
counts and "nearer". Results: see the TASK-01 run report and the amendment below.
|
||||||
|
|
||||||
|
**Amendment, 2026-09-29 (TASK-01 review fix round).** The review blocked on B1 and noted
|
||||||
|
N1 to N5. All are fixed here; the dated amendments to legacy-gameboy-v1 section 10 and 15 cover
|
||||||
|
B1, N1 and N3.
|
||||||
|
|
||||||
|
- **B1: the task ledger is artifact-backed.** On the live fly the adapter ledger is 42-46 KB,
|
||||||
|
past the 32 KiB `TypedValue` bound.
|
||||||
|
- `Task` gains `capture_attachments`, `validate_restore_with` and `install_restore_with`.
|
||||||
|
- The coordinator files those attachments as `task-ledger-<name>` payloads in captures and
|
||||||
|
imports.
|
||||||
|
- A bad ledger is an error, never a panic, so a boot falls to the next candidate.
|
||||||
|
- Boot parity now covers row 64 (42 KB) and the row 65 yard (46 KB).
|
||||||
|
- **N1: a sugar admitted before the next commit is an active pulse.**
|
||||||
|
- **N3: a restore seeds the palette as `Sim::boot` does.** `tests/palette_seed.rs` shows that the
|
||||||
|
seed is never read.
|
||||||
|
- **N4: saves are queued to the writer thread.**
|
||||||
|
- **N5: speed.** The profile is below. Changes:
|
||||||
|
- The world seals its three artifacts concurrently.
|
||||||
|
- Cache and caller holds are taken concurrently.
|
||||||
|
- In-process participants use the in-memory transport.
|
||||||
|
- A service session publishes every other boundary (the feed's 30 Hz) and keeps a bounded
|
||||||
|
history.
|
||||||
|
- `State.Capture` is off the loop. The worker shell lets a handler finish its reply outside
|
||||||
|
the endpoint's lock, and takes mutations in arrival order. The legacy agent copies its state
|
||||||
|
under the lock, then encodes, digests and seals it off the lock. The coordinator's
|
||||||
|
`begin_capture` / `finish_capture` let the session step on while the payload is written.
|
||||||
|
- **Measured** (`tests/speed.rs`, `tests/speed_ab.rs`):
|
||||||
|
- The brain is the same: the legacy `ticks` phase and the agent's `ticks` span agree within a
|
||||||
|
few percent.
|
||||||
|
- What remains is a fixed per-frame overhead of the process boundary. It is about 3-5 ms on a
|
||||||
|
quiet 8-core build box: roughly 0.7-1 ms per RPC round trip for Prepare, Advance and Commit,
|
||||||
|
plus the world's and the agent's artifact seals and reads.
|
||||||
|
- Against it, the legacy loop spends about 0.7 ms per frame outside the ticks.
|
||||||
|
- The report `claude-task-01` has the per-phase table and what would close the rest.
|
||||||
|
|
||||||
### 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.
|
||||||
|
|
|
||||||
|
|
@ -288,6 +288,37 @@ signal. The object serves exactly one agent on one port.
|
||||||
- **Cancel.** `cancel(ms)` abandons a running macro. It is followed by `observe` on the world
|
- **Cancel.** `cancel(ms)` abandons a running macro. It is followed by `observe` on the world
|
||||||
the fly now stands in.
|
the fly now stands in.
|
||||||
|
|
||||||
|
**Amendment, 2026-09-29 (TASK-01).** Choices the section above leaves open, fixed as built by
|
||||||
|
`fly-legacy-session::task`:
|
||||||
|
|
||||||
|
- *The ratchet's slot.* The ratchet ledger stays in the task. Its snapshot lives in the environment
|
||||||
|
as the slot `best`. The ratchet only asks whether one exists: its budget test is "no snapshot".
|
||||||
|
So the task holds a marker snapshot in its place, and a task ledger records `slotFilled`. A slot
|
||||||
|
save is asked for exactly when the legacy capture closure runs: safe, and rank above best.
|
||||||
|
- *The task ledger is artifact-backed* (amended 2026-09-29, TASK-01 review B1). The adapter's
|
||||||
|
lifetime ledger grows with play: it is 42-46 KB on the live fly at rungs 12-15, which is past
|
||||||
|
the 32 KiB `TypedValue` bound. So the typed ledger is `{reward: {digest, byteLength}, ratchet,
|
||||||
|
slotFilled}`, and the adapter state's JSON travels as the ledger attachment `reward`. A
|
||||||
|
checkpoint files it as the payload `task-ledger-reward` ([workers-v1](workers-v1.md) section 1's
|
||||||
|
explicit artifact-backed schema; `Task::capture_attachments`). A missing, altered or unreadable
|
||||||
|
attachment is `INCOMPATIBLE_STATE`, never a panic, so a boot falls to the next candidate.
|
||||||
|
- *The palette seed* (amended 2026-09-29, TASK-01 review N3). The legacy loop seeds the palette
|
||||||
|
from the brain's RNG state after boot. A restore does the same: it seeds with the restored
|
||||||
|
agent state's RNG, which it holds. A fresh start cannot see the agent's RNG after the warm-up,
|
||||||
|
so it uses a constant. That is exact because `MacroMachine` never reads its generator: no macro
|
||||||
|
has a random step. `fly-legacy-session` `tests/palette_seed.rs` holds this on the cartridge:
|
||||||
|
two seeds, driven by the same decisions, press the same buttons for 3000 frames. A future
|
||||||
|
macro that draws from the generator fails there.
|
||||||
|
- *The clock of the first observation.* A fresh start's layer observes O[0] at the end of the
|
||||||
|
warm-up, `warmupMs` = 2500 ms, which the profile pins. That is the same time the legacy loop's
|
||||||
|
`Sim::boot` observes at, although the agent is initialized after the task bootstraps. After a
|
||||||
|
restore the layer observes at the restored brain time.
|
||||||
|
- *A reward event with `stimulation_ms` = 0* is one `Reward` and no `Stimulus`, because
|
||||||
|
`Stimulus.durationMs` is positive. The legacy `stimulate(0)` changes nothing.
|
||||||
|
- *Executor events.* Macro starts and finishes are not `executionEvents`. They are reported as
|
||||||
|
`FLY_TRACE` `macroEvents` (phases `execute`, `evaluate`, `rollback`). Reward events are the
|
||||||
|
task's `TaskEvent`s.
|
||||||
|
|
||||||
## 11. Episode policy `legacy-ratchet-rollback-v1`
|
## 11. Episode policy `legacy-ratchet-rollback-v1`
|
||||||
|
|
||||||
The ratchet's game-only rollback is a declared episode policy. When the ratchet fires during
|
The ratchet's game-only rollback is a declared episode policy. When the ratchet fires during
|
||||||
|
|
@ -331,6 +362,14 @@ the adapter's persistent state. The first audio chunk after the rollback marks a
|
||||||
discontinuity. This is the legacy `recover_game` sequence with the neural half moved into the agent.
|
discontinuity. This is the legacy `recover_game` sequence with the neural half moved into the agent.
|
||||||
Each half touches only its own state, so the order between the halves does not matter.
|
Each half touches only its own state, so the order between the halves does not matter.
|
||||||
|
|
||||||
|
**Amendment, 2026-09-29 (TASK-01).** The coordinator applies the policy itself, as the section
|
||||||
|
describes. The phase is `RollingBack(k)`. The new epoch is the session's epoch root plus `.rb<n>`,
|
||||||
|
which is deterministic, so two runs of one session name the same epochs. A composition that
|
||||||
|
declares the policy refuses to start unless every agent advertises `legacy-ratchet-rollback-v1`.
|
||||||
|
The task's rollback request carries `{slotId: best, trigger}`. The world must advertise
|
||||||
|
`gameboy-slots-v1` before anything is saved or restored. Service traces with a ratchet slot save
|
||||||
|
and a ratchet rollback reproduce as described in the implementation guide's TASK-01 entry.
|
||||||
|
|
||||||
## 12. Composition declaration and digest
|
## 12. Composition declaration and digest
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
|
|
@ -500,6 +539,27 @@ Resume tests compare against the legacy restore outcome, not against an uninterr
|
||||||
unstick procedure depends on: restarting the service clears the ledger-shaped traps and keeps
|
unstick procedure depends on: restarting the service clears the ledger-shaped traps and keeps
|
||||||
the rung.
|
the rung.
|
||||||
|
|
||||||
|
**Amendment, 2026-09-29 (TASK-01): a FLYSIM01 checkpoint as the start.** A new-runtime session
|
||||||
|
starts from the live fly's own save through the ordinary group restore
|
||||||
|
(`Coordinator::import`, `fly-legacy-session::import`):
|
||||||
|
|
||||||
|
- The world is ENV-01's `WorldState::from_flysim01` at `k = emulatorFrame - 1`, staged on a
|
||||||
|
replacement world.
|
||||||
|
- The agent is the checkpoint's agent state in the worker's own capture format: STATE-02's
|
||||||
|
`legacy_checkpoint::agent_payload`. It carries the file's reinforcement count and the file's
|
||||||
|
framebuffer as the next input, and its ids come from the file.
|
||||||
|
- The task is STATE-02's ledger `{reward, ratchet, slotFilled}`.
|
||||||
|
|
||||||
|
A session boots from the live stores the way `Sim::boot` does: the legacy candidate order, the
|
||||||
|
legacy gate, the next candidate on any refusal, then a startup durable save. See the
|
||||||
|
implementation guide's TASK-01 entry.
|
||||||
|
|
||||||
|
This section's resets then apply, and nothing else. The executor is fresh and observes the restored
|
||||||
|
image once, at the restored brain time. The agent's readout transient is a fresh process's. The
|
||||||
|
decision context is computed from the checkpoint's memory image before the install, and the
|
||||||
|
coordinator refuses the install if the task, re-observing the restored world, derives another
|
||||||
|
context.
|
||||||
|
|
||||||
## 15. Sugar admission
|
## 15. Sugar admission
|
||||||
|
|
||||||
The coordinator owns admission, with the legacy rules: the per-minute limiter, and "no overlap
|
The coordinator owns admission, with the legacy rules: the per-minute limiter, and "no overlap
|
||||||
|
|
@ -523,6 +583,29 @@ applies it never commits, the admission is reported aborted and the edge refunds
|
||||||
bridge's fulfil path and refund path both get tests in the slice that wires them
|
bridge's fulfil path and refund path both get tests in the slice that wires them
|
||||||
([workers-v1](workers-v1.md) section 5 amendment).
|
([workers-v1](workers-v1.md) section 5 amendment).
|
||||||
|
|
||||||
|
**Amendment, 2026-09-29 (TASK-01).** As built:
|
||||||
|
|
||||||
|
- *Admission.* The coordinator's `AdmissionQueue` is cut at the top of each Prepare. It reports
|
||||||
|
every admission `applied` at the boundary its Prepare committed at, or `aborted` when the epoch
|
||||||
|
fails first. The legacy rules run on the edge side, unchanged: flysim's `RateLimiter` and the
|
||||||
|
clamp. They read `stimulusRemainingMs` from the last `Agent.Commit` or `Agent.Rollback` reply.
|
||||||
|
After a restore the pulse is unknown and a request is refused with a retry of one frame.
|
||||||
|
*Amended 2026-09-29 (TASK-01 review N1):* a sugar admitted but not yet reported on by a commit
|
||||||
|
counts as an active pulse, at its full duration (`AdmissionQueue::pending_stimulus_ms`). The
|
||||||
|
legacy `stimulate` activates the pulse the moment it admits, so this matches:
|
||||||
|
- two sugars between two commits get one admission and one `PulseActive`, as the legacy drain
|
||||||
|
gives them;
|
||||||
|
- the rate-limit slot is not spent on the refused one.
|
||||||
|
|
||||||
|
The retry advice may differ by less than a frame. Legacy reports the pulse decayed by the
|
||||||
|
ticks between drains; here it is undecayed until the commit reports it.
|
||||||
|
- *The operator's `POST /reward` pulse is refused (declared).* In the legacy loop it is off unless
|
||||||
|
an operator sets `control.allow_reward`. Every shipped configuration leaves it off, and the API
|
||||||
|
answers 403. The session runtime has no counterpart to turn on, because a reinforcement outside
|
||||||
|
`Agent.Commit` is not a session-framework operation. `LegacyAdmission::reward` therefore always
|
||||||
|
refuses. A legacy trace that carries a reward pulse cannot be reproduced; FND-01's checker
|
||||||
|
refuses one as well.
|
||||||
|
|
||||||
## 16. Checkpoint format of record
|
## 16. Checkpoint format of record
|
||||||
|
|
||||||
**Order at a boundary (amended 2026-09-23, review round 1).** A slot save due at `Ready(k)`
|
**Order at a boundary (amended 2026-09-23, review round 1).** A slot save due at `Ready(k)`
|
||||||
|
|
|
||||||
|
|
@ -65,6 +65,19 @@ amendment). The boundary number does not change; the epoch does. A pause request
|
||||||
lands on `Ready(e', k)`; any failure inside it is `Failed → Restoring(new epoch)`. Capture is
|
lands on `Ready(e', k)`; any failure inside it is `Failed → Restoring(new epoch)`. Capture is
|
||||||
not allowed in `RollingBack`.
|
not allowed in `RollingBack`.
|
||||||
|
|
||||||
|
**Amendment, 2026-09-29 (TASK-01).** Two edges are implemented as written above (`fly-session`
|
||||||
|
`phase.rs`): `Ready(k) -> RollingBack(k) -> Ready(k)`, where the epoch is the coordinator's and
|
||||||
|
the boundary stays the same. One edge is added for a checkpoint of another format installed as a
|
||||||
|
session's start (the legacy composition's FLYSIM01 import):
|
||||||
|
|
||||||
|
```text
|
||||||
|
Ready(0), no transition taken -> Restoring(k) -> Paused(k)
|
||||||
|
```
|
||||||
|
|
||||||
|
The install is the group restore of [state-media-v1](state-media-v1.md) section 6, unchanged. Only
|
||||||
|
a session that has not advanced may take the edge; the coordinator enforces this, because the phase
|
||||||
|
alone cannot tell a fresh `Ready(0)` from a reset one.
|
||||||
|
|
||||||
## 3. Transaction sequence
|
## 3. Transaction sequence
|
||||||
|
|
||||||
### Phase A: prepare all agents concurrently
|
### Phase A: prepare all agents concurrently
|
||||||
|
|
@ -111,6 +124,12 @@ and returns StepResult for `k+1`. It MUST NOT advance another interval while wai
|
||||||
the next request. Transport/control scaffolding may have a measured fixed latency; it must
|
the next request. Transport/control scaffolding may have a measured fixed latency; it must
|
||||||
be declared in its descriptor and conformance tests.
|
be declared in its descriptor and conformance tests.
|
||||||
|
|
||||||
|
*Amendment, 2026-09-29 (TASK-01):* as built, the clock the executor is handed is
|
||||||
|
`brainTicks x tickDuration` from the agent's `PreparedDecision`, exact in `RationalNs`. For the
|
||||||
|
legacy profile this is the legacy `network.ms` in nanoseconds. An artifact-backed inspection reaches
|
||||||
|
the executor and the task as bytes: the coordinator holds each attachment the task declares
|
||||||
|
(`inspection.memory`) from the world's reply until the transition that reads it has been evaluated.
|
||||||
|
|
||||||
### Phase C: observe and evaluate the task
|
### Phase C: observe and evaluate the task
|
||||||
|
|
||||||
The coordinator receives the environment result and verifies batch identity, boundary,
|
The coordinator receives the environment result and verifies batch identity, boundary,
|
||||||
|
|
|
||||||
|
|
@ -426,6 +426,22 @@ composition that declares no rollback policy treats the request as a task failur
|
||||||
"cannot reset the environment directly": the coordinator applies the policy through the
|
"cannot reset the environment directly": the coordinator applies the policy through the
|
||||||
section 7 methods.
|
section 7 methods.
|
||||||
|
|
||||||
|
**Amendment, 2026-09-29 (TASK-01).** The Rust interfaces, as built in `fly-session::task`:
|
||||||
|
|
||||||
|
- The inspection argument is an `Inspection`: the observation's typed `inspection` value, plus the
|
||||||
|
bytes of every attachment the task declares (`Task::inspection_attachments`, for example
|
||||||
|
`inspection.memory`). A synthetic task declares none, and its inspection reads as the typed value
|
||||||
|
it always was.
|
||||||
|
- `Evaluation.slot_saves` names the `Environment.SaveSlot`s the transition asks for at the boundary
|
||||||
|
it reached. They are applied after every Commit, saves first.
|
||||||
|
- `Task::rollback(scope', restored)` is step 3 of a declared rollback policy. It returns the next
|
||||||
|
contexts.
|
||||||
|
- `Task::restored(scope', restored, clock)` runs after a group restore installed the ledger. A task
|
||||||
|
whose executor state is transient re-observes the restored world here, and returns the contexts
|
||||||
|
the coordinator holds against the checkpoint's.
|
||||||
|
- A task and an executor that are one object (`pokered-macros-v1`) are two handles on one shared
|
||||||
|
state.
|
||||||
|
|
||||||
## 5. Admission and audience boundary
|
## 5. Admission and audience boundary
|
||||||
|
|
||||||
The first synthetic implementation has no audience input. Later integration maps permitted
|
The first synthetic implementation has no audience input. Later integration maps permitted
|
||||||
|
|
@ -453,6 +469,13 @@ first and refunds the second, and the slice wiring the bridge tests both. This i
|
||||||
accepted/applied/aborted distinction the paragraph above asks for, for this one interaction
|
accepted/applied/aborted distinction the paragraph above asks for, for this one interaction
|
||||||
kind; paid interactions in general still need the public v2 contract.
|
kind; paid interactions in general still need the public v2 contract.
|
||||||
|
|
||||||
|
**Amendment, 2026-09-29 (TASK-01).** As built, the coordinator's `AdmissionQueue` is the
|
||||||
|
admission record: an admitted stimulus carries its interaction id into `preStepStimulations`, and it
|
||||||
|
ends `applied` (with its boundary) or `aborted` (the epoch failed before its Prepare committed). The
|
||||||
|
legacy composition's rules run on the edge side of the queue. No other interaction kind is admitted.
|
||||||
|
The legacy operator reward pulse is refused (legacy-gameboy-v1 section 15, amendment of
|
||||||
|
2026-09-29).
|
||||||
|
|
||||||
## 6. Health, shutdown and extensions
|
## 6. Health, shutdown and extensions
|
||||||
|
|
||||||
All workers implement the common Hello/Status/Shutdown/Acknowledge methods. Capture/restore
|
All workers implement the common Hello/Status/Shutdown/Acknowledge methods. Capture/restore
|
||||||
|
|
|
||||||
14
services/flysim/Cargo.lock
generated
14
services/flysim/Cargo.lock
generated
|
|
@ -435,6 +435,20 @@ dependencies = [
|
||||||
"tracing-subscriber",
|
"tracing-subscriber",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "fly-legacy-session"
|
||||||
|
version = "0.1.1"
|
||||||
|
dependencies = [
|
||||||
|
"fly-session",
|
||||||
|
"flybrain-core",
|
||||||
|
"flybrain-gb",
|
||||||
|
"flybus",
|
||||||
|
"flysim",
|
||||||
|
"serde_json",
|
||||||
|
"tempfile",
|
||||||
|
"tokio",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "fly-session"
|
name = "fly-session"
|
||||||
version = "0.1.1"
|
version = "0.1.1"
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@
|
||||||
resolver = "3"
|
resolver = "3"
|
||||||
members = [
|
members = [
|
||||||
"crates/fly-edge",
|
"crates/fly-edge",
|
||||||
|
"crates/fly-legacy-session",
|
||||||
"crates/fly-session",
|
"crates/fly-session",
|
||||||
"crates/fly-session-types",
|
"crates/fly-session-types",
|
||||||
"crates/flybrain-core",
|
"crates/flybrain-core",
|
||||||
|
|
|
||||||
28
services/flysim/crates/fly-legacy-session/Cargo.toml
Normal file
28
services/flysim/crates/fly-legacy-session/Cargo.toml
Normal file
|
|
@ -0,0 +1,28 @@
|
||||||
|
[package]
|
||||||
|
name = "fly-legacy-session"
|
||||||
|
version.workspace = true
|
||||||
|
edition = "2024"
|
||||||
|
rust-version.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
publish = false
|
||||||
|
description = "The live fly's composition on the session framework: the pokered-macros-v1 task and executor, the FLYSIM01 import, and the parity harness against the legacy loop's FLY_TRACE."
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
name = "fly_legacy_session"
|
||||||
|
path = "src/lib.rs"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
# The session framework and its legacy workers (AGENT-01, ENV-01).
|
||||||
|
fly-session = { path = "../fly-session" }
|
||||||
|
flybus = { path = "../flybus" }
|
||||||
|
# The unchanged legacy engine the task and executor run: flysim's macro layer, flybrain-gb's
|
||||||
|
# palette, macro executor, PokeState, reward adapter and ratchet, read through MEM-01's image.
|
||||||
|
# flysim is a library dependency only; nothing here changes the service it builds.
|
||||||
|
flysim = { path = "../flysim" }
|
||||||
|
flybrain-gb = { path = "../flybrain-gb" }
|
||||||
|
flybrain-core = { path = "../flybrain-core" }
|
||||||
|
serde_json = { workspace = true }
|
||||||
|
tokio = { version = "1", features = ["rt", "rt-multi-thread", "sync", "time", "macros"] }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tempfile = "3"
|
||||||
126
services/flysim/crates/fly-legacy-session/src/admission.rs
Normal file
126
services/flysim/crates/fly-legacy-session/src/admission.rs
Normal file
|
|
@ -0,0 +1,126 @@
|
||||||
|
//! Sugar, admitted by the legacy rules onto the coordinator's admission queue, and the operator
|
||||||
|
//! reward pulse, refused (`legacy-gameboy-v1` section 15 and its amendment of 2026-09-29).
|
||||||
|
//!
|
||||||
|
//! The rules are flysim's own, unchanged: `flysim::ratelimit::RateLimiter` (the per-minute limit
|
||||||
|
//! and "no overlap with an active pulse") and the duration clamp to `[1, sugar_max_ms]`. What
|
||||||
|
//! changed is the pulse they read: the agent's `stimulusRemainingMs` from the **last completed
|
||||||
|
//! commit** ([`AdmissionQueue::stimulus_remaining_ms`]), which the operator accepted as one commit
|
||||||
|
//! stale. Until the first commit of an epoch it is unknown, and a request is refused with a retry.
|
||||||
|
//! A sugar admitted and not yet reported on by a commit counts as active from its admission, as
|
||||||
|
//! the legacy loop's `stimulate` makes it active at once, so two sugars between two commits are
|
||||||
|
//! one admission and one `PulseActive` refusal, exactly as the legacy drain answers them.
|
||||||
|
//!
|
||||||
|
//! The operator's `POST /reward` pulse is refused. The legacy loop refuses it too unless an
|
||||||
|
//! operator turns `control.allow_reward` on (it is off in every shipped configuration); the new
|
||||||
|
//! runtime has no counterpart to turn on, and says so rather than approximating one -- a
|
||||||
|
//! reinforcement outside `Agent.Commit` is not a session-framework operation.
|
||||||
|
|
||||||
|
use flysim::ratelimit::{RateLimiter, Refusal};
|
||||||
|
|
||||||
|
use fly_session::coordinator::{Admission, AdmissionQueue};
|
||||||
|
use fly_session::fly_session_types::gameboy::STIMULUS_REWARD_PULSE;
|
||||||
|
use fly_session::types::*;
|
||||||
|
|
||||||
|
/// Why `POST /reward` is refused (`legacy-gameboy-v1` section 15, amendment of 2026-09-29).
|
||||||
|
pub const OPERATOR_REWARD_REFUSED: &str = "the operator reward pulse is not available on the session runtime (legacy-gameboy-v1 section 15)";
|
||||||
|
|
||||||
|
/// Retry advice while the pulse is unknown: one frame, rounded up.
|
||||||
|
pub const UNKNOWN_PULSE_RETRY_MS: u64 = 17;
|
||||||
|
|
||||||
|
/// The edge-side admission of the legacy composition.
|
||||||
|
pub struct LegacyAdmission {
|
||||||
|
queue: AdmissionQueue,
|
||||||
|
agent_id: Id,
|
||||||
|
limiter: RateLimiter,
|
||||||
|
default_ms: f64,
|
||||||
|
max_ms: f64,
|
||||||
|
serial: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LegacyAdmission {
|
||||||
|
/// flysim's defaults: 6 per minute, 400 ms by default, at most 1000 ms.
|
||||||
|
pub fn new(queue: AdmissionQueue, agent_id: Id) -> LegacyAdmission {
|
||||||
|
let control = flysim::config::Config::default().control;
|
||||||
|
LegacyAdmission::with_limits(
|
||||||
|
queue,
|
||||||
|
agent_id,
|
||||||
|
control.sugar_per_minute,
|
||||||
|
control.sugar_default_ms,
|
||||||
|
control.sugar_max_ms,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_limits(
|
||||||
|
queue: AdmissionQueue,
|
||||||
|
agent_id: Id,
|
||||||
|
per_minute: usize,
|
||||||
|
default_ms: f64,
|
||||||
|
max_ms: f64,
|
||||||
|
) -> LegacyAdmission {
|
||||||
|
LegacyAdmission {
|
||||||
|
queue,
|
||||||
|
agent_id,
|
||||||
|
limiter: RateLimiter::new(per_minute),
|
||||||
|
default_ms,
|
||||||
|
max_ms,
|
||||||
|
serial: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn next_id(&mut self, kind: &str) -> Id {
|
||||||
|
self.serial += 1;
|
||||||
|
id(&format!("{kind}-{}", self.serial))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `POST /stimulate`: the legacy rule over the last commit's pulse. On admission the sugar is
|
||||||
|
/// queued for the next Prepare; the result is its interaction id and the clamped duration.
|
||||||
|
pub fn sugar(&mut self, now_ms: u64, duration_ms: Option<f64>) -> Result<(Id, f64), Refusal> {
|
||||||
|
// Read the pulse, decide and queue under one lock, so a commit cannot land between the
|
||||||
|
// reads and the push (TASK-01 review R2-3). A sugar admitted and not yet reported on by
|
||||||
|
// a commit is an active pulse, as it is in the legacy loop the moment `stimulate` runs:
|
||||||
|
// a second request before the next commit is refused (`PulseActive`), not admitted
|
||||||
|
// into a pulse that would take the max and add nothing (review N1).
|
||||||
|
let agent_id = self.agent_id.clone();
|
||||||
|
let interaction_id = self.next_id("sugar");
|
||||||
|
let (limiter, default_ms, max_ms) = (&mut self.limiter, self.default_ms, self.max_ms);
|
||||||
|
let admission = self.queue.admit_with(&agent_id, |remaining, pending| {
|
||||||
|
let Some(remaining) = remaining else {
|
||||||
|
return Err(Refusal::PulseActive {
|
||||||
|
retry_after_ms: UNKNOWN_PULSE_RETRY_MS,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
limiter.admit(now_ms, remaining.max(pending.unwrap_or(0.0)))?;
|
||||||
|
let duration = duration_ms.unwrap_or(default_ms).clamp(1.0, max_ms).min(max_ms);
|
||||||
|
Ok(Admission::Stimulus {
|
||||||
|
agent_id: agent_id.clone(),
|
||||||
|
interaction_id: interaction_id.clone(),
|
||||||
|
kind_id: id(STIMULUS_REWARD_PULSE),
|
||||||
|
duration_ms: duration,
|
||||||
|
})
|
||||||
|
});
|
||||||
|
if admission.is_err() {
|
||||||
|
// A refusal spends no id.
|
||||||
|
self.serial -= 1;
|
||||||
|
}
|
||||||
|
let Admission::Stimulus { duration_ms: duration, .. } = admission?;
|
||||||
|
Ok((interaction_id, duration))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `POST /reward`: refused, always (the legacy default, `control.allow_reward = false`).
|
||||||
|
pub fn reward(&mut self, _value: f64) -> Result<Id, &'static str> {
|
||||||
|
Err(OPERATOR_REWARD_REFUSED)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Admits exactly this sugar, bypassing the rules: a parity run replays the legacy loop's
|
||||||
|
/// admitted inputs, it does not re-decide them.
|
||||||
|
pub fn replay_sugar(&mut self, duration_ms: f64) -> Id {
|
||||||
|
let interaction_id = self.next_id("sugar");
|
||||||
|
self.queue.admit(Admission::Stimulus {
|
||||||
|
agent_id: self.agent_id.clone(),
|
||||||
|
interaction_id: interaction_id.clone(),
|
||||||
|
kind_id: id(STIMULUS_REWARD_PULSE),
|
||||||
|
duration_ms,
|
||||||
|
});
|
||||||
|
interaction_id
|
||||||
|
}
|
||||||
|
}
|
||||||
765
services/flysim/crates/fly-legacy-session/src/composition.rs
Normal file
765
services/flysim/crates/fly-legacy-session/src/composition.rs
Normal file
|
|
@ -0,0 +1,765 @@
|
||||||
|
//! The legacy Game Boy composition on the session framework: one legacy agent (AGENT-01), the
|
||||||
|
//! legacy environment (ENV-01), and the `pokered-macros-v1` task and executor (this crate) in the
|
||||||
|
//! coordinator, over one router, in any of the launcher's execution modes.
|
||||||
|
//!
|
||||||
|
//! This is the whole new runtime of the live fly short of its edge (EDGE-01) and its FLYSIM01
|
||||||
|
//! export (STATE-02): what CUT-01's shadow runs beside the legacy service.
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use flybus::{Grants, Pattern, Policy, RouterConfig};
|
||||||
|
|
||||||
|
use fly_session::coordinator::{AgentSlot, Coordinator, StepDetails, StepReport};
|
||||||
|
use fly_session::fly_session_types::extensions::ROLLBACK_POLICY;
|
||||||
|
use fly_session::fly_session_types::gameboy;
|
||||||
|
use fly_session::launcher::{
|
||||||
|
ExecutionMode, Launcher, LegacyAgentLaunch, LegacyEnvironmentLaunch, SUPERVISOR_CLIENT,
|
||||||
|
ThreadBudget, Via,
|
||||||
|
};
|
||||||
|
use fly_session::legacy_agent::{LegacyProfileKind, SPIKES_ATTACHMENT};
|
||||||
|
use fly_session::legacy_env::BackendConfig;
|
||||||
|
use fly_session::task::ActionExecutor;
|
||||||
|
use fly_session::types::*;
|
||||||
|
use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros;
|
||||||
|
use flysim::snapshot::MacroMode;
|
||||||
|
|
||||||
|
use crate::task::{PokeredConfig, PokeredTask, TaskRecord};
|
||||||
|
use fly_session::legacy_checkpoint::{
|
||||||
|
AgentImport, CheckpointerConfig, LegacyCapture, LegacyCheckpointer, RankChange, SaveKind,
|
||||||
|
SaveReport, SaveTicket, TaskHalf, now_wall_ms,
|
||||||
|
};
|
||||||
|
use flysim::store::Checkpoint;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
fn grants(f: impl FnOnce(&mut Grants)) -> Grants {
|
||||||
|
let mut g = Grants::default();
|
||||||
|
f(&mut g);
|
||||||
|
g
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The transitions a service session keeps in memory for diagnosis (about a minute at 60 Hz).
|
||||||
|
const HISTORY: usize = 4096;
|
||||||
|
|
||||||
|
/// Every other boundary's snapshot: the legacy feed's `snapshot_hz` (30 Hz) at 60 Hz.
|
||||||
|
const SNAPSHOT_EVERY: u64 = 2;
|
||||||
|
|
||||||
|
const COORDINATOR_CLIENT: &str = "coordinator";
|
||||||
|
const ENV_CLIENT: &str = "legacy-world";
|
||||||
|
const ENV_SERVICE: &str = "env.world";
|
||||||
|
const ENV_WORKER: &str = "world";
|
||||||
|
const AGENT_CLIENT: &str = "legacy-fly";
|
||||||
|
|
||||||
|
/// How one legacy session is composed.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct LegacyConfig {
|
||||||
|
pub mode: ExecutionMode,
|
||||||
|
pub rom_path: PathBuf,
|
||||||
|
pub dataset_dir: PathBuf,
|
||||||
|
pub profile: LegacyProfileKind,
|
||||||
|
pub macro_mode: MacroMode,
|
||||||
|
pub agent_id: Id,
|
||||||
|
pub agent_threads: usize,
|
||||||
|
/// Record the step details and the task records (a parity run).
|
||||||
|
pub record: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The macro channels and the macro group's hold for a mode: the decoder preset flysim builds.
|
||||||
|
pub fn channels_and_hold(mode: MacroMode) -> (Vec<String>, f64) {
|
||||||
|
let channels: Vec<&str> = if mode.dealt() {
|
||||||
|
flybrain_gb::macro_channels(crate::task::GAME)
|
||||||
|
} else {
|
||||||
|
Vec::new()
|
||||||
|
};
|
||||||
|
let preset = gameboy_decoder_config_with_macros(&channels);
|
||||||
|
let hold_ms = preset
|
||||||
|
.macros
|
||||||
|
.as_ref()
|
||||||
|
.or(preset.exclusive.as_ref())
|
||||||
|
.map_or(0.0, |group| group.hold_ms);
|
||||||
|
(channels.iter().map(|c| (*c).to_owned()).collect(), hold_ms)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A running legacy session: its launcher, its coordinator and the task object.
|
||||||
|
pub struct LegacySession {
|
||||||
|
pub coordinator: Coordinator,
|
||||||
|
pub task: PokeredTask,
|
||||||
|
pub launcher: Launcher,
|
||||||
|
pub rom: Vec<u8>,
|
||||||
|
pub config: LegacyConfig,
|
||||||
|
session_id: Id,
|
||||||
|
backend: BackendConfig,
|
||||||
|
/// Which generation of the world is running: 1 is the one the session started.
|
||||||
|
world_generation: u32,
|
||||||
|
/// The legacy store policy, once attached ([`LegacySession::attach_store`]).
|
||||||
|
checkpointer: Option<LegacyCheckpointer>,
|
||||||
|
saves: u64,
|
||||||
|
/// Saves on the writer thread whose outcome has not been collected.
|
||||||
|
pending_saves: Vec<SaveTicket>,
|
||||||
|
/// Captures sent and not yet collected ([`LegacySession::begin_save`]).
|
||||||
|
pending_captures: Vec<(fly_session::coordinator::PendingCapture, SaveKind, TaskHalf)>,
|
||||||
|
/// The feed event log's watermark the saves record: the restored file's, carried over (the
|
||||||
|
/// session runtime has no feed event log of its own before EDGE-01).
|
||||||
|
last_event_id: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the legacy store lives and how often it is written (the service's `[paths]` and
|
||||||
|
/// `[loop]`).
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct StoreConfig {
|
||||||
|
pub hot_dir: PathBuf,
|
||||||
|
pub durable_dir: PathBuf,
|
||||||
|
pub keep_generations: usize,
|
||||||
|
pub hot_seconds: f64,
|
||||||
|
pub checkpoint_seconds: f64,
|
||||||
|
pub speed: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This build's legacy compatibility string (`flysim --print-compatibility`): the kernel, the
|
||||||
|
/// adapter, the profile's dataset fingerprint, the plasticity rule and the pokered symbols. It is
|
||||||
|
/// the restore gate and what every save records (`legacy-gameboy-v1` section 12).
|
||||||
|
pub fn compatibility_of(config: &LegacyConfig) -> String {
|
||||||
|
let adapter = flybrain_gb::pokemon_red::PokemonRedReward::new();
|
||||||
|
let profile = config.profile.profile();
|
||||||
|
flybrain_gb::Compatibility {
|
||||||
|
neural_kernel_version: gameboy::KERNEL_VERSION,
|
||||||
|
adapter: flybrain_gb::GameAdapter::id(&adapter),
|
||||||
|
dataset_fingerprint: &profile.dataset_fingerprint,
|
||||||
|
plasticity_version: gameboy::PLASTICITY_VERSION,
|
||||||
|
pokered_commit: &flybrain_gb::GameAdapter::symbol_provenance(&adapter),
|
||||||
|
}
|
||||||
|
.string()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How a session came up.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum Boot {
|
||||||
|
/// No checkpoint in either store: a fresh fly, warmed up.
|
||||||
|
Fresh,
|
||||||
|
/// A candidate restored, after `skipped` were refused.
|
||||||
|
Restored {
|
||||||
|
candidate: flysim::store::Candidate,
|
||||||
|
skipped: Vec<(flysim::store::Candidate, String)>,
|
||||||
|
migrated_from: Option<String>,
|
||||||
|
imported: crate::import::Imported,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Sim::boot` on the session runtime: restore from the live FLYSIM01 stores in the legacy order
|
||||||
|
/// (hot latest, hot previous, durable latest, durable previous, milestone archives by rank), each
|
||||||
|
/// candidate held to the legacy gate (`RestoreGate`: the cartridge and the compatibility decision
|
||||||
|
/// with `FLY_ACCEPT_ADAPTERS`), falling to the next on *any* refusal -- unreadable, gated, or
|
||||||
|
/// refused by a participant's `State.StageRestore` or the task. A refused install fences its
|
||||||
|
/// session, so each attempt runs on a session of its own (a directory under `root` each). No
|
||||||
|
/// candidate at all is a fresh start; candidates that all fail are an error, as the legacy loop
|
||||||
|
/// refuses to start a fresh fly over them. Either way the store is attached and the startup
|
||||||
|
/// durable save is written, and the intervals run from then.
|
||||||
|
pub async fn boot(
|
||||||
|
root: &Path,
|
||||||
|
config: LegacyConfig,
|
||||||
|
store: &StoreConfig,
|
||||||
|
) -> Result<(LegacySession, Boot), String> {
|
||||||
|
let hot = flysim::store::Store::new(&store.hot_dir, store.keep_generations);
|
||||||
|
let durable = flysim::store::Store::new(&store.durable_dir, store.keep_generations);
|
||||||
|
let candidates = flysim::store::restore_order(&hot, &durable);
|
||||||
|
let rom = std::fs::read(&config.rom_path)
|
||||||
|
.map_err(|e| format!("the cartridge {}: {e}", config.rom_path.display()))?;
|
||||||
|
let adapter = flybrain_gb::pokemon_red::PokemonRedReward::new();
|
||||||
|
let gate = fly_session::legacy_checkpoint::RestoreGate::from_env(
|
||||||
|
&sha256_hex(&rom),
|
||||||
|
&compatibility_of(&config),
|
||||||
|
flybrain_gb::GameAdapter::migrates_from(&adapter),
|
||||||
|
);
|
||||||
|
let mut skipped: Vec<(flysim::store::Candidate, String)> = Vec::new();
|
||||||
|
let mut outcome = None;
|
||||||
|
for (attempt, candidate) in candidates.iter().enumerate() {
|
||||||
|
let checkpoint = match flysim::store::load(&candidate.path) {
|
||||||
|
Ok(checkpoint) => checkpoint,
|
||||||
|
Err(e) => {
|
||||||
|
skipped.push((candidate.clone(), format!("{e:#}")));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let migrated_from = match gate.check(&checkpoint) {
|
||||||
|
Ok(from) => from,
|
||||||
|
Err(reason) => {
|
||||||
|
skipped.push((candidate.clone(), reason));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut session =
|
||||||
|
LegacySession::start(&root.join(format!("attempt-{attempt}")), config.clone()).await?;
|
||||||
|
let installed = match session.bootstrap().await {
|
||||||
|
Ok(()) => session.import_checkpoint(&checkpoint, &id("e2")).await,
|
||||||
|
Err(e) => Err(e),
|
||||||
|
};
|
||||||
|
match installed {
|
||||||
|
Ok(imported) => {
|
||||||
|
let rank = session.task.rank();
|
||||||
|
session.attach_store(store)?;
|
||||||
|
session
|
||||||
|
.checkpointer_mut()
|
||||||
|
.expect("attached")
|
||||||
|
.restored(rank, imported.rank_since_ms);
|
||||||
|
outcome = Some((
|
||||||
|
session,
|
||||||
|
Boot::Restored {
|
||||||
|
candidate: candidate.clone(),
|
||||||
|
skipped: std::mem::take(&mut skipped),
|
||||||
|
migrated_from,
|
||||||
|
imported,
|
||||||
|
},
|
||||||
|
));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Err(reason) => {
|
||||||
|
session.stop().await;
|
||||||
|
skipped.push((candidate.clone(), reason));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let (mut session, boot) = match outcome {
|
||||||
|
Some(pair) => pair,
|
||||||
|
None if candidates.is_empty() => {
|
||||||
|
let mut session = LegacySession::start(&root.join("fresh"), config).await?;
|
||||||
|
session.bootstrap().await?;
|
||||||
|
session.attach_store(store)?;
|
||||||
|
(session, Boot::Fresh)
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
let reasons: Vec<String> = skipped
|
||||||
|
.iter()
|
||||||
|
.map(|(candidate, reason)| format!("{}: {reason}", candidate.origin))
|
||||||
|
.collect();
|
||||||
|
return Err(format!(
|
||||||
|
"every one of the {} checkpoint candidates failed to load; refusing to start a \
|
||||||
|
fresh run over them:\n{}",
|
||||||
|
candidates.len(),
|
||||||
|
reasons.join("\n")
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// `Sim::boot`: a durable save of the state the process starts from, then the intervals.
|
||||||
|
session.save(SaveKind::Durable).await?;
|
||||||
|
session
|
||||||
|
.checkpointer_mut()
|
||||||
|
.expect("attached")
|
||||||
|
.start_intervals(Instant::now());
|
||||||
|
Ok((session, boot))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A save [`LegacySession::advance`] queued at the boundary it reached.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub struct SaveQueued {
|
||||||
|
pub generation: u64,
|
||||||
|
pub durable: bool,
|
||||||
|
pub archive_rank: Option<u32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One transition as a parity run sees it.
|
||||||
|
pub struct Step {
|
||||||
|
pub report: StepReport,
|
||||||
|
pub details: Option<StepDetails>,
|
||||||
|
pub records: Vec<TaskRecord>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LegacySession {
|
||||||
|
/// Builds the router, launches the world and the fly, and builds the coordinator with the task
|
||||||
|
/// object's two faces. Nothing has been initialized yet.
|
||||||
|
pub async fn start(root: &Path, config: LegacyConfig) -> Result<LegacySession, String> {
|
||||||
|
let rom = std::fs::read(&config.rom_path)
|
||||||
|
.map_err(|e| format!("the cartridge {}: {e}", config.rom_path.display()))?;
|
||||||
|
let rom_digest = sha256_hex(&rom);
|
||||||
|
let session_id = id("legacy");
|
||||||
|
let epoch = id("e1");
|
||||||
|
let store_root = root.join("store");
|
||||||
|
let sockets = root.join("sockets");
|
||||||
|
std::fs::create_dir_all(&sockets).map_err(|e| format!("sockets: {e}"))?;
|
||||||
|
let agent_service = format!("agent.{}", config.agent_id);
|
||||||
|
let policy = Policy::closed()
|
||||||
|
.client(
|
||||||
|
COORDINATOR_CLIENT,
|
||||||
|
grants(|g| {
|
||||||
|
g.call = vec![Pattern::prefix("agent."), Pattern::prefix("env.")];
|
||||||
|
g.publish = vec![Pattern::prefix("session.")];
|
||||||
|
g.manage_topics = vec![Pattern::prefix("session.")];
|
||||||
|
g.register = vec![Pattern::prefix("session.")];
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
// The launcher's supervisor: health checks and shutdown, never a registration.
|
||||||
|
.client(
|
||||||
|
SUPERVISOR_CLIENT,
|
||||||
|
grants(|g| g.call = vec![Pattern::prefix("agent."), Pattern::prefix("env.")]),
|
||||||
|
)
|
||||||
|
.client(
|
||||||
|
ENV_CLIENT,
|
||||||
|
grants(|g| g.register = vec![Pattern::exact(ENV_SERVICE)]),
|
||||||
|
)
|
||||||
|
.client(
|
||||||
|
&format!("{ENV_CLIENT}-r2"),
|
||||||
|
grants(|g| g.register = vec![Pattern::exact(ENV_SERVICE)]),
|
||||||
|
)
|
||||||
|
.client(
|
||||||
|
AGENT_CLIENT,
|
||||||
|
grants(|g| g.register = vec![Pattern::exact(&agent_service)]),
|
||||||
|
);
|
||||||
|
let mut router_config = RouterConfig::new(&store_root);
|
||||||
|
router_config.policy = policy;
|
||||||
|
let router = flybus::Router::new(router_config).map_err(|e| format!("router: {e}"))?;
|
||||||
|
let budget = ThreadBudget::new(2 + config.agent_threads, 1).map_err(|e| e.message)?;
|
||||||
|
let mut launcher = Launcher::start(
|
||||||
|
router,
|
||||||
|
config.mode,
|
||||||
|
// In-process participants reach the router in memory: no socket between two tasks
|
||||||
|
// of one process (a separate process always uses the socket).
|
||||||
|
Via::Memory,
|
||||||
|
&store_root,
|
||||||
|
&sockets,
|
||||||
|
budget,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("launcher: {}", e.message))?;
|
||||||
|
|
||||||
|
let mut backend = BackendConfig::legacy(&rom_digest);
|
||||||
|
backend.slots = vec![id(crate::task::SLOT)];
|
||||||
|
launcher
|
||||||
|
.launch_legacy_environment(LegacyEnvironmentLaunch {
|
||||||
|
session_id: session_id.clone(),
|
||||||
|
worker_id: id(ENV_WORKER),
|
||||||
|
incarnation_id: id("world-inc-1"),
|
||||||
|
worker_threads: 1,
|
||||||
|
rom_path: config.rom_path.clone(),
|
||||||
|
backend: backend.clone(),
|
||||||
|
client_id: ENV_CLIENT.to_owned(),
|
||||||
|
service: ENV_SERVICE.to_owned(),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("the world: {}", e.message))?;
|
||||||
|
let environment = launcher
|
||||||
|
.worker(&id(ENV_WORKER))
|
||||||
|
.expect("launched")
|
||||||
|
.worker_ref();
|
||||||
|
|
||||||
|
let (macro_channels, hold_ms) = channels_and_hold(config.macro_mode);
|
||||||
|
let identity = launcher
|
||||||
|
.launch_legacy_agent(LegacyAgentLaunch {
|
||||||
|
session_id: session_id.clone(),
|
||||||
|
agent_id: config.agent_id.clone(),
|
||||||
|
port_id: id(fly_session::legacy_env::DEFAULT_PORT),
|
||||||
|
incarnation_id: parse_id(&format!("{}-inc-1", config.agent_id))?,
|
||||||
|
worker_threads: config.agent_threads,
|
||||||
|
dataset_dir: config.dataset_dir.clone(),
|
||||||
|
profile: config.profile,
|
||||||
|
macro_channels: macro_channels.clone(),
|
||||||
|
client_id: AGENT_CLIENT.to_owned(),
|
||||||
|
service: agent_service,
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("the fly: {}", e.message))?;
|
||||||
|
let agent_ref = launcher
|
||||||
|
.worker(&config.agent_id)
|
||||||
|
.expect("launched")
|
||||||
|
.worker_ref();
|
||||||
|
let mut slot = AgentSlot::new(
|
||||||
|
agent_ref,
|
||||||
|
config.agent_id.clone(),
|
||||||
|
id(fly_session::legacy_env::DEFAULT_PORT),
|
||||||
|
config.profile.profile().asset,
|
||||||
|
fly_session::legacy_parity::LEGACY_SEED,
|
||||||
|
);
|
||||||
|
slot.worker_threads = identity.worker_threads as u64;
|
||||||
|
slot.model_version = gameboy::KERNEL_VERSION.to_owned();
|
||||||
|
slot.plasticity_version = gameboy::PLASTICITY_VERSION.to_owned();
|
||||||
|
|
||||||
|
let task = PokeredTask::new(
|
||||||
|
PokeredConfig {
|
||||||
|
agent_id: config.agent_id.clone(),
|
||||||
|
port_id: id(fly_session::legacy_env::DEFAULT_PORT),
|
||||||
|
mode: config.macro_mode,
|
||||||
|
macro_channels,
|
||||||
|
hold_ms,
|
||||||
|
record: config.record,
|
||||||
|
},
|
||||||
|
&rom,
|
||||||
|
&rom_digest,
|
||||||
|
&epoch,
|
||||||
|
)?;
|
||||||
|
let client = launcher
|
||||||
|
.connect(COORDINATOR_CLIENT)
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("connect: {}", e.message))?;
|
||||||
|
let executors: BTreeMap<Id, Box<dyn ActionExecutor>> =
|
||||||
|
BTreeMap::from([(config.agent_id.clone(), task.executor())]);
|
||||||
|
let mut coordinator = Coordinator::new(
|
||||||
|
client,
|
||||||
|
session_id.clone(),
|
||||||
|
epoch,
|
||||||
|
id("ep1"),
|
||||||
|
environment,
|
||||||
|
vec![slot],
|
||||||
|
task.task(),
|
||||||
|
executors,
|
||||||
|
);
|
||||||
|
coordinator.set_environment_config(
|
||||||
|
backend.asset_ref(),
|
||||||
|
fly_session::environment::synthetic_asset("pokered-task", gameboy::EXECUTOR_ID),
|
||||||
|
);
|
||||||
|
coordinator.set_media(
|
||||||
|
&[gameboy::VIEW_ID],
|
||||||
|
&[fly_session::legacy_env::AUDIO_STREAM_ID],
|
||||||
|
);
|
||||||
|
coordinator.set_state_format(fly_session::legacy_env::STATE_FORMAT_ID);
|
||||||
|
coordinator.set_decision_schema(gameboy::CHANNELS.schema_ref());
|
||||||
|
coordinator
|
||||||
|
.declare_rollback_policy(ROLLBACK_POLICY)
|
||||||
|
.map_err(|e| e.message)?;
|
||||||
|
// The legacy loop runs as fast as its brain allows when measured, and the service paces
|
||||||
|
// itself; a parity run is a measurement.
|
||||||
|
if config.record {
|
||||||
|
coordinator.request_commit_attachments(&[SPIKES_ATTACHMENT]);
|
||||||
|
} else {
|
||||||
|
// A service session runs indefinitely: its in-memory history stays bounded.
|
||||||
|
coordinator.bound_history(HISTORY);
|
||||||
|
// The legacy feed publishes at `snapshot_hz` (30 Hz) from a 60 Hz loop.
|
||||||
|
coordinator.snapshot_every(SNAPSHOT_EVERY);
|
||||||
|
}
|
||||||
|
Ok(LegacySession {
|
||||||
|
coordinator,
|
||||||
|
task,
|
||||||
|
launcher,
|
||||||
|
rom,
|
||||||
|
config,
|
||||||
|
session_id,
|
||||||
|
backend,
|
||||||
|
world_generation: 1,
|
||||||
|
checkpointer: None,
|
||||||
|
saves: 0,
|
||||||
|
pending_saves: Vec::new(),
|
||||||
|
pending_captures: Vec::new(),
|
||||||
|
last_event_id: 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hello, `Environment.Initialize` (the one-frame scaffold), the task's bootstrap on O[0],
|
||||||
|
/// `Agent.Initialize` (the warm-up): `Ready(0)`.
|
||||||
|
pub async fn bootstrap(&mut self) -> Result<(), String> {
|
||||||
|
self.coordinator
|
||||||
|
.bootstrap()
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("bootstrap ({}): {}", e.detail, e.error.message))?;
|
||||||
|
if self.config.record {
|
||||||
|
self.coordinator.disable_pacing();
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The agent's identity as an import stamps it.
|
||||||
|
pub fn agent_import(&self) -> AgentImport {
|
||||||
|
let (macro_channels, _) = channels_and_hold(self.config.macro_mode);
|
||||||
|
AgentImport {
|
||||||
|
agent_id: self.config.agent_id.clone(),
|
||||||
|
profile: self.config.profile.profile().asset,
|
||||||
|
seed: fly_session::legacy_parity::LEGACY_SEED,
|
||||||
|
macro_channels,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This build's legacy compatibility string ([`compatibility_of`]).
|
||||||
|
pub fn compatibility(&self) -> String {
|
||||||
|
compatibility_of(&self.config)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Installs a FLYSIM01 checkpoint as this session's start (after [`LegacySession::bootstrap`],
|
||||||
|
/// before any transition): the world is replaced by a fresh one (the environment stages a
|
||||||
|
/// restore only on a replacement, as every group restore does), then [`crate::import`] runs
|
||||||
|
/// the group install and the session resumes at the checkpoint's boundary.
|
||||||
|
pub async fn import_checkpoint(
|
||||||
|
&mut self,
|
||||||
|
checkpoint: &Checkpoint,
|
||||||
|
epoch: &Id,
|
||||||
|
) -> Result<crate::import::Imported, String> {
|
||||||
|
if self.world_generation != 1 {
|
||||||
|
return Err("this session has already replaced its world".to_owned());
|
||||||
|
}
|
||||||
|
self.launcher.reap(&id(ENV_WORKER), &id("import")).await;
|
||||||
|
self.world_generation = 2;
|
||||||
|
self.launcher
|
||||||
|
.launch_legacy_environment(LegacyEnvironmentLaunch {
|
||||||
|
session_id: self.session_id.clone(),
|
||||||
|
worker_id: id(ENV_WORKER),
|
||||||
|
incarnation_id: id("world-inc-2"),
|
||||||
|
worker_threads: 1,
|
||||||
|
rom_path: self.config.rom_path.clone(),
|
||||||
|
backend: self.backend.clone(),
|
||||||
|
client_id: format!("{ENV_CLIENT}-r2"),
|
||||||
|
service: ENV_SERVICE.to_owned(),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("the replacement world: {}", e.message))?;
|
||||||
|
let world = self
|
||||||
|
.launcher
|
||||||
|
.worker(&id(ENV_WORKER))
|
||||||
|
.expect("launched")
|
||||||
|
.worker_ref();
|
||||||
|
self.coordinator
|
||||||
|
.replace_participant(&id(ENV_WORKER), world)
|
||||||
|
.map_err(|e| format!("replacing the world: {}", e.error.message))?;
|
||||||
|
let rom = self.rom.clone();
|
||||||
|
let agent = self.agent_import();
|
||||||
|
let imported = crate::import::import_flysim01(
|
||||||
|
&mut self.coordinator,
|
||||||
|
&self.task,
|
||||||
|
checkpoint,
|
||||||
|
&rom,
|
||||||
|
&agent,
|
||||||
|
self.backend.audio_sample_rate,
|
||||||
|
epoch,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
if self.config.record {
|
||||||
|
self.coordinator.disable_pacing();
|
||||||
|
}
|
||||||
|
self.last_event_id = checkpoint.runtime.last_event_id;
|
||||||
|
Ok(imported)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes FLYSIM01 bytes and installs them ([`LegacySession::import_checkpoint`]).
|
||||||
|
pub async fn import_flysim01(
|
||||||
|
&mut self,
|
||||||
|
bytes: &[u8],
|
||||||
|
epoch: &Id,
|
||||||
|
) -> Result<crate::import::Imported, String> {
|
||||||
|
let checkpoint = flysim::store::decode(bytes).map_err(|e| format!("FLYSIM01: {e:#}"))?;
|
||||||
|
self.import_checkpoint(&checkpoint, epoch).await
|
||||||
|
}
|
||||||
|
|
||||||
|
// -- the store (STATE-02) ------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// Attaches the legacy store policy (`LegacyCheckpointer`): FLYSIM01 generations in the hot
|
||||||
|
/// and durable stores, milestone archives, the legacy intervals. Rollbacks are deferred from
|
||||||
|
/// here on, so a milestone capture lands between the boundary's slot save and its rollback.
|
||||||
|
pub fn attach_store(&mut self, store: &StoreConfig) -> Result<(), String> {
|
||||||
|
let checkpointer = LegacyCheckpointer::open(CheckpointerConfig {
|
||||||
|
hot_dir: store.hot_dir.clone(),
|
||||||
|
durable_dir: store.durable_dir.clone(),
|
||||||
|
keep_generations: store.keep_generations,
|
||||||
|
hot_seconds: store.hot_seconds,
|
||||||
|
checkpoint_seconds: store.checkpoint_seconds,
|
||||||
|
compatibility: self.compatibility(),
|
||||||
|
speed: store.speed,
|
||||||
|
slot_id: id(crate::task::SLOT),
|
||||||
|
})?;
|
||||||
|
self.checkpointer = Some(checkpointer);
|
||||||
|
self.coordinator.defer_rollbacks(true);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn checkpointer(&self) -> Option<&LegacyCheckpointer> {
|
||||||
|
self.checkpointer.as_ref()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn checkpointer_mut(&mut self) -> Option<&mut LegacyCheckpointer> {
|
||||||
|
self.checkpointer.as_mut()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One save of the committed boundary, written by the checkpointer's writer thread; waits for
|
||||||
|
/// the commit, so a caller that goes on to read the store finds it. For the startup and
|
||||||
|
/// shutdown saves, which the legacy loop takes blocking too.
|
||||||
|
pub async fn save(&mut self, kind: SaveKind) -> Result<SaveReport, String> {
|
||||||
|
let ticket = self.queue_save(kind).await?;
|
||||||
|
ticket
|
||||||
|
.reply
|
||||||
|
.await
|
||||||
|
.map_err(|_| "the checkpoint writer stopped".to_owned())?
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One save of the committed boundary, queued: the participants capture now (the boundary's
|
||||||
|
/// state) and the encoding and fsync run on the checkpointer's writer thread while the loop
|
||||||
|
/// goes on, as the legacy loop hands its saves to its writer thread (TASK-01 review N4). The
|
||||||
|
/// outcome is collected by [`LegacySession::completed_saves`].
|
||||||
|
pub async fn queue_save(&mut self, kind: SaveKind) -> Result<SaveTicket, String> {
|
||||||
|
self.begin_save(kind).await?;
|
||||||
|
let mut tickets = self.finish_captures().await?;
|
||||||
|
let last = tickets
|
||||||
|
.pop()
|
||||||
|
.ok_or_else(|| "no save was begun".to_owned())?;
|
||||||
|
self.pending_saves.extend(tickets);
|
||||||
|
Ok(last)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Begins one save of the committed boundary: every participant's `State.Capture` is sent
|
||||||
|
/// (each takes its state now) and the task's half is taken now; the session may step on
|
||||||
|
/// while the agent encodes and seals its payload off its lock
|
||||||
|
/// (`Coordinator::begin_capture`, TASK-01 review N5). [`LegacySession::finish_captures`]
|
||||||
|
/// hands it to the writer.
|
||||||
|
pub async fn begin_save(&mut self, kind: SaveKind) -> Result<(), String> {
|
||||||
|
self.saves += 1;
|
||||||
|
let capture = self
|
||||||
|
.coordinator
|
||||||
|
.begin_capture(&parse_id(&format!("legacy-save-{}", self.saves))?)
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("capture ({}): {}", e.detail, e.error.message))?;
|
||||||
|
let (task, _slot_filled) = self.task.task_half();
|
||||||
|
self.pending_captures.push((capture, kind, task));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Collects every begun capture, in order, and queues it to the checkpointer's writer.
|
||||||
|
pub async fn finish_captures(&mut self) -> Result<Vec<SaveTicket>, String> {
|
||||||
|
let mut tickets = Vec::new();
|
||||||
|
for (capture, kind, task) in std::mem::take(&mut self.pending_captures) {
|
||||||
|
let (boundary, world, agents) = self
|
||||||
|
.coordinator
|
||||||
|
.finish_capture(capture)
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("capture ({}): {}", e.detail, e.error.message))?;
|
||||||
|
let [(_, agent)] = <[(Id, Vec<u8>); 1]>::try_from(agents)
|
||||||
|
.map_err(|_| "the legacy composition has exactly one agent".to_owned())?;
|
||||||
|
let capture = LegacyCapture {
|
||||||
|
boundary,
|
||||||
|
agent_payload: agent,
|
||||||
|
world_payload: world,
|
||||||
|
task,
|
||||||
|
};
|
||||||
|
let last_event_id = self.last_event_id;
|
||||||
|
let checkpointer = self.checkpointer.as_mut().ok_or("no store is attached")?;
|
||||||
|
tickets.push(checkpointer.save(kind, capture, last_event_id, now_wall_ms())?);
|
||||||
|
}
|
||||||
|
Ok(tickets)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The saves queued so far that have committed (or failed), without waiting; with `wait`,
|
||||||
|
/// every queued save's outcome. Every outcome is reported, a failed save as its own `Err`
|
||||||
|
/// beside the others (TASK-01 review R2-2): the caller decides.
|
||||||
|
pub async fn completed_saves(&mut self, wait: bool) -> Vec<Result<SaveReport, String>> {
|
||||||
|
let mut done = Vec::new();
|
||||||
|
let mut still = Vec::new();
|
||||||
|
for mut ticket in std::mem::take(&mut self.pending_saves) {
|
||||||
|
let stopped = || Err("the checkpoint writer stopped".to_owned());
|
||||||
|
if wait {
|
||||||
|
done.push((&mut ticket.reply).await.unwrap_or_else(|_| stopped()));
|
||||||
|
} else {
|
||||||
|
match ticket.reply.try_recv() {
|
||||||
|
Ok(result) => done.push(result),
|
||||||
|
Err(tokio::sync::oneshot::error::TryRecvError::Empty) => still.push(ticket),
|
||||||
|
Err(tokio::sync::oneshot::error::TryRecvError::Closed) => done.push(stopped()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.pending_saves = still;
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hands every begun capture to the writer now and reports what was queued. `advance` does
|
||||||
|
/// this after the next step so the agent's sealing overlaps it; a step that fails does it
|
||||||
|
/// before returning the error, and a caller that pauses (or is about to stop stepping) calls
|
||||||
|
/// this so a save begun at the last boundary reaches the writer as the legacy loop's
|
||||||
|
/// immediate hand-off would have (TASK-01 review R2-1).
|
||||||
|
pub async fn flush_captures(&mut self) -> Result<Vec<SaveQueued>, String> {
|
||||||
|
let mut saves = Vec::new();
|
||||||
|
for ticket in self.finish_captures().await? {
|
||||||
|
saves.push(SaveQueued {
|
||||||
|
generation: ticket.generation,
|
||||||
|
durable: ticket.durable,
|
||||||
|
archive_rank: ticket.archive_rank,
|
||||||
|
});
|
||||||
|
self.pending_saves.push(ticket);
|
||||||
|
}
|
||||||
|
Ok(saves)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One transition and what the legacy loop does at the boundary it reaches, in the declared
|
||||||
|
/// order (`legacy-gameboy-v1` sections 4 and 16): the slot save (inside the step), the
|
||||||
|
/// milestone archive when the rank climbed (`Sim::track_rank`), the rollback, a durable save
|
||||||
|
/// after it, then the interval saves (`checkpoint_if_due`).
|
||||||
|
pub async fn advance(&mut self) -> Result<(Step, Vec<SaveQueued>), String> {
|
||||||
|
let report = match self.coordinator.step().await {
|
||||||
|
Ok(report) => report,
|
||||||
|
Err(e) => {
|
||||||
|
// The legacy writer already has the saves of the earlier boundaries: hand the
|
||||||
|
// begun captures over before reporting the failure (TASK-01 review R2-1).
|
||||||
|
let flushed = self.flush_captures().await.err();
|
||||||
|
let mut message =
|
||||||
|
format!("step ({} at {}): {}", e.detail, e.phase, e.error.message);
|
||||||
|
if let Some(flush) = flushed {
|
||||||
|
message.push_str(&format!("; and the pending saves: {flush}"));
|
||||||
|
}
|
||||||
|
return Err(message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// The captures begun at the last boundary: the agent sealed its payload while this
|
||||||
|
// transition's Prepare ticked.
|
||||||
|
let saves = self.flush_captures().await?;
|
||||||
|
if self.checkpointer.is_some() {
|
||||||
|
let rank = self.task.rank();
|
||||||
|
let ms = self.task.brain_ms();
|
||||||
|
let change = self
|
||||||
|
.checkpointer
|
||||||
|
.as_mut()
|
||||||
|
.expect("attached")
|
||||||
|
.observe_rank(rank, ms);
|
||||||
|
if let Some(RankChange::Climbed(rank)) = change {
|
||||||
|
self.begin_save(SaveKind::Milestone(rank)).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let rolled_back = self
|
||||||
|
.coordinator
|
||||||
|
.apply_pending_rollback()
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
format!(
|
||||||
|
"rollback ({} at {}): {}",
|
||||||
|
e.detail, e.phase, e.error.message
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
if self.checkpointer.is_some() {
|
||||||
|
if rolled_back {
|
||||||
|
self.begin_save(SaveKind::Durable).await?;
|
||||||
|
}
|
||||||
|
let due = self
|
||||||
|
.checkpointer
|
||||||
|
.as_mut()
|
||||||
|
.expect("attached")
|
||||||
|
.due(Instant::now());
|
||||||
|
if let Some(kind) = due {
|
||||||
|
self.begin_save(kind).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok((
|
||||||
|
Step {
|
||||||
|
report,
|
||||||
|
details: self.coordinator.take_details(),
|
||||||
|
records: self.task.take_records(),
|
||||||
|
},
|
||||||
|
saves,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One transition, with its details when recorded ([`LegacySession::advance`] without the
|
||||||
|
/// saves it reports).
|
||||||
|
pub async fn step(&mut self) -> Result<Step, String> {
|
||||||
|
self.advance().await.map(|(step, _)| step)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A durable save, as the legacy loop takes on shutdown, then the store's writer is closed.
|
||||||
|
pub async fn shutdown_save(&mut self) -> Result<Option<SaveReport>, String> {
|
||||||
|
if self.checkpointer.is_none() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
self.flush_captures().await?;
|
||||||
|
let report = self.save(SaveKind::Durable).await?;
|
||||||
|
let outcomes = self.completed_saves(true).await;
|
||||||
|
if let Some(checkpointer) = self.checkpointer.as_mut() {
|
||||||
|
checkpointer.close();
|
||||||
|
}
|
||||||
|
// Every queued save has been waited for; the first failure is the shutdown's.
|
||||||
|
for outcome in outcomes {
|
||||||
|
outcome?;
|
||||||
|
}
|
||||||
|
Ok(Some(report))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn stop(mut self) {
|
||||||
|
self.launcher.reap_all(&id("done")).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
79
services/flysim/crates/fly-legacy-session/src/driver.rs
Normal file
79
services/flysim/crates/fly-legacy-session/src/driver.rs
Normal file
|
|
@ -0,0 +1,79 @@
|
||||||
|
//! A stub readout for parity runs that must earn real rewards: the rotation driver of flysim's ROM
|
||||||
|
//! tests (`tests/rom_catch.rs`, `tests/rom_macros_mode.rs`) -- a decoder of its own, fed rates
|
||||||
|
//! that lean on one macro population at a time, rotating every [`BURST_FRAMES`] frames.
|
||||||
|
//!
|
||||||
|
//! The brain still ticks and decodes exactly as it would; the driver only replaces the decision
|
||||||
|
//! the executor is handed, at the one point the legacy loop lets a harness do that
|
||||||
|
//! (`flysim::frame::FrameObserver::readout`). A session run hands the same driver the same
|
||||||
|
//! `(ms, bound)` in its executor ([`crate::task::PokeredTask::set_driver`]), so both arms press the
|
||||||
|
//! same macros and the rewards those macros earn reach `Agent.Commit`. Not a service path.
|
||||||
|
|
||||||
|
use flybrain_core::decoder::PopulationDecoder;
|
||||||
|
use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros;
|
||||||
|
use flybrain_core::ordered::NumberMap;
|
||||||
|
|
||||||
|
/// Frames the stub leans on one channel before the rotation moves on (`rom_catch.rs`).
|
||||||
|
pub const BURST_FRAMES: u32 = 24;
|
||||||
|
/// The hot population's rate, and every other one's (`rom_catch.rs`).
|
||||||
|
const HOT: f64 = 16.0;
|
||||||
|
const REST: f64 = 10.0;
|
||||||
|
|
||||||
|
/// Replaces a decision, given the brain clock and the scene's bound channels.
|
||||||
|
pub trait DecisionDriver: Send {
|
||||||
|
fn readout(&mut self, ms: f64, bound: &[String], active: &mut Vec<String>);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The rotation: one macro population hot at a time, in channel order.
|
||||||
|
pub struct RotationDriver {
|
||||||
|
decoder: PopulationDecoder,
|
||||||
|
channels: Vec<&'static str>,
|
||||||
|
frame: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for RotationDriver {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RotationDriver {
|
||||||
|
pub fn new() -> RotationDriver {
|
||||||
|
let channels = flybrain_gb::macro_channels(crate::task::GAME);
|
||||||
|
let mut decoder = PopulationDecoder::new(gameboy_decoder_config_with_macros(&channels))
|
||||||
|
.expect("the preset is well formed");
|
||||||
|
decoder.calibrate(&rates(&channels, None));
|
||||||
|
RotationDriver {
|
||||||
|
decoder,
|
||||||
|
channels,
|
||||||
|
frame: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rates(channels: &[&str], hot: Option<&str>) -> NumberMap {
|
||||||
|
let mut rates = NumberMap::new();
|
||||||
|
for channel in channels {
|
||||||
|
rates.set(channel, REST);
|
||||||
|
}
|
||||||
|
for bucket in 0..8 {
|
||||||
|
rates.set(&format!("command_{bucket}"), REST);
|
||||||
|
}
|
||||||
|
if let Some(channel) = hot {
|
||||||
|
rates.set(channel, HOT);
|
||||||
|
}
|
||||||
|
rates
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DecisionDriver for RotationDriver {
|
||||||
|
fn readout(&mut self, ms: f64, bound: &[String], active: &mut Vec<String>) {
|
||||||
|
let hot = self.channels[(self.frame / BURST_FRAMES) as usize % self.channels.len()];
|
||||||
|
self.frame += 1;
|
||||||
|
*active = self.decoder.decode_bound(
|
||||||
|
&rates(&self.channels, Some(hot)),
|
||||||
|
ms,
|
||||||
|
false,
|
||||||
|
None,
|
||||||
|
Some(bound),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
140
services/flysim/crates/fly-legacy-session/src/import.rs
Normal file
140
services/flysim/crates/fly-legacy-session/src/import.rs
Normal file
|
|
@ -0,0 +1,140 @@
|
||||||
|
//! A FLYSIM01 checkpoint as a session's start: the legacy fly's own save, installed into the new
|
||||||
|
//! runtime through the ordinary group restore (`Coordinator::import`).
|
||||||
|
//!
|
||||||
|
//! The halves are STATE-02's (`fly_session::legacy_checkpoint`): the world as ENV-01's `FLYENV01`
|
||||||
|
//! payload at `k = emulatorFrame - 1` with the ratchet's snapshot as slot `best`; the agent as its
|
||||||
|
//! `FLYAGT01` payload with the file's reinforcement count and the file's framebuffer as the next
|
||||||
|
//! input, as `LegacyFrame::restore` installs it; the task as `{reward, ratchet, slotFilled}`. The ids
|
||||||
|
//! come from the file (`flysim01-g<generation>`, source scope `(session, legacy, k)`).
|
||||||
|
//!
|
||||||
|
//! The rest is `restore: legacy-transient-reset` (`legacy-gameboy-v1` section 14): the executor
|
||||||
|
//! starts fresh and observes the restored boundary, and the agent's readout transient starts as a
|
||||||
|
//! fresh process has it. The decision context the agent resumes with is computed here, from the
|
||||||
|
//! task's ledger and the checkpoint's own memory image. After the install the coordinator holds the
|
||||||
|
//! task to it: `Task::restored` re-observes the restored world and must derive the same context.
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use fly_session::coordinator::{Coordinator, ImportSpec, ImportedAgent};
|
||||||
|
use fly_session::legacy_agent::legacy_remainder_to_rational;
|
||||||
|
use fly_session::legacy_checkpoint::{
|
||||||
|
AgentImport, agent_payload, halves, import_checkpoint_id, legacy_source_scope, world_payload,
|
||||||
|
};
|
||||||
|
use fly_session::types::*;
|
||||||
|
use flybrain_gb::{DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator, MemoryImage};
|
||||||
|
use flysim::store::Checkpoint;
|
||||||
|
|
||||||
|
use crate::task::PokeredTask;
|
||||||
|
|
||||||
|
/// What an import installed.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Imported {
|
||||||
|
pub boundary: u64,
|
||||||
|
pub epoch: Id,
|
||||||
|
pub brain_ticks: u64,
|
||||||
|
pub checkpoint_id: Id,
|
||||||
|
/// The file's `rankSinceMs` and generation, for the host's rank tracking and store.
|
||||||
|
pub rank_since_ms: f64,
|
||||||
|
pub generation: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The checkpoint's memory image at its boundary, read as the environment reads it after an
|
||||||
|
/// import: the emulator state imported into a stopped emulator, then MEM-01's one bulk read.
|
||||||
|
pub fn image_of(rom: &[u8], emulator_state: &[u8]) -> Result<MemoryImage, String> {
|
||||||
|
let mut emulator = Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES)
|
||||||
|
.map_err(|e| format!("the cartridge: {e}"))?;
|
||||||
|
emulator
|
||||||
|
.import_state(emulator_state)
|
||||||
|
.map_err(|e| format!("the emulator state: {e}"))?;
|
||||||
|
Ok(emulator.read_memory_image())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Installs a FLYSIM01 checkpoint as the start of a bootstrapped session that has taken no
|
||||||
|
/// transition, onto a replacement world. `task` is the composition's task object.
|
||||||
|
pub async fn import_flysim01(
|
||||||
|
coordinator: &mut Coordinator,
|
||||||
|
task: &PokeredTask,
|
||||||
|
checkpoint: &Checkpoint,
|
||||||
|
rom: &[u8],
|
||||||
|
agent: &AgentImport,
|
||||||
|
audio_sample_rate: u64,
|
||||||
|
new_epoch: &Id,
|
||||||
|
) -> Result<Imported, String> {
|
||||||
|
let descriptor = coordinator
|
||||||
|
.descriptor()
|
||||||
|
.cloned()
|
||||||
|
.ok_or("the session never bootstrapped")?;
|
||||||
|
let halves = halves(
|
||||||
|
checkpoint,
|
||||||
|
coordinator.episode_id(),
|
||||||
|
&id(crate::task::SLOT),
|
||||||
|
audio_sample_rate,
|
||||||
|
)?;
|
||||||
|
let boundary = halves.world.boundary;
|
||||||
|
let checkpoint_id = import_checkpoint_id(halves.host.generation);
|
||||||
|
let scope = legacy_source_scope(coordinator.session_id(), boundary);
|
||||||
|
let world = world_payload(
|
||||||
|
&halves.world,
|
||||||
|
&coordinator.environment_ref().worker_id,
|
||||||
|
&checkpoint_id,
|
||||||
|
&scope,
|
||||||
|
&descriptor.configuration_digest,
|
||||||
|
);
|
||||||
|
|
||||||
|
// The task's ledger, and from it and the restored image the context the agent resumes with.
|
||||||
|
let (ledger, task_attachments) =
|
||||||
|
PokeredTask::ledger_of(&halves.task, !checkpoint.runtime.ratchet_game.is_empty())
|
||||||
|
.map_err(|e| format!("the task ledger: {}", e.message))?;
|
||||||
|
let brain_ms = halves.agent.network.ms;
|
||||||
|
// `Sim::boot` seeds the palette from the restored brain's RNG state.
|
||||||
|
task.set_palette_seed(halves.agent.network.rng as u32);
|
||||||
|
let image = image_of(rom, &halves.world.emulator)?;
|
||||||
|
let context = task.preview_context(&ledger, &task_attachments, &image, brain_ms)?;
|
||||||
|
let payload = agent_payload(
|
||||||
|
&halves.agent,
|
||||||
|
halves.reinforcements,
|
||||||
|
&checkpoint.runtime.framebuffer,
|
||||||
|
agent,
|
||||||
|
&checkpoint_id,
|
||||||
|
&scope,
|
||||||
|
&context,
|
||||||
|
)?;
|
||||||
|
let remainder = legacy_remainder_to_rational(halves.agent.remainder)
|
||||||
|
.map_err(|e| format!("the remainder: {e}"))?;
|
||||||
|
let audio_positions: BTreeMap<String, u64> = descriptor
|
||||||
|
.audio
|
||||||
|
.iter()
|
||||||
|
.map(|stream| (stream.stream_id.clone(), halves.world.audio_next_sample))
|
||||||
|
.collect();
|
||||||
|
let spec = ImportSpec {
|
||||||
|
checkpoint_id: checkpoint_id.clone(),
|
||||||
|
source_scope: scope,
|
||||||
|
boundary,
|
||||||
|
world_payload: world,
|
||||||
|
agents: vec![ImportedAgent {
|
||||||
|
agent_id: agent.agent_id.clone(),
|
||||||
|
payload,
|
||||||
|
brain_ticks: brain_ms as u64,
|
||||||
|
remainder,
|
||||||
|
context,
|
||||||
|
}],
|
||||||
|
task_ledger: ledger,
|
||||||
|
task_attachments,
|
||||||
|
audio_positions,
|
||||||
|
};
|
||||||
|
coordinator
|
||||||
|
.import(spec, new_epoch)
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("the import ({}): {}", e.detail, e.error.message))?;
|
||||||
|
coordinator
|
||||||
|
.resume()
|
||||||
|
.map_err(|e| format!("resuming the import: {}", e.error.message))?;
|
||||||
|
Ok(Imported {
|
||||||
|
boundary,
|
||||||
|
epoch: new_epoch.clone(),
|
||||||
|
brain_ticks: brain_ms as u64,
|
||||||
|
checkpoint_id,
|
||||||
|
rank_since_ms: halves.host.rank_since_ms,
|
||||||
|
generation: halves.host.generation,
|
||||||
|
})
|
||||||
|
}
|
||||||
19
services/flysim/crates/fly-legacy-session/src/lib.rs
Normal file
19
services/flysim/crates/fly-legacy-session/src/lib.rs
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
//! The live fly on the session framework (TASK-01).
|
||||||
|
//!
|
||||||
|
//! - [`task`]: `pokered-macros-v1`, the Pokémon Red task and its action executor as one object,
|
||||||
|
//! running the legacy macro engine and reward adapter unchanged over the boundary memory image.
|
||||||
|
//! - [`composition`]: the legacy agent, the legacy environment and the task under one coordinator.
|
||||||
|
//! - [`import`]: a FLYSIM01 checkpoint as the session's start.
|
||||||
|
//! - [`admission`]: sugar by the legacy rules; the operator reward pulse refused.
|
||||||
|
//! - [`trace`]: the session's `FLY_TRACE`, in the legacy loop's format, and the comparison.
|
||||||
|
//! - [`driver`]: a stub readout for parity runs that must earn rewards.
|
||||||
|
//!
|
||||||
|
//! `docs/design/session-framework/legacy-gameboy-v1.md` is the contract, `implementation.md`
|
||||||
|
//! TASK-01 the record.
|
||||||
|
|
||||||
|
pub mod admission;
|
||||||
|
pub mod composition;
|
||||||
|
pub mod driver;
|
||||||
|
pub mod import;
|
||||||
|
pub mod task;
|
||||||
|
pub mod trace;
|
||||||
985
services/flysim/crates/fly-legacy-session/src/task.rs
Normal file
985
services/flysim/crates/fly-legacy-session/src/task.rs
Normal file
|
|
@ -0,0 +1,985 @@
|
||||||
|
//! `pokered-macros-v1`: the Pokémon Red task and its action executor, one object
|
||||||
|
//! (`legacy-gameboy-v1` section 10, `workers-v1` section 4 amendment of 2026-09-23).
|
||||||
|
//!
|
||||||
|
//! Nothing here is a port of a rule. The reward adapter (`PokemonRedReward`), the ratchet, and the
|
||||||
|
//! macro layer (`flysim::macros::MacroLayer` over `flybrain-gb`'s palette, executor and `PokeState`)
|
||||||
|
//! are the very types the legacy loop runs, called in `flysim::frame::LegacyFrame`'s order. What
|
||||||
|
//! changed is what they read: a boundary's 64 KiB memory image and the cartridge, through
|
||||||
|
//! `flybrain_gb::ImageReader` (MEM-01), instead of a live emulator.
|
||||||
|
//!
|
||||||
|
//! | legacy frame | here |
|
||||||
|
//! | --- | --- |
|
||||||
|
//! | `execute`: `MacroLayer::decide` over the emulator | Phase B, [`ActionExecutor::apply`] over `ImageReader(O[k])` |
|
||||||
|
//! | `evaluate`: `adapter.sample`, `MacroLayer::observe`, location, progress | Phase C, [`Task::evaluate_transition`] over `ImageReader(O[k+1])` |
|
||||||
|
//! | `boundary`: the ratchet's capture and decision | Phase C too: a slot save and a rollback request, applied by the coordinator at `Ready(k+1)` |
|
||||||
|
//! | `rollback`: `recover_game`'s `clear_transient`, `cancel`, `observe` | [`Task::rollback`] over `ImageReader(O'[k+1])` |
|
||||||
|
//!
|
||||||
|
//! The ratchet keeps its ledger here; its *slot* lives in the environment (`gameboy-slots-v1`).
|
||||||
|
//! The ratchet only needs to know a slot exists (its budget test is `snapshot.is_none()`), so it
|
||||||
|
//! holds a marker [`Snapshot`] in place of the bytes.
|
||||||
|
//!
|
||||||
|
//! `restore: legacy-transient-reset` (section 14): a restore installs the adapter and the ratchet,
|
||||||
|
//! and the executor starts as a fresh process has it -- a new macro layer with empty ledgers and
|
||||||
|
//! nothing running, which observes the restored boundary before it decides anything.
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::sync::{Arc, Mutex, MutexGuard};
|
||||||
|
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
use fly_session::fly_session_types::gameboy::{
|
||||||
|
self, ChannelsDecision, Location, MemoryInspection, ReadoutContext, RollbackRequest,
|
||||||
|
};
|
||||||
|
use fly_session::legacy_checkpoint::TaskHalf;
|
||||||
|
use fly_session::task::{
|
||||||
|
ActionExecutor, Bootstrap, Evaluation, Inspection, RollbackEvaluation, Task,
|
||||||
|
};
|
||||||
|
use fly_session::types::*;
|
||||||
|
use flybrain_core::decoder::gameboy::to_button_mask;
|
||||||
|
use flybrain_gb::adapter::GameAdapter;
|
||||||
|
use flybrain_gb::emulator::FRAMEBUFFER_LEN;
|
||||||
|
use flybrain_gb::pokemon_red::PokemonRedReward;
|
||||||
|
use flybrain_gb::ratchet::{Ratchet, Snapshot};
|
||||||
|
use flybrain_gb::{AdapterLedger, Cartridge, ImageReader, MemoryImage};
|
||||||
|
use flysim::config::Config;
|
||||||
|
use flysim::macros::{MacroEvent, MacroLayer, macro_layer};
|
||||||
|
use flysim::snapshot::MacroMode;
|
||||||
|
|
||||||
|
/// The attachment the image travels under (ENV-01's `legacy_env::MEMORY_ATTACHMENT`).
|
||||||
|
pub const MEMORY_ATTACHMENT: &str = fly_session::legacy_env::MEMORY_ATTACHMENT;
|
||||||
|
/// The composition's one slot, which is the ratchet's.
|
||||||
|
pub const SLOT: &str = fly_session::legacy_env::DEFAULT_SLOT;
|
||||||
|
/// The game id the adapter and the palette are chosen by.
|
||||||
|
pub const GAME: &str = "pokemon-red";
|
||||||
|
/// The palette seed of a fresh start. The legacy loop seeds the palette from the brain's RNG
|
||||||
|
/// state after the warm-up (`Sim::boot`: `rng_state() as u32`), which the task cannot read: the
|
||||||
|
/// agent does not publish it. It is also never read: `MacroMachine`'s generator is written and
|
||||||
|
/// never consulted (no macro has a random step), which `tests/palette_seed.rs` holds on the
|
||||||
|
/// cartridge, so a fresh start's constant presses exactly what the legacy seed presses. A
|
||||||
|
/// restore uses the legacy seed itself, the imported agent state's RNG
|
||||||
|
/// ([`PokeredTask::set_palette_seed`]).
|
||||||
|
pub const PALETTE_SEED: u32 = 0;
|
||||||
|
|
||||||
|
fn schema(name: &str) -> SchemaRef {
|
||||||
|
let digest = digest_of_bytes(format!("fly-legacy-session-schema-v1\n{name}\n1\n").as_bytes());
|
||||||
|
SchemaRef::new(name, 1, &digest).expect("a task-local schema reference is valid")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The task ledger's schema: STATE-02's `TaskHalf` ledger `{reward, ratchet, slotFilled}` --
|
||||||
|
/// FLYSIM01's `reward` and `ratchet`, and whether the environment's slot `best` holds the
|
||||||
|
/// ratchet's snapshot. Nothing else: the executor's ledgers and the adapter's transient
|
||||||
|
/// observations are not captured (`legacy-transient-reset`).
|
||||||
|
pub fn ledger_schema() -> SchemaRef {
|
||||||
|
schema("pokered-task-ledger-v1")
|
||||||
|
}
|
||||||
|
/// The attachment the task ledger's adapter state travels as (its JSON).
|
||||||
|
pub const REWARD_ATTACHMENT: &str = "reward";
|
||||||
|
|
||||||
|
/// The executor's capture: a marker only, because its state is transient (section 10, "Capture").
|
||||||
|
pub fn executor_schema() -> SchemaRef {
|
||||||
|
schema("pokered.executor.v1")
|
||||||
|
}
|
||||||
|
pub fn progress_schema() -> SchemaRef {
|
||||||
|
schema("pokered.progress.v1")
|
||||||
|
}
|
||||||
|
pub fn event_schema() -> SchemaRef {
|
||||||
|
schema("pokered.event.v1")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn state_error(message: impl std::fmt::Display) -> DomainError {
|
||||||
|
DomainError::before(ErrorCode::IncompatibleState, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ratchet's stand-in for a slot it knows the environment holds.
|
||||||
|
fn slot_marker() -> Snapshot {
|
||||||
|
Snapshot {
|
||||||
|
game: format!("slot:{SLOT}").into_bytes(),
|
||||||
|
frame: vec![0; FRAMEBUFFER_LEN],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The legacy trace's JSON of one macro event (`flysim::trace::macro_json`).
|
||||||
|
pub fn macro_json(phase: &str, event: &MacroEvent) -> Value {
|
||||||
|
json!({
|
||||||
|
"phase": phase,
|
||||||
|
"slot": event.slot,
|
||||||
|
"name": event.name,
|
||||||
|
"outcome": event.outcome.map(|outcome| outcome.as_str()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the object did in one transition, for the trace and the ledger comparison: the fields of
|
||||||
|
/// `flysim-legacy-frame-trace-v1` that are the task's and the executor's.
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq)]
|
||||||
|
pub struct TaskRecord {
|
||||||
|
/// The boundary the transition started from.
|
||||||
|
pub boundary: u64,
|
||||||
|
/// The decision as the executor was given it, as the legacy active set (buttons, then the
|
||||||
|
/// macro channel).
|
||||||
|
pub decision: Vec<String>,
|
||||||
|
/// The bound channels the decision was masked to (the context of this transition's Prepare).
|
||||||
|
pub bound: Vec<String>,
|
||||||
|
pub mask: u32,
|
||||||
|
/// `macroEvents`, phases `execute`, `evaluate` and `rollback`, in order.
|
||||||
|
pub macro_events: Vec<Value>,
|
||||||
|
/// SHA-256 of work RAM, `$C000-$DFFF`, of O[k+1].
|
||||||
|
pub wram_digest: String,
|
||||||
|
/// `rewards`: `{kind, value, stimulationMs}` in adapter order.
|
||||||
|
pub rewards: Vec<Value>,
|
||||||
|
pub rank: u32,
|
||||||
|
/// The ratchet asked for a slot save at `Ready(k+1)`.
|
||||||
|
pub saved: bool,
|
||||||
|
/// The ratchet asked for a rollback at `Ready(k+1)`, and it ran.
|
||||||
|
pub rolled_back: bool,
|
||||||
|
/// The ledgers after the boundary: adapter, ratchet and executor, as one canonical string.
|
||||||
|
pub ledgers: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ledgers as one canonical string: the adapter's export (its lifetime ledgers), the
|
||||||
|
/// ratchet's state and whether it holds a slot, and the executor's observable state -- scene,
|
||||||
|
/// bound channels, running macro, outcome counts, "nearer the objective". A legacy loop computes
|
||||||
|
/// the same string from its own parts, which is how a parity run compares ledgers frame by frame.
|
||||||
|
pub fn ledgers_of(
|
||||||
|
adapter: &PokemonRedReward,
|
||||||
|
ratchet: &Ratchet,
|
||||||
|
macros: Option<&MacroLayer>,
|
||||||
|
) -> String {
|
||||||
|
let executor = match 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()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How the object is configured. Everything here is composition, not state.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct PokeredConfig {
|
||||||
|
pub agent_id: Id,
|
||||||
|
pub port_id: Id,
|
||||||
|
pub mode: MacroMode,
|
||||||
|
/// `executor.macroChannels`, composition order; empty in raw mode.
|
||||||
|
pub macro_channels: Vec<String>,
|
||||||
|
/// The macro group's `holdMs` from the decoder configuration.
|
||||||
|
pub hold_ms: f64,
|
||||||
|
/// Record a [`TaskRecord`] per transition (a parity run); off in service.
|
||||||
|
pub record: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Inner {
|
||||||
|
config: PokeredConfig,
|
||||||
|
cartridge: Cartridge,
|
||||||
|
adapter: PokemonRedReward,
|
||||||
|
ratchet: Ratchet,
|
||||||
|
macros: Option<MacroLayer>,
|
||||||
|
epoch: Id,
|
||||||
|
/// O[k]: the image the executor reads in Phase B and the task reads as "old" in Phase C.
|
||||||
|
current: Option<(u64, MemoryImage)>,
|
||||||
|
/// The brain clock of the transition in flight (Phase B's clock), in ms.
|
||||||
|
ms: f64,
|
||||||
|
evaluations: u64,
|
||||||
|
issued: u64,
|
||||||
|
last_source_step: u64,
|
||||||
|
open: Option<TaskRecord>,
|
||||||
|
records: Vec<TaskRecord>,
|
||||||
|
/// A parity run's stub readout ([`crate::driver`]); never set in service.
|
||||||
|
driver: Option<Box<dyn crate::driver::DecisionDriver>>,
|
||||||
|
/// Addresses the engine read that the image does not capture ([`Watched`]).
|
||||||
|
uncaptured: std::collections::BTreeSet<u16>,
|
||||||
|
/// The seed the next fresh macro layer is built with ([`PALETTE_SEED`], or a restored
|
||||||
|
/// agent's RNG state as the legacy loop seeds it).
|
||||||
|
palette_seed: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one object. [`PokeredTask::task`] and [`PokeredTask::executor`] are its two faces; the
|
||||||
|
/// coordinator holds each where it expects a task and an executor, and both reach the same state.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct PokeredTask {
|
||||||
|
inner: Arc<Mutex<Inner>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PokeredTask {
|
||||||
|
/// A fresh object over the cartridge. `rom_digest` is the environment's `contentDigest`: a
|
||||||
|
/// cartridge that is not it is refused (`legacy-gameboy-v1` section 8).
|
||||||
|
pub fn new(
|
||||||
|
config: PokeredConfig,
|
||||||
|
rom: &[u8],
|
||||||
|
rom_digest: &str,
|
||||||
|
epoch: &Id,
|
||||||
|
) -> Result<Self, String> {
|
||||||
|
let cartridge = Cartridge::verified(rom, rom_digest).map_err(|e| e.to_string())?;
|
||||||
|
let adapter = PokemonRedReward::new();
|
||||||
|
let ratchet = Ratchet::with_policy(adapter.recovery_policy());
|
||||||
|
let macros = fresh_layer(&config, PALETTE_SEED);
|
||||||
|
Ok(Self {
|
||||||
|
inner: Arc::new(Mutex::new(Inner {
|
||||||
|
config,
|
||||||
|
cartridge,
|
||||||
|
adapter,
|
||||||
|
ratchet,
|
||||||
|
macros,
|
||||||
|
epoch: epoch.clone(),
|
||||||
|
current: None,
|
||||||
|
ms: 0.0,
|
||||||
|
evaluations: 0,
|
||||||
|
issued: 0,
|
||||||
|
last_source_step: 0,
|
||||||
|
open: None,
|
||||||
|
records: Vec::new(),
|
||||||
|
driver: None,
|
||||||
|
uncaptured: std::collections::BTreeSet::new(),
|
||||||
|
palette_seed: PALETTE_SEED,
|
||||||
|
})),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lock(&self) -> MutexGuard<'_, Inner> {
|
||||||
|
self.inner
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The task face.
|
||||||
|
pub fn task(&self) -> Box<dyn Task> {
|
||||||
|
Box::new(TaskFace(self.clone()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The executor face.
|
||||||
|
pub fn executor(&self) -> Box<dyn ActionExecutor> {
|
||||||
|
Box::new(ExecutorFace(self.clone()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replace every decision the executor is handed by `driver`'s, as a legacy harness does
|
||||||
|
/// through `FrameObserver::readout`. A parity run's tool; the service never sets one.
|
||||||
|
pub fn set_driver(&self, driver: Box<dyn crate::driver::DecisionDriver>) {
|
||||||
|
self.lock().driver = Some(driver);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every address the engine has read that the image does not capture. Empty is the contract
|
||||||
|
/// (`legacy-gameboy-v1` section 8): a register window reads `$FF` in the image.
|
||||||
|
pub fn uncaptured_reads(&self) -> Vec<u16> {
|
||||||
|
self.lock().uncaptured.iter().copied().collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Seeds the next restore's fresh macro layer as the legacy loop does after a restore: with
|
||||||
|
/// the restored brain's RNG state (`rng_state() as u32`).
|
||||||
|
pub fn set_palette_seed(&self, seed: u32) {
|
||||||
|
self.lock().palette_seed = seed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The records since the last call.
|
||||||
|
pub fn take_records(&self) -> Vec<TaskRecord> {
|
||||||
|
std::mem::take(&mut self.lock().records)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ledgers as one canonical string: the adapter's export, the ratchet's state, and the
|
||||||
|
/// executor's observable state (scene, bound channels, running macro, outcome counts).
|
||||||
|
pub fn ledgers(&self) -> String {
|
||||||
|
self.lock().ledgers()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ledger of a task half (STATE-02's `TaskHalf`, FLYSIM01's `reward` and `ratchet`), with
|
||||||
|
/// whether the ratchet holds a snapshot (which the environment's slot `best` now holds).
|
||||||
|
///
|
||||||
|
/// The adapter's lifetime ledger grows with play and is past the 32 KiB `TypedValue` bound on
|
||||||
|
/// the live fly (42-46 KB at rank 12-15), so it is artifact-backed (`workers-v1` section 1):
|
||||||
|
/// the typed value is `{reward: {digest, byteLength}, ratchet, slotFilled}` and the reward's
|
||||||
|
/// JSON travels as the attachment [`REWARD_ATTACHMENT`].
|
||||||
|
pub fn ledger_of(
|
||||||
|
half: &TaskHalf,
|
||||||
|
slot_filled: bool,
|
||||||
|
) -> DomainResult<(TypedValue, BTreeMap<String, Vec<u8>>)> {
|
||||||
|
// The adapter's own JSON, exactly as FLYSIM01's `reward` member holds it.
|
||||||
|
let reward = serde_json::to_vec(&half.reward)
|
||||||
|
.map_err(|e| state_error(format!("the adapter ledger: {e}")))?;
|
||||||
|
let value = json!({
|
||||||
|
"reward": {"digest": digest_of_bytes(&reward), "byteLength": reward.len().to_string()},
|
||||||
|
"ratchet": serde_json::to_value(half.ratchet)
|
||||||
|
.map_err(|e| state_error(format!("the ratchet: {e}")))?,
|
||||||
|
"slotFilled": slot_filled,
|
||||||
|
});
|
||||||
|
let typed = TypedValue::new(ledger_schema(), value).map_err(|e| state_error(e.0))?;
|
||||||
|
Ok((
|
||||||
|
typed,
|
||||||
|
BTreeMap::from([(REWARD_ATTACHMENT.to_owned(), reward)]),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The task's half of a FLYSIM01 export at the committed boundary, and whether the slot is
|
||||||
|
/// filled.
|
||||||
|
pub fn task_half(&self) -> (TaskHalf, bool) {
|
||||||
|
let inner = self.lock();
|
||||||
|
(
|
||||||
|
TaskHalf {
|
||||||
|
reward: inner.adapter.export_state(),
|
||||||
|
ratchet: inner.ratchet.state,
|
||||||
|
},
|
||||||
|
inner.ratchet.snapshot.is_some(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The brain time of the last transition (its Prepare's clock), in ms: `network.ms`.
|
||||||
|
pub fn brain_ms(&self) -> f64 {
|
||||||
|
self.lock().ms
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The adapter's ladder rank now (`Sim::track_rank` reads it after each transition).
|
||||||
|
pub fn rank(&self) -> u32 {
|
||||||
|
self.lock().adapter.progress().rank
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The context a restore of `ledger` onto the boundary `image` shows at brain time `ms`: what
|
||||||
|
/// [`Task::restored`] will compute after the install, computed before it so the agent's
|
||||||
|
/// payload can carry it. Changes nothing.
|
||||||
|
pub fn preview_context(
|
||||||
|
&self,
|
||||||
|
ledger: &TypedValue,
|
||||||
|
attachments: &BTreeMap<String, Vec<u8>>,
|
||||||
|
image: &MemoryImage,
|
||||||
|
ms: f64,
|
||||||
|
) -> Result<TypedValue, String> {
|
||||||
|
let inner = self.lock();
|
||||||
|
let (adapter, _ratchet) =
|
||||||
|
parse_ledger(&inner, ledger, attachments).map_err(|e| e.message)?;
|
||||||
|
let mut layer = fresh_layer(&inner.config, inner.palette_seed);
|
||||||
|
if let Some(layer) = layer.as_mut() {
|
||||||
|
let mut reader = ImageReader::new(image, &inner.cartridge);
|
||||||
|
let _ = layer.observe(&mut reader, &AdapterLedger(&adapter), ms);
|
||||||
|
}
|
||||||
|
Ok(ReadoutContext {
|
||||||
|
boot: adapter.boot(),
|
||||||
|
bound: layer
|
||||||
|
.as_ref()
|
||||||
|
.map(MacroLayer::bound_channels)
|
||||||
|
.unwrap_or_default(),
|
||||||
|
location: adapter
|
||||||
|
.location()
|
||||||
|
.map(|(area, x, y)| Location { area, x, y }),
|
||||||
|
}
|
||||||
|
.to_typed())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The readout context the task would hand the decoder now.
|
||||||
|
pub fn context(&self) -> ReadoutContext {
|
||||||
|
self.lock().context()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Sim::boot`'s layer: the configuration's palette at the macro group's hold.
|
||||||
|
fn fresh_layer(config: &PokeredConfig, seed: u32) -> Option<MacroLayer> {
|
||||||
|
let mut service = Config::default();
|
||||||
|
service.loop_.game = GAME.to_owned();
|
||||||
|
service.macros.mode = config.mode;
|
||||||
|
macro_layer(&service, config.hold_ms, seed)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The image reader the engine is handed: `ImageReader`, plus a record of any address it was asked
|
||||||
|
/// for that the image does not capture (`legacy-gameboy-v1` section 8, MEM-01 amendment). Such a
|
||||||
|
/// read answers `$FF` where the live emulator would answer the register, so the engine and the
|
||||||
|
/// legacy loop could disagree; the record makes that visible rather than silent.
|
||||||
|
struct Watched<'a> {
|
||||||
|
reader: ImageReader<'a>,
|
||||||
|
uncaptured: &'a mut std::collections::BTreeSet<u16>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl flybrain_gb::adapter::MemoryReader for Watched<'_> {
|
||||||
|
fn read8(&mut self, address: u16) -> u8 {
|
||||||
|
if !flybrain_gb::captured(address) {
|
||||||
|
self.uncaptured.insert(address);
|
||||||
|
}
|
||||||
|
self.reader.read8(address)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_rom(&mut self, bank: u8, address: u16) -> Option<u8> {
|
||||||
|
self.reader.read_rom(bank, address)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decision_active(decision: &ChannelsDecision) -> Vec<String> {
|
||||||
|
let mut active: Vec<String> = gameboy::GAMEBOY_BUTTONS
|
||||||
|
.iter()
|
||||||
|
.zip(decision.buttons)
|
||||||
|
.filter(|(_, down)| *down)
|
||||||
|
.map(|(name, _)| (*name).to_owned())
|
||||||
|
.collect();
|
||||||
|
if let Some(channel) = &decision.macro_channel {
|
||||||
|
active.push(channel.clone());
|
||||||
|
}
|
||||||
|
active
|
||||||
|
}
|
||||||
|
|
||||||
|
fn intent_of(mask: u32) -> ControllerIntent {
|
||||||
|
let control = fly_session::legacy_env::control_of("p1", mask as u8);
|
||||||
|
ControllerIntent {
|
||||||
|
buttons: control.buttons,
|
||||||
|
axes: control.axes,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Inner {
|
||||||
|
fn image_of(&self, inspection: &Inspection) -> DomainResult<MemoryImage> {
|
||||||
|
let typed = MemoryInspection::from_typed(&inspection.value)
|
||||||
|
.map_err(|e| DomainError::before(ErrorCode::IdentityMismatch, e.0))?;
|
||||||
|
if typed.rom_digest != self.cartridge.sha256_hex() {
|
||||||
|
return Err(DomainError::before(
|
||||||
|
ErrorCode::IdentityMismatch,
|
||||||
|
"the inspection's romDigest is not the executor's cartridge",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let bytes = inspection
|
||||||
|
.attachments
|
||||||
|
.get(MEMORY_ATTACHMENT)
|
||||||
|
.ok_or_else(|| {
|
||||||
|
DomainError::new(
|
||||||
|
ErrorCode::BufferInvalid,
|
||||||
|
format!(
|
||||||
|
"boundary {} has no {MEMORY_ATTACHMENT}",
|
||||||
|
inspection.boundary
|
||||||
|
),
|
||||||
|
MutationCertainty::Unknown,
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
MemoryImage::from_bytes(bytes).map_err(|e| {
|
||||||
|
DomainError::new(
|
||||||
|
ErrorCode::BufferInvalid,
|
||||||
|
e.to_string(),
|
||||||
|
MutationCertainty::Unknown,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn context(&self) -> ReadoutContext {
|
||||||
|
ReadoutContext {
|
||||||
|
boot: self.adapter.boot(),
|
||||||
|
bound: self
|
||||||
|
.macros
|
||||||
|
.as_ref()
|
||||||
|
.map(MacroLayer::bound_channels)
|
||||||
|
.unwrap_or_default(),
|
||||||
|
location: self
|
||||||
|
.adapter
|
||||||
|
.location()
|
||||||
|
.map(|(area, x, y)| Location { area, x, y }),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn contexts(&self) -> BTreeMap<Id, TypedValue> {
|
||||||
|
BTreeMap::from([(self.config.agent_id.clone(), self.context().to_typed())])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn progress_value(&self) -> TypedValue {
|
||||||
|
let progress = self.adapter.progress();
|
||||||
|
TypedValue::new(
|
||||||
|
progress_schema(),
|
||||||
|
json!({
|
||||||
|
"rank": progress.rank,
|
||||||
|
"uniqueLocations": progress.unique_locations,
|
||||||
|
"rewardTotal": progress.reward_total,
|
||||||
|
"best": self.ratchet.state.best,
|
||||||
|
"recoveries": self.ratchet.state.recoveries,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.expect("progress fits the contract")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ledgers(&self) -> String {
|
||||||
|
ledgers_of(&self.adapter, &self.ratchet, self.macros.as_ref())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn observe(&mut self, image: &MemoryImage, ms: f64) -> Vec<MacroEvent> {
|
||||||
|
let cartridge = self.cartridge.clone();
|
||||||
|
let Inner {
|
||||||
|
macros,
|
||||||
|
adapter,
|
||||||
|
uncaptured,
|
||||||
|
..
|
||||||
|
} = self;
|
||||||
|
let mut reader = Watched {
|
||||||
|
reader: ImageReader::new(image, &cartridge),
|
||||||
|
uncaptured,
|
||||||
|
};
|
||||||
|
match macros.as_mut() {
|
||||||
|
Some(layer) => layer.observe(&mut reader, &AdapterLedger(&*adapter), ms),
|
||||||
|
None => Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn event(
|
||||||
|
&mut self,
|
||||||
|
source_step: u64,
|
||||||
|
rule: &str,
|
||||||
|
ordinal: u32,
|
||||||
|
kind: &str,
|
||||||
|
payload: Value,
|
||||||
|
) -> TaskEvent {
|
||||||
|
self.issued += 1;
|
||||||
|
TaskEvent {
|
||||||
|
id: event_id(&self.epoch, source_step, rule, ordinal),
|
||||||
|
kind_id: id(kind),
|
||||||
|
source_step,
|
||||||
|
agent_id: Some(self.config.agent_id.clone()),
|
||||||
|
payload: TypedValue::new(event_schema(), payload).expect("an event payload fits"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn close(&mut self) {
|
||||||
|
if let Some(mut record) = self.open.take() {
|
||||||
|
record.ledgers = self.ledgers();
|
||||||
|
self.records.push(record);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TaskFace(PokeredTask);
|
||||||
|
struct ExecutorFace(PokeredTask);
|
||||||
|
|
||||||
|
impl Task for TaskFace {
|
||||||
|
fn schema(&self) -> SchemaRef {
|
||||||
|
progress_schema()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn inspection_attachments(&self) -> Vec<String> {
|
||||||
|
vec![MEMORY_ATTACHMENT.to_owned()]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bootstrap(
|
||||||
|
&mut self,
|
||||||
|
initial: &Inspection,
|
||||||
|
bindings: &[PortBinding],
|
||||||
|
) -> DomainResult<Bootstrap> {
|
||||||
|
let mut inner = self.0.lock();
|
||||||
|
if bindings.len() != 1
|
||||||
|
|| bindings[0].agent_id != inner.config.agent_id
|
||||||
|
|| bindings[0].port_id != inner.config.port_id
|
||||||
|
{
|
||||||
|
return Err(DomainError::before(
|
||||||
|
ErrorCode::IdentityMismatch,
|
||||||
|
"pokered-macros-v1 serves exactly one agent on its one port",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let image = inner.image_of(initial)?;
|
||||||
|
// `Sim::boot` on a fresh start: the layer observes O[0] once, at the warm-up's end. The
|
||||||
|
// agent is initialized after this, but its warm-up is the profile's constant, so the
|
||||||
|
// brain time the legacy loop observes at is known: exactly `warmupMs`.
|
||||||
|
let ms = gameboy::WARMUP_MS as f64;
|
||||||
|
inner.ms = ms;
|
||||||
|
inner.observe(&image, ms);
|
||||||
|
inner.current = Some((initial.boundary, image));
|
||||||
|
Ok(Bootstrap {
|
||||||
|
contexts: inner.contexts(),
|
||||||
|
progress: inner.progress_value(),
|
||||||
|
events: Vec::new(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn evaluate_transition(
|
||||||
|
&mut self,
|
||||||
|
scope: &Scope,
|
||||||
|
old: &Inspection,
|
||||||
|
new: &Inspection,
|
||||||
|
_applied_controls: &[PortControl],
|
||||||
|
) -> DomainResult<Evaluation> {
|
||||||
|
let mut inner = self.0.lock();
|
||||||
|
match &inner.current {
|
||||||
|
Some((boundary, _)) if *boundary == old.boundary && old.boundary == scope.step => {}
|
||||||
|
_ => {
|
||||||
|
return Err(DomainError::before(
|
||||||
|
ErrorCode::InvalidPhase,
|
||||||
|
"the task evaluates the transition from the boundary it last observed",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let image = inner.image_of(new)?;
|
||||||
|
let ms = inner.ms;
|
||||||
|
let k1 = scope.step + 1;
|
||||||
|
inner.evaluations += 1;
|
||||||
|
inner.last_source_step = k1;
|
||||||
|
|
||||||
|
// `LegacyFrame::evaluate`: rewards from the frame just produced, then the scene, then the
|
||||||
|
// location (the agent's, from the context), then the rank.
|
||||||
|
let cartridge = inner.cartridge.clone();
|
||||||
|
let rewards = {
|
||||||
|
let Inner {
|
||||||
|
adapter,
|
||||||
|
uncaptured,
|
||||||
|
..
|
||||||
|
} = &mut *inner;
|
||||||
|
let mut reader = Watched {
|
||||||
|
reader: ImageReader::new(&image, &cartridge),
|
||||||
|
uncaptured,
|
||||||
|
};
|
||||||
|
adapter.sample(&mut reader, ms)
|
||||||
|
};
|
||||||
|
let abandoned = inner.observe(&image, ms);
|
||||||
|
let progress = inner.adapter.progress();
|
||||||
|
|
||||||
|
// `LegacyFrame::boundary`, the decision half: the ratchet captures on a safe frame above
|
||||||
|
// its best -- a slot save at `Ready(k+1)` -- and says whether to roll back.
|
||||||
|
let safe = inner.adapter.safe_for_snapshot();
|
||||||
|
let nearer = inner
|
||||||
|
.macros
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(MacroLayer::nearer_the_objective);
|
||||||
|
let game_over = inner.adapter.game_over();
|
||||||
|
let mut saved = false;
|
||||||
|
let recover = inner.ratchet.observe_with_progress(
|
||||||
|
safe,
|
||||||
|
u64::from(progress.rank),
|
||||||
|
progress.unique_locations as u64,
|
||||||
|
ms as u64,
|
||||||
|
game_over,
|
||||||
|
nearer,
|
||||||
|
|| {
|
||||||
|
saved = true;
|
||||||
|
slot_marker()
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut outcome = AgentOutcome::default();
|
||||||
|
let mut events = Vec::new();
|
||||||
|
for (n, event) in rewards.iter().enumerate() {
|
||||||
|
let ordinal = n as u32;
|
||||||
|
let task_event = inner.event(
|
||||||
|
k1,
|
||||||
|
"reward",
|
||||||
|
ordinal,
|
||||||
|
"pokered.reward",
|
||||||
|
json!({"kind": event.kind, "label": event.label, "value": event.value}),
|
||||||
|
);
|
||||||
|
outcome.rewards.push(Reward {
|
||||||
|
event_id: task_event.id.clone(),
|
||||||
|
rule_id: id(event.kind),
|
||||||
|
value: event.value,
|
||||||
|
});
|
||||||
|
// `Stimulus.durationMs` is positive: an event that drives no pulse is a Reward alone,
|
||||||
|
// as the legacy `stimulate(0)` changes nothing.
|
||||||
|
if event.stimulation_ms > 0 {
|
||||||
|
outcome.stimulations.push(Stimulus {
|
||||||
|
id: task_event.id.clone(),
|
||||||
|
kind_id: gameboy::STIMULUS_REWARD_PULSE.to_owned(),
|
||||||
|
duration_ms: f64::from(event.stimulation_ms),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
events.push(task_event);
|
||||||
|
}
|
||||||
|
let episode = recover.then(|| EpisodeRequest {
|
||||||
|
kind: EpisodeRequestKind::Rollback,
|
||||||
|
reason: id(if game_over { "game-over" } else { "stall" }),
|
||||||
|
outcome: RollbackRequest {
|
||||||
|
slot_id: SLOT.to_owned(),
|
||||||
|
trigger: if game_over { "game-over" } else { "stall" }.to_owned(),
|
||||||
|
}
|
||||||
|
.to_typed(),
|
||||||
|
});
|
||||||
|
|
||||||
|
if let Some(record) = inner.open.as_mut() {
|
||||||
|
record
|
||||||
|
.macro_events
|
||||||
|
.extend(abandoned.iter().map(|e| macro_json("evaluate", e)));
|
||||||
|
record.wram_digest = sha256_hex(&image.as_bytes()[0xc000..=0xdfff]);
|
||||||
|
record.rewards = rewards
|
||||||
|
.iter()
|
||||||
|
.map(|e| json!({"kind": e.kind, "value": e.value, "stimulationMs": e.stimulation_ms}))
|
||||||
|
.collect();
|
||||||
|
record.rank = progress.rank;
|
||||||
|
record.saved = saved;
|
||||||
|
}
|
||||||
|
let next_contexts = inner.contexts();
|
||||||
|
let progress_value = inner.progress_value();
|
||||||
|
inner.current = Some((new.boundary, image));
|
||||||
|
if !recover {
|
||||||
|
inner.close();
|
||||||
|
}
|
||||||
|
Ok(Evaluation {
|
||||||
|
outcomes: BTreeMap::from([(inner.config.agent_id.clone(), outcome)]),
|
||||||
|
next_contexts,
|
||||||
|
progress: progress_value,
|
||||||
|
events,
|
||||||
|
episode,
|
||||||
|
slot_saves: if saved { vec![id(SLOT)] } else { Vec::new() },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rollback(
|
||||||
|
&mut self,
|
||||||
|
scope: &Scope,
|
||||||
|
restored: &Inspection,
|
||||||
|
) -> DomainResult<RollbackEvaluation> {
|
||||||
|
let mut inner = self.0.lock();
|
||||||
|
let image = inner.image_of(restored)?;
|
||||||
|
let ms = inner.ms;
|
||||||
|
inner.epoch = scope.epoch.clone();
|
||||||
|
// `recover_game`'s task half: the adapter's transient observations; then the executor
|
||||||
|
// cancels and observes the restored game (`LegacyFrame::rollback`).
|
||||||
|
inner.adapter.clear_transient();
|
||||||
|
let mut events = match inner.macros.as_mut() {
|
||||||
|
Some(layer) => layer.cancel(ms),
|
||||||
|
None => Vec::new(),
|
||||||
|
};
|
||||||
|
events.extend(inner.observe(&image, ms));
|
||||||
|
if let Some(record) = inner.open.as_mut() {
|
||||||
|
record.rolled_back = true;
|
||||||
|
record
|
||||||
|
.macro_events
|
||||||
|
.extend(events.iter().map(|e| macro_json("rollback", e)));
|
||||||
|
}
|
||||||
|
inner.current = Some((restored.boundary, image));
|
||||||
|
inner.close();
|
||||||
|
Ok(RollbackEvaluation {
|
||||||
|
next_contexts: inner.contexts(),
|
||||||
|
events: Vec::new(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn restored(
|
||||||
|
&mut self,
|
||||||
|
scope: &Scope,
|
||||||
|
restored: &Inspection,
|
||||||
|
clock: &RationalNs,
|
||||||
|
) -> DomainResult<Option<BTreeMap<Id, TypedValue>>> {
|
||||||
|
let mut inner = self.0.lock();
|
||||||
|
let image = inner.image_of(restored)?;
|
||||||
|
let ms = clock_ms(clock)?;
|
||||||
|
inner.epoch = scope.epoch.clone();
|
||||||
|
inner.ms = ms;
|
||||||
|
// `Sim::boot` after a restore: a fresh layer (installed by `install_restore`) observes the
|
||||||
|
// restored game once, at the restored brain time, before the first frame decides.
|
||||||
|
inner.observe(&image, ms);
|
||||||
|
inner.current = Some((restored.boundary, image));
|
||||||
|
Ok(Some(inner.contexts()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn progress(&self) -> TypedValue {
|
||||||
|
self.0.lock().progress_value()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn evaluations(&self) -> u64 {
|
||||||
|
self.0.lock().evaluations
|
||||||
|
}
|
||||||
|
|
||||||
|
fn capture(&self) -> DomainResult<TypedValue> {
|
||||||
|
let (half, slot_filled) = self.0.task_half();
|
||||||
|
PokeredTask::ledger_of(&half, slot_filled).map(|(typed, _)| typed)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn capture_attachments(&self) -> DomainResult<BTreeMap<String, Vec<u8>>> {
|
||||||
|
let (half, slot_filled) = self.0.task_half();
|
||||||
|
PokeredTask::ledger_of(&half, slot_filled).map(|(_, attachments)| attachments)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_restore(&self, state: &TypedValue) -> DomainResult<()> {
|
||||||
|
self.validate_restore_with(state, &BTreeMap::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_restore_with(
|
||||||
|
&self,
|
||||||
|
state: &TypedValue,
|
||||||
|
attachments: &BTreeMap<String, Vec<u8>>,
|
||||||
|
) -> DomainResult<()> {
|
||||||
|
let inner = self.0.lock();
|
||||||
|
parse_ledger(&inner, state, attachments).map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn install_restore(&mut self, epoch: &Id, state: &TypedValue) -> DomainResult<()> {
|
||||||
|
self.install_restore_with(epoch, state, &BTreeMap::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn install_restore_with(
|
||||||
|
&mut self,
|
||||||
|
epoch: &Id,
|
||||||
|
state: &TypedValue,
|
||||||
|
attachments: &BTreeMap<String, Vec<u8>>,
|
||||||
|
) -> DomainResult<()> {
|
||||||
|
let mut inner = self.0.lock();
|
||||||
|
let (adapter, ratchet) = parse_ledger(&inner, state, attachments)?;
|
||||||
|
inner.adapter = adapter;
|
||||||
|
inner.ratchet = ratchet;
|
||||||
|
// `legacy-transient-reset`: a fresh executor, nothing running, empty ledgers.
|
||||||
|
inner.macros = fresh_layer(&inner.config, inner.palette_seed);
|
||||||
|
inner.current = None;
|
||||||
|
inner.open = None;
|
||||||
|
inner.epoch = epoch.clone();
|
||||||
|
inner.evaluations = 0;
|
||||||
|
inner.issued = 0;
|
||||||
|
inner.last_source_step = 0;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rebase_ids(&self, _to_epoch: &Id) -> DomainResult<BTreeMap<Id, Id>> {
|
||||||
|
Err(DomainError::before(
|
||||||
|
ErrorCode::Unsupported,
|
||||||
|
"pokered-macros-v1 compares runs by FLY_TRACE, not by rebased event ids",
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn event_watermarks(&self) -> (u64, u64) {
|
||||||
|
let inner = self.0.lock();
|
||||||
|
(inner.last_source_step, inner.issued)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_ledger(
|
||||||
|
inner: &Inner,
|
||||||
|
state: &TypedValue,
|
||||||
|
attachments: &BTreeMap<String, Vec<u8>>,
|
||||||
|
) -> DomainResult<(PokemonRedReward, Ratchet)> {
|
||||||
|
if state.schema != ledger_schema() {
|
||||||
|
return Err(state_error(
|
||||||
|
"the captured ledger is not a pokered-macros-v1 ledger",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let bytes = attachments
|
||||||
|
.get(REWARD_ATTACHMENT)
|
||||||
|
.ok_or_else(|| state_error("the ledger's reward attachment is missing"))?;
|
||||||
|
let declared = &state.value["reward"];
|
||||||
|
if declared["digest"].as_str() != Some(digest_of_bytes(bytes).as_str())
|
||||||
|
|| declared["byteLength"].as_str() != Some(bytes.len().to_string().as_str())
|
||||||
|
{
|
||||||
|
return Err(state_error(
|
||||||
|
"the reward attachment is not the one the ledger names",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let reward: Value = serde_json::from_slice(bytes)
|
||||||
|
.map_err(|e| state_error(format!("the reward attachment is not JSON: {e}")))?;
|
||||||
|
let mut value = state.value.clone();
|
||||||
|
value["reward"] = reward;
|
||||||
|
let half = TaskHalf::from_ledger(&value).map_err(state_error)?;
|
||||||
|
let slot_filled = state
|
||||||
|
.value
|
||||||
|
.get("slotFilled")
|
||||||
|
.and_then(Value::as_bool)
|
||||||
|
.ok_or_else(|| state_error("the ledger has no slotFilled"))?;
|
||||||
|
// `LegacyFrame::restore`'s order: the adapter (unless the file has none), then the ratchet
|
||||||
|
// bounded by the adapter's ladder.
|
||||||
|
let mut adapter = PokemonRedReward::new();
|
||||||
|
if !half.reward.is_null() {
|
||||||
|
adapter
|
||||||
|
.import_state(&half.reward)
|
||||||
|
.map_err(|e| state_error(format!("adapter: {e}")))?;
|
||||||
|
}
|
||||||
|
let mut ratchet = Ratchet::with_policy(adapter.recovery_policy());
|
||||||
|
ratchet
|
||||||
|
.import(
|
||||||
|
Some(half.ratchet),
|
||||||
|
slot_filled.then(slot_marker),
|
||||||
|
adapter.rank_ladder().len(),
|
||||||
|
)
|
||||||
|
.map_err(|e| state_error(format!("ratchet: {e}")))?;
|
||||||
|
let _ = inner;
|
||||||
|
Ok((adapter, ratchet))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActionExecutor for ExecutorFace {
|
||||||
|
fn apply(
|
||||||
|
&mut self,
|
||||||
|
scope: &Scope,
|
||||||
|
decision: &TypedValue,
|
||||||
|
current: &Inspection,
|
||||||
|
_progress: &TypedValue,
|
||||||
|
clock: &RationalNs,
|
||||||
|
) -> DomainResult<(ControllerIntent, Vec<TaskEvent>)> {
|
||||||
|
let mut inner = self.0.lock();
|
||||||
|
let decision = ChannelsDecision::from_typed(decision)
|
||||||
|
.map_err(|e| DomainError::before(ErrorCode::IdentityMismatch, e.0))?;
|
||||||
|
let image = match &inner.current {
|
||||||
|
Some((boundary, image)) if *boundary == current.boundary && *boundary == scope.step => {
|
||||||
|
image.clone()
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
return Err(DomainError::before(
|
||||||
|
ErrorCode::InvalidPhase,
|
||||||
|
"the executor reads the boundary the task last observed",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// The clock is the brain time after Prepare, whole milliseconds (the legacy
|
||||||
|
// `network.ms`), which is what the macro layer's windows read.
|
||||||
|
let ms = clock_ms(clock)?;
|
||||||
|
inner.ms = ms;
|
||||||
|
let mut active = decision_active(&decision);
|
||||||
|
let bound = inner
|
||||||
|
.macros
|
||||||
|
.as_ref()
|
||||||
|
.map(MacroLayer::bound_channels)
|
||||||
|
.unwrap_or_default();
|
||||||
|
if let Some(driver) = inner.driver.as_mut() {
|
||||||
|
driver.readout(ms, &bound, &mut active);
|
||||||
|
}
|
||||||
|
let raw = to_button_mask(&active);
|
||||||
|
let cartridge = inner.cartridge.clone();
|
||||||
|
let (mask, events) = {
|
||||||
|
let Inner {
|
||||||
|
macros,
|
||||||
|
adapter,
|
||||||
|
uncaptured,
|
||||||
|
..
|
||||||
|
} = &mut *inner;
|
||||||
|
match macros.as_mut() {
|
||||||
|
Some(layer) => {
|
||||||
|
let mut reader = Watched {
|
||||||
|
reader: ImageReader::new(&image, &cartridge),
|
||||||
|
uncaptured,
|
||||||
|
};
|
||||||
|
let decided =
|
||||||
|
layer.decide(&active, raw, ms, &mut reader, &AdapterLedger(&*adapter));
|
||||||
|
(decided.mask, decided.events)
|
||||||
|
}
|
||||||
|
None => (raw, Vec::new()),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if inner.config.record {
|
||||||
|
inner.open = Some(TaskRecord {
|
||||||
|
boundary: scope.step,
|
||||||
|
decision: active,
|
||||||
|
bound,
|
||||||
|
mask,
|
||||||
|
macro_events: events.iter().map(|e| macro_json("execute", e)).collect(),
|
||||||
|
..TaskRecord::default()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok((intent_of(mask), Vec::new()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn capture(&self) -> DomainResult<TypedValue> {
|
||||||
|
TypedValue::new(executor_schema(), json!({"executor": gameboy::EXECUTOR_ID}))
|
||||||
|
.map_err(|e| DomainError::invalid(e.0))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_restore(&self, state: &TypedValue) -> DomainResult<()> {
|
||||||
|
if state.schema != executor_schema()
|
||||||
|
|| state.value.get("executor").and_then(Value::as_str) != Some(gameboy::EXECUTOR_ID)
|
||||||
|
{
|
||||||
|
return Err(state_error(
|
||||||
|
"the captured executor is not pokered-macros-v1",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Nothing to install: the executor's state is transient (`legacy-transient-reset`), and
|
||||||
|
/// the task's install already gave it a fresh layer.
|
||||||
|
fn install_restore(&mut self, state: &TypedValue) -> DomainResult<()> {
|
||||||
|
self.validate_restore(state)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Brain time in ms from the executor's clock: exact whole nanoseconds of whole milliseconds.
|
||||||
|
pub fn clock_ms(clock: &RationalNs) -> DomainResult<f64> {
|
||||||
|
if clock.denominator != 1 || !clock.numerator.is_multiple_of(1_000_000) {
|
||||||
|
return Err(DomainError::invalid(
|
||||||
|
"the executor clock is not a whole number of milliseconds",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok((clock.numerator / 1_000_000) as f64)
|
||||||
|
}
|
||||||
238
services/flysim/crates/fly-legacy-session/src/trace.rs
Normal file
238
services/flysim/crates/fly-legacy-session/src/trace.rs
Normal file
|
|
@ -0,0 +1,238 @@
|
||||||
|
//! The session's own `FLY_TRACE`: the legacy loop's trace format (`flysim-legacy-frame-trace-v1`,
|
||||||
|
//! FND-01) written from a session-framework run, and the comparison of two of them.
|
||||||
|
//!
|
||||||
|
//! FND-01's trace is what the running service does, frame by frame, as digests. A new-runtime
|
||||||
|
//! session driven from the same checkpoint with the same admissions must write the same lines. So
|
||||||
|
//! the session trace is assembled from exactly what crosses the session's boundaries --
|
||||||
|
//! `Agent.Prepare` (ticks, clock, remainder, decision), `Agent.Commit` (rates, spike bitset), the
|
||||||
|
//! executor's joypad batch, `Environment.Advance`'s view, the task's image-derived fields, and the
|
||||||
|
//! boundary actions -- and compared as JSON, with one declared exclusion: the decision is compared
|
||||||
|
//! as `gameboy-channels-v1` sees it ([`channels`]): the buttons down, and the first channel of the
|
||||||
|
//! context's bound set the decode holds. The decoder's list order is not in the decision schema,
|
||||||
|
//! and a macro channel the macro group still holds after its scene unbound it (the legacy `active`
|
||||||
|
//! can carry one) reaches nothing: the macro layer starts only a bound channel, and the joypad mask
|
||||||
|
//! is the buttons'. The mask, the macro events and every other field are compared as they are.
|
||||||
|
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
use fly_session::coordinator::StepDetails;
|
||||||
|
use fly_session::fly_session_types::gameboy::GAMEBOY_BUTTONS;
|
||||||
|
use fly_session::legacy_parity::trace_rates_digest;
|
||||||
|
use fly_session::types::*;
|
||||||
|
|
||||||
|
use crate::task::TaskRecord;
|
||||||
|
|
||||||
|
pub const FORMAT: &str = "flysim-legacy-frame-trace-v1";
|
||||||
|
|
||||||
|
/// flysim's `remainder_ns`: the exact rational nanoseconds of the frame remainder.
|
||||||
|
fn remainder_json(remainder: &RationalNs) -> Value {
|
||||||
|
json!({"numerator": remainder.numerator.to_string(), "denominator": remainder.denominator.to_string()})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn popcount(bytes: &[u8]) -> u64 {
|
||||||
|
bytes.iter().map(|b| u64::from(b.count_ones())).sum()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One transition line of the session's trace, built from the coordinator's details of the
|
||||||
|
/// transition and the task's record of it.
|
||||||
|
pub fn line(details: &StepDetails, record: &TaskRecord) -> Result<Value, String> {
|
||||||
|
let [(agent_id, prepared)] = details.prepared.as_slice() else {
|
||||||
|
return Err("the legacy composition has exactly one agent".to_owned());
|
||||||
|
};
|
||||||
|
let commit = details
|
||||||
|
.commits
|
||||||
|
.iter()
|
||||||
|
.find(|(id, _)| id == agent_id)
|
||||||
|
.map(|(_, result)| result)
|
||||||
|
.ok_or("no commit for the agent")?;
|
||||||
|
let spikes = details
|
||||||
|
.commit_attachments
|
||||||
|
.iter()
|
||||||
|
.find(|(id, name, _)| {
|
||||||
|
id == agent_id && name == fly_session::legacy_agent::SPIKES_ATTACHMENT
|
||||||
|
})
|
||||||
|
.map(|(_, _, bytes)| bytes)
|
||||||
|
.ok_or("the commit carried no spike bitset")?;
|
||||||
|
let step: u64 = details
|
||||||
|
.engine_frame
|
||||||
|
.as_deref()
|
||||||
|
.ok_or("O[k] has no engineFrame")?
|
||||||
|
.parse()
|
||||||
|
.map_err(|_| "engineFrame is not a U64")?;
|
||||||
|
let admissions: Vec<Value> = details
|
||||||
|
.admissions
|
||||||
|
.iter()
|
||||||
|
.map(|admission| match admission {
|
||||||
|
fly_session::coordinator::Admission::Stimulus { duration_ms, .. } => {
|
||||||
|
json!({"kind": "sugar", "durationMs": duration_ms})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let framebuffer = details
|
||||||
|
.view_digests
|
||||||
|
.iter()
|
||||||
|
.find(|(view, _)| view == "lcd")
|
||||||
|
.map(|(_, digest)| digest.clone())
|
||||||
|
.ok_or("O[k+1] has no lcd view")?;
|
||||||
|
let boundary_actions: Vec<Value> = details
|
||||||
|
.boundary_actions
|
||||||
|
.iter()
|
||||||
|
.map(|action| {
|
||||||
|
json!({
|
||||||
|
"kind": action.kind.as_str(),
|
||||||
|
"slotId": action.slot_id,
|
||||||
|
"stateDigest": action.state_digest,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
Ok(json!({
|
||||||
|
"behaviour": {
|
||||||
|
"step": step.to_string(),
|
||||||
|
"admissions": admissions,
|
||||||
|
"ticksAdvanced": prepared.ticks_advanced.to_string(),
|
||||||
|
"brainTicks": prepared.brain_ticks.to_string(),
|
||||||
|
"remainder": remainder_json(&prepared.remainder),
|
||||||
|
"ratesDigest": trace_rates_digest(&commit.telemetry)?,
|
||||||
|
"spikesDigest": sha256_hex(spikes),
|
||||||
|
"spikeCount": popcount(spikes),
|
||||||
|
"decision": record.decision,
|
||||||
|
"mask": record.mask,
|
||||||
|
"macroEvents": record.macro_events,
|
||||||
|
"framebufferDigest": framebuffer,
|
||||||
|
"wramDigest": record.wram_digest,
|
||||||
|
"rewards": record.rewards,
|
||||||
|
"rank": record.rank,
|
||||||
|
"acknowledgedBoundary": (step + 1).to_string(),
|
||||||
|
"boundaryActions": boundary_actions,
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The decision as `gameboy-channels-v1` sees it, given the bound channels it was masked to: the
|
||||||
|
/// buttons down, and the first bound channel the active set holds (AGENT-01's rule).
|
||||||
|
pub fn channels(decision: &Value, bound: &[String]) -> (BTreeSet<String>, Option<String>) {
|
||||||
|
let active: Vec<&str> = decision
|
||||||
|
.as_array()
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.filter_map(Value::as_str)
|
||||||
|
.collect();
|
||||||
|
let buttons = active
|
||||||
|
.iter()
|
||||||
|
.filter(|name| GAMEBOY_BUTTONS.contains(name))
|
||||||
|
.map(|name| (*name).to_owned())
|
||||||
|
.collect();
|
||||||
|
let macro_channel = bound
|
||||||
|
.iter()
|
||||||
|
.find(|channel| active.contains(&channel.as_str()))
|
||||||
|
.cloned();
|
||||||
|
(buttons, macro_channel)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads a trace file's transition lines (`behaviour` only), skipping the header and the start
|
||||||
|
/// boundary line.
|
||||||
|
pub fn behaviours(text: &str) -> Result<Vec<Value>, String> {
|
||||||
|
let mut lines = text.lines().filter(|l| !l.trim().is_empty());
|
||||||
|
let header: Value = serde_json::from_str(lines.next().ok_or("an empty trace")?)
|
||||||
|
.map_err(|e| format!("header: {e}"))?;
|
||||||
|
if header["format"] != FORMAT {
|
||||||
|
return Err(format!("not {FORMAT}: {}", header["format"]));
|
||||||
|
}
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for line in lines {
|
||||||
|
let value: Value = serde_json::from_str(line).map_err(|e| format!("line: {e}"))?;
|
||||||
|
if let Some(behaviour) = value.get("behaviour") {
|
||||||
|
out.push(behaviour.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a comparison found, for the report.
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||||
|
pub struct Agreement {
|
||||||
|
pub transitions: u64,
|
||||||
|
pub sugar: u64,
|
||||||
|
pub reward_pulses: u64,
|
||||||
|
pub rewards: u64,
|
||||||
|
pub reward_kinds: Vec<String>,
|
||||||
|
pub macro_events: u64,
|
||||||
|
pub pressed: u64,
|
||||||
|
pub saves: u64,
|
||||||
|
pub rollbacks: u64,
|
||||||
|
pub spikes: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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.
|
||||||
|
pub fn compare(
|
||||||
|
legacy: &[Value],
|
||||||
|
session: &[Value],
|
||||||
|
bounds: &[Vec<String>],
|
||||||
|
) -> Result<Agreement, String> {
|
||||||
|
if bounds.len() != session.len() {
|
||||||
|
return Err("one bound set per session transition".to_owned());
|
||||||
|
}
|
||||||
|
if legacy.len() != session.len() {
|
||||||
|
return Err(format!(
|
||||||
|
"the legacy trace has {} transitions, the session's {}",
|
||||||
|
legacy.len(),
|
||||||
|
session.len()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let mut agreement = Agreement::default();
|
||||||
|
for (n, (a, b)) in legacy.iter().zip(session).enumerate() {
|
||||||
|
let (Some(a_map), Some(b_map)) = (a.as_object(), b.as_object()) else {
|
||||||
|
return Err(format!("transition {n}: not an object"));
|
||||||
|
};
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `GAMEBOY_BUTTONS`, re-exported for the decision reconstruction's tests.
|
||||||
|
pub const BUTTONS: [&str; 8] = GAMEBOY_BUTTONS;
|
||||||
130
services/flysim/crates/fly-legacy-session/tests/ledger_size.rs
Normal file
130
services/flysim/crates/fly-legacy-session/tests/ledger_size.rs
Normal file
|
|
@ -0,0 +1,130 @@
|
||||||
|
//! The task ledger is not bounded by the 32 KiB `TypedValue` limit (TASK-01 review B1).
|
||||||
|
//!
|
||||||
|
//! The adapter's lifetime ledger grows with play (42-46 KB on the live fly at rank 12-15). The
|
||||||
|
//! pokered-macros-v1 ledger keeps it as an attachment beside a small typed value, so a ledger of
|
||||||
|
//! any size captures, validates and installs, and a malformed one is an error, never a panic.
|
||||||
|
//! ROM-free: the cartridge is ENV-01's toy one, which the task never reads here.
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
use fly_legacy_session::task::{PokeredConfig, PokeredTask, REWARD_ATTACHMENT};
|
||||||
|
use fly_session::fly_session_types::gameboy::ReadoutContext;
|
||||||
|
use fly_session::legacy_checkpoint::TaskHalf;
|
||||||
|
use fly_session::legacy_env_parity::toy_cart;
|
||||||
|
use fly_session::types::*;
|
||||||
|
use flybrain_gb::pokemon_red::PokemonRedReward;
|
||||||
|
use flysim::snapshot::MacroMode;
|
||||||
|
|
||||||
|
fn task() -> PokeredTask {
|
||||||
|
let rom = toy_cart::rom(0);
|
||||||
|
PokeredTask::new(
|
||||||
|
PokeredConfig {
|
||||||
|
agent_id: id("fly"),
|
||||||
|
port_id: id("p1"),
|
||||||
|
mode: MacroMode::Raw,
|
||||||
|
macro_channels: Vec::new(),
|
||||||
|
hold_ms: 0.0,
|
||||||
|
record: false,
|
||||||
|
},
|
||||||
|
&rom,
|
||||||
|
&digest_of_bytes(&rom),
|
||||||
|
&id("e1"),
|
||||||
|
)
|
||||||
|
.expect("the object")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A real adapter state grown past 64 KB: thousands of walked tiles, as a long life has.
|
||||||
|
fn big_reward() -> Value {
|
||||||
|
let mut reward = PokemonRedReward::new().export_state();
|
||||||
|
let tiles: Vec<Value> = (0..12_000)
|
||||||
|
.map(|n| json!(format!("{}:{}:{}", n % 200, n / 200 % 64, n / 12_800)))
|
||||||
|
.collect();
|
||||||
|
reward["tiles"] = Value::Array(tiles);
|
||||||
|
reward
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_ledger_past_32_kib_captures_validates_and_installs() {
|
||||||
|
let reward = big_reward();
|
||||||
|
let bytes = serde_json::to_vec(&reward).unwrap();
|
||||||
|
assert!(bytes.len() > 64 * 1024, "{} bytes", bytes.len());
|
||||||
|
// The adapter itself takes it, so it is a real ledger and not just a large JSON value.
|
||||||
|
PokemonRedReward::new()
|
||||||
|
.import_state(&reward)
|
||||||
|
.expect("an adapter state");
|
||||||
|
|
||||||
|
let half = TaskHalf {
|
||||||
|
reward,
|
||||||
|
ratchet: Default::default(),
|
||||||
|
};
|
||||||
|
let (typed, attachments) = PokeredTask::ledger_of(&half, false).expect("any size");
|
||||||
|
assert!(
|
||||||
|
typed.to_json().to_string().len() < 1024,
|
||||||
|
"the typed value stays small"
|
||||||
|
);
|
||||||
|
assert_eq!(attachments[REWARD_ATTACHMENT], bytes);
|
||||||
|
|
||||||
|
let object = task();
|
||||||
|
let mut face = object.task();
|
||||||
|
face.validate_restore_with(&typed, &attachments)
|
||||||
|
.expect("validates");
|
||||||
|
face.install_restore_with(&id("e2"), &typed, &attachments)
|
||||||
|
.expect("installs");
|
||||||
|
let (restored, slot) = object.task_half();
|
||||||
|
assert!(!slot);
|
||||||
|
let mut direct = PokemonRedReward::new();
|
||||||
|
direct.import_state(&half.reward).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
restored.reward,
|
||||||
|
direct.export_state(),
|
||||||
|
"the installed adapter is the imported one"
|
||||||
|
);
|
||||||
|
// And what it captures back is a ledger of the same kind, which installs again.
|
||||||
|
let (again, again_attachments) = (face.capture().unwrap(), face.capture_attachments().unwrap());
|
||||||
|
assert!(again_attachments[REWARD_ATTACHMENT].len() > 32 * 1024);
|
||||||
|
face.validate_restore_with(&again, &again_attachments)
|
||||||
|
.expect("re-validates");
|
||||||
|
|
||||||
|
// The context preview reads it too.
|
||||||
|
let image = flybrain_gb::MemoryImage::zeroed();
|
||||||
|
let context = object
|
||||||
|
.preview_context(&typed, &attachments, &image, 1_000.0)
|
||||||
|
.expect("previews");
|
||||||
|
assert!(ReadoutContext::from_typed(&context).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_bad_ledger_is_an_error_not_a_panic() {
|
||||||
|
let half = TaskHalf {
|
||||||
|
reward: big_reward(),
|
||||||
|
ratchet: Default::default(),
|
||||||
|
};
|
||||||
|
let (typed, attachments) = PokeredTask::ledger_of(&half, false).unwrap();
|
||||||
|
let face = task().task();
|
||||||
|
for (what, attachments) in [
|
||||||
|
("missing", BTreeMap::new()),
|
||||||
|
(
|
||||||
|
"another",
|
||||||
|
BTreeMap::from([(REWARD_ATTACHMENT.to_owned(), b"{}".to_vec())]),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"truncated",
|
||||||
|
BTreeMap::from([(
|
||||||
|
REWARD_ATTACHMENT.to_owned(),
|
||||||
|
attachments[REWARD_ATTACHMENT][..100].to_vec(),
|
||||||
|
)]),
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
let err = face
|
||||||
|
.validate_restore_with(&typed, &attachments)
|
||||||
|
.unwrap_err();
|
||||||
|
assert_eq!(
|
||||||
|
err.code,
|
||||||
|
ErrorCode::IncompatibleState,
|
||||||
|
"{what}: {}",
|
||||||
|
err.message
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,79 @@
|
||||||
|
//! The palette seed is never read (TASK-01 review N3).
|
||||||
|
//!
|
||||||
|
//! The legacy loop seeds the macro palette with the brain's RNG state after boot; a fresh session
|
||||||
|
//! start cannot see it and uses `PALETTE_SEED`. That is equivalent only while no macro reads its
|
||||||
|
//! generator. This holds it on the cartridge: two macro layers seeded differently, handed the same
|
||||||
|
//! decisions (the ROM tests' rotation driver) over the same frames, press the same buttons and
|
||||||
|
//! report the same events, frame by frame. A macro that ever draws from its generator breaks it
|
||||||
|
//! here rather than in a shadow run.
|
||||||
|
//!
|
||||||
|
//! ROM job: `FLY_ROM` and `FLY_DOOR_CHECKPOINT` (the operator's rom env script).
|
||||||
|
|
||||||
|
use fly_legacy_session::composition::channels_and_hold;
|
||||||
|
use fly_legacy_session::driver::{DecisionDriver, RotationDriver};
|
||||||
|
use flybrain_core::decoder::gameboy::to_button_mask;
|
||||||
|
use flybrain_gb::pokemon_red::PokemonRedReward;
|
||||||
|
use flybrain_gb::{AdapterLedger, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator};
|
||||||
|
use flysim::config::Config;
|
||||||
|
use flysim::macros::macro_layer;
|
||||||
|
use flysim::snapshot::MacroMode;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn two_palette_seeds_press_the_same_buttons() {
|
||||||
|
let (Some(rom), Some(path)) = (
|
||||||
|
std::env::var_os("FLY_ROM"),
|
||||||
|
std::env::var_os("FLY_DOOR_CHECKPOINT"),
|
||||||
|
) else {
|
||||||
|
eprintln!("skipping: FLY_ROM or FLY_DOOR_CHECKPOINT is not set");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let rom = std::fs::read(rom).expect("the cartridge");
|
||||||
|
let checkpoint = flysim::store::load(std::path::Path::new(&path)).expect("FLYSIM01");
|
||||||
|
let mut emulator =
|
||||||
|
Emulator::new(&rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES).expect("binjgb");
|
||||||
|
emulator
|
||||||
|
.import_state(&checkpoint.runtime.emulator)
|
||||||
|
.expect("the emulator state");
|
||||||
|
let mut adapter = PokemonRedReward::new();
|
||||||
|
adapter
|
||||||
|
.import_state(&checkpoint.runtime.reward)
|
||||||
|
.expect("the adapter state");
|
||||||
|
let mut config = Config::default();
|
||||||
|
config.loop_.game = "pokemon-red".to_owned();
|
||||||
|
config.macros.mode = MacroMode::Macros;
|
||||||
|
let (_, hold_ms) = channels_and_hold(MacroMode::Macros);
|
||||||
|
let mut a = macro_layer(&config, hold_ms, 0).expect("a layer");
|
||||||
|
let mut b = macro_layer(&config, hold_ms, 0xdead_beef).expect("a layer");
|
||||||
|
let mut driver = RotationDriver::new();
|
||||||
|
let mut ms = checkpoint.agent.network.ms;
|
||||||
|
let frames = std::env::var("FLY_TASK01_SEED_FRAMES")
|
||||||
|
.ok()
|
||||||
|
.and_then(|v| v.parse().ok())
|
||||||
|
.unwrap_or(3000);
|
||||||
|
let mut macros = 0;
|
||||||
|
for frame in 0..frames {
|
||||||
|
assert_eq!(
|
||||||
|
a.bound_channels(),
|
||||||
|
b.bound_channels(),
|
||||||
|
"frame {frame}: bound"
|
||||||
|
);
|
||||||
|
let mut active = Vec::new();
|
||||||
|
driver.readout(ms, &a.bound_channels(), &mut active);
|
||||||
|
let raw = to_button_mask(&active);
|
||||||
|
let da = a.decide(&active, raw, ms, &mut emulator, &AdapterLedger(&adapter));
|
||||||
|
let db = b.decide(&active, raw, ms, &mut emulator, &AdapterLedger(&adapter));
|
||||||
|
assert_eq!(da.mask, db.mask, "frame {frame}: mask");
|
||||||
|
assert_eq!(da.events, db.events, "frame {frame}: events");
|
||||||
|
macros += da.events.iter().filter(|e| e.outcome.is_none()).count();
|
||||||
|
emulator.set_buttons(da.mask as u8);
|
||||||
|
emulator.run_frame().expect("a frame");
|
||||||
|
let _ = emulator.take_audio_u8();
|
||||||
|
ms += 17.0;
|
||||||
|
let _ = adapter.sample(&mut emulator, ms);
|
||||||
|
let ea = a.observe(&mut emulator, &AdapterLedger(&adapter), ms);
|
||||||
|
let eb = b.observe(&mut emulator, &AdapterLedger(&adapter), ms);
|
||||||
|
assert_eq!(ea, eb, "frame {frame}: observe");
|
||||||
|
}
|
||||||
|
assert!(macros > 10, "the driver started macros ({macros})");
|
||||||
|
eprintln!("{frames} frames, {macros} macros started: two seeds, the same presses");
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,537 @@
|
||||||
|
//! The coordinator's boundary actions on the legacy workers, without a ROM: ENV-01's toy
|
||||||
|
//! cartridge, AGENT-01's toy connectome, and a scripted task that asks for a slot save at
|
||||||
|
//! boundary 3, a reward at 4 and a rollback onto the slot at 6.
|
||||||
|
//!
|
||||||
|
//! What it holds, in-process and as processes:
|
||||||
|
//!
|
||||||
|
//! - the rollback runs `Ready(e, 6) -> RollingBack(6) -> Ready(e', 6)`, in the policy's order
|
||||||
|
//! (`RestoreSlot`, the task's part, `Agent.Rollback`), and the session steps on in `e'`;
|
||||||
|
//! - the restored boundary is the saved one: the task reads O'[6]'s memory image and it is O[3]'s;
|
||||||
|
//! - the step details record the save's state digest and the rollback, and the trace carries them
|
||||||
|
//! as boundary actions, saves first;
|
||||||
|
//! - admitted sugar is cut into the next Prepare and reported applied at the boundary it committed.
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
use flybus::{Grants, Pattern, Policy, RouterConfig};
|
||||||
|
|
||||||
|
use fly_session::coordinator::{AdmissionEnd, AgentSlot, Coordinator};
|
||||||
|
use fly_session::fly_session_types::extensions::ROLLBACK_POLICY;
|
||||||
|
use fly_session::fly_session_types::gameboy::{
|
||||||
|
self, ChannelsDecision, ReadoutContext, RollbackRequest,
|
||||||
|
};
|
||||||
|
use fly_session::fly_session_types::trace::BoundaryActionKind;
|
||||||
|
use fly_session::launcher::{
|
||||||
|
ExecutionMode, Launcher, LegacyAgentLaunch, LegacyEnvironmentLaunch, SUPERVISOR_CLIENT,
|
||||||
|
ThreadBudget, Via,
|
||||||
|
};
|
||||||
|
use fly_session::legacy_agent::LegacyProfileKind;
|
||||||
|
use fly_session::legacy_env::{BackendConfig, MEMORY_ATTACHMENT, STATE_FORMAT_ID};
|
||||||
|
use fly_session::legacy_env_parity::toy_cart;
|
||||||
|
use fly_session::task::{
|
||||||
|
ActionExecutor, Bootstrap, Evaluation, Inspection, RollbackEvaluation, Task,
|
||||||
|
};
|
||||||
|
use fly_session::types::*;
|
||||||
|
|
||||||
|
fn grants(f: impl FnOnce(&mut Grants)) -> Grants {
|
||||||
|
let mut g = Grants::default();
|
||||||
|
f(&mut g);
|
||||||
|
g
|
||||||
|
}
|
||||||
|
|
||||||
|
fn schema(name: &str) -> SchemaRef {
|
||||||
|
SchemaRef::new(name, 1, &digest_of_bytes(name.as_bytes())).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the scripted task saw.
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Seen {
|
||||||
|
/// Boundary -> the image digest the task read for it (the last reading wins).
|
||||||
|
images: BTreeMap<u64, String>,
|
||||||
|
restored: Option<(u64, String)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Scripted {
|
||||||
|
agent: Id,
|
||||||
|
seen: Arc<Mutex<Seen>>,
|
||||||
|
evaluations: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn context() -> TypedValue {
|
||||||
|
ReadoutContext {
|
||||||
|
boot: false,
|
||||||
|
bound: Vec::new(),
|
||||||
|
location: None,
|
||||||
|
}
|
||||||
|
.to_typed()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn image_digest(inspection: &Inspection) -> DomainResult<String> {
|
||||||
|
let bytes = inspection
|
||||||
|
.attachments
|
||||||
|
.get(MEMORY_ATTACHMENT)
|
||||||
|
.ok_or_else(|| DomainError::invalid("no image"))?;
|
||||||
|
assert_eq!(bytes.len(), 65_536);
|
||||||
|
Ok(digest_of_bytes(bytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Task for Scripted {
|
||||||
|
fn schema(&self) -> SchemaRef {
|
||||||
|
schema("scripted.progress")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn inspection_attachments(&self) -> Vec<String> {
|
||||||
|
vec![MEMORY_ATTACHMENT.to_owned()]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bootstrap(
|
||||||
|
&mut self,
|
||||||
|
initial: &Inspection,
|
||||||
|
_bindings: &[PortBinding],
|
||||||
|
) -> DomainResult<Bootstrap> {
|
||||||
|
let digest = image_digest(initial)?;
|
||||||
|
self.seen
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.images
|
||||||
|
.insert(initial.boundary, digest);
|
||||||
|
Ok(Bootstrap {
|
||||||
|
contexts: BTreeMap::from([(self.agent.clone(), context())]),
|
||||||
|
progress: self.progress(),
|
||||||
|
events: Vec::new(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn evaluate_transition(
|
||||||
|
&mut self,
|
||||||
|
scope: &Scope,
|
||||||
|
old: &Inspection,
|
||||||
|
new: &Inspection,
|
||||||
|
_controls: &[PortControl],
|
||||||
|
) -> DomainResult<Evaluation> {
|
||||||
|
assert_eq!(old.boundary, scope.step, "O[k] is the old inspection");
|
||||||
|
assert_eq!(new.boundary, scope.step + 1, "O[k+1] is the new one");
|
||||||
|
self.evaluations += 1;
|
||||||
|
let k1 = scope.step + 1;
|
||||||
|
self.seen
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.images
|
||||||
|
.insert(k1, image_digest(new)?);
|
||||||
|
let mut outcome = AgentOutcome::default();
|
||||||
|
let mut events = Vec::new();
|
||||||
|
if k1 == 4 {
|
||||||
|
let event = TaskEvent {
|
||||||
|
id: event_id(&scope.epoch, k1, "scripted", 0),
|
||||||
|
kind_id: id("scripted.reward"),
|
||||||
|
source_step: k1,
|
||||||
|
agent_id: Some(self.agent.clone()),
|
||||||
|
payload: TypedValue::new(schema("scripted.event"), json!({})).unwrap(),
|
||||||
|
};
|
||||||
|
outcome.rewards.push(Reward {
|
||||||
|
event_id: event.id.clone(),
|
||||||
|
rule_id: id("scripted"),
|
||||||
|
value: 0.5,
|
||||||
|
});
|
||||||
|
outcome.stimulations.push(Stimulus {
|
||||||
|
id: event.id.clone(),
|
||||||
|
kind_id: gameboy::STIMULUS_REWARD_PULSE.to_owned(),
|
||||||
|
duration_ms: 100.0,
|
||||||
|
});
|
||||||
|
events.push(event);
|
||||||
|
}
|
||||||
|
Ok(Evaluation {
|
||||||
|
outcomes: BTreeMap::from([(self.agent.clone(), outcome)]),
|
||||||
|
next_contexts: BTreeMap::from([(self.agent.clone(), context())]),
|
||||||
|
progress: self.progress(),
|
||||||
|
events,
|
||||||
|
episode: (k1 == 6).then(|| EpisodeRequest {
|
||||||
|
kind: EpisodeRequestKind::Rollback,
|
||||||
|
reason: id("stall"),
|
||||||
|
outcome: RollbackRequest {
|
||||||
|
slot_id: "best".into(),
|
||||||
|
trigger: "stall".into(),
|
||||||
|
}
|
||||||
|
.to_typed(),
|
||||||
|
}),
|
||||||
|
slot_saves: if k1 == 3 {
|
||||||
|
vec![id("best")]
|
||||||
|
} else {
|
||||||
|
Vec::new()
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rollback(
|
||||||
|
&mut self,
|
||||||
|
scope: &Scope,
|
||||||
|
restored: &Inspection,
|
||||||
|
) -> DomainResult<RollbackEvaluation> {
|
||||||
|
assert_eq!(restored.boundary, scope.step);
|
||||||
|
self.seen.lock().unwrap().restored = Some((restored.boundary, image_digest(restored)?));
|
||||||
|
Ok(RollbackEvaluation {
|
||||||
|
next_contexts: BTreeMap::from([(self.agent.clone(), context())]),
|
||||||
|
events: Vec::new(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn progress(&self) -> TypedValue {
|
||||||
|
TypedValue::new(
|
||||||
|
schema("scripted.progress"),
|
||||||
|
json!({"evaluations": self.evaluations}),
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn evaluations(&self) -> u64 {
|
||||||
|
self.evaluations
|
||||||
|
}
|
||||||
|
|
||||||
|
fn capture(&self) -> DomainResult<TypedValue> {
|
||||||
|
Ok(self.progress())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_restore(&self, _state: &TypedValue) -> DomainResult<()> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn install_restore(&mut self, _epoch: &Id, _state: &TypedValue) -> DomainResult<()> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rebase_ids(&self, _to_epoch: &Id) -> DomainResult<BTreeMap<Id, Id>> {
|
||||||
|
Ok(BTreeMap::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn event_watermarks(&self) -> (u64, u64) {
|
||||||
|
(0, 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The joypad the decision's buttons ask for.
|
||||||
|
struct Buttons;
|
||||||
|
|
||||||
|
impl ActionExecutor for Buttons {
|
||||||
|
fn apply(
|
||||||
|
&mut self,
|
||||||
|
_scope: &Scope,
|
||||||
|
decision: &TypedValue,
|
||||||
|
_current: &Inspection,
|
||||||
|
_progress: &TypedValue,
|
||||||
|
_clock: &RationalNs,
|
||||||
|
) -> DomainResult<(ControllerIntent, Vec<TaskEvent>)> {
|
||||||
|
let decision =
|
||||||
|
ChannelsDecision::from_typed(decision).map_err(|e| DomainError::invalid(e.0))?;
|
||||||
|
let control = fly_session::legacy_env::control_of("p1", decision.mask());
|
||||||
|
Ok((
|
||||||
|
ControllerIntent {
|
||||||
|
buttons: control.buttons,
|
||||||
|
axes: control.axes,
|
||||||
|
},
|
||||||
|
Vec::new(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn capture(&self) -> DomainResult<TypedValue> {
|
||||||
|
Ok(TypedValue::new(schema("buttons"), json!({})).unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_restore(&self, _state: &TypedValue) -> DomainResult<()> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn install_restore(&mut self, _state: &TypedValue) -> DomainResult<()> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run(mode: ExecutionMode) {
|
||||||
|
let root = tempfile::tempdir().unwrap();
|
||||||
|
let rom = toy_cart::rom(0);
|
||||||
|
let rom_path = root.path().join("toy.gb");
|
||||||
|
std::fs::write(&rom_path, &rom).unwrap();
|
||||||
|
let store = root.path().join("store");
|
||||||
|
let sockets = root.path().join("sockets");
|
||||||
|
std::fs::create_dir_all(&sockets).unwrap();
|
||||||
|
let policy = Policy::closed()
|
||||||
|
.client(
|
||||||
|
"coordinator",
|
||||||
|
grants(|g| {
|
||||||
|
g.call = vec![Pattern::prefix("agent."), Pattern::prefix("env.")];
|
||||||
|
g.publish = vec![Pattern::prefix("session.")];
|
||||||
|
g.manage_topics = vec![Pattern::prefix("session.")];
|
||||||
|
g.register = vec![Pattern::prefix("session.")];
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.client(
|
||||||
|
SUPERVISOR_CLIENT,
|
||||||
|
grants(|g| g.call = vec![Pattern::prefix("agent."), Pattern::prefix("env.")]),
|
||||||
|
)
|
||||||
|
.client(
|
||||||
|
"world",
|
||||||
|
grants(|g| g.register = vec![Pattern::exact("env.world")]),
|
||||||
|
)
|
||||||
|
.client(
|
||||||
|
"fly",
|
||||||
|
grants(|g| g.register = vec![Pattern::exact("agent.fly")]),
|
||||||
|
);
|
||||||
|
let mut config = RouterConfig::new(&store);
|
||||||
|
config.policy = policy;
|
||||||
|
let router = flybus::Router::new(config).unwrap();
|
||||||
|
let mut launcher = Launcher::start(
|
||||||
|
router,
|
||||||
|
mode,
|
||||||
|
Via::Unix,
|
||||||
|
&store,
|
||||||
|
&sockets,
|
||||||
|
ThreadBudget::new(3, 1).unwrap(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let mut backend = BackendConfig::legacy(&digest_of_bytes(&rom));
|
||||||
|
backend.slots = vec![id("best")];
|
||||||
|
launcher
|
||||||
|
.launch_legacy_environment(LegacyEnvironmentLaunch {
|
||||||
|
session_id: id("s"),
|
||||||
|
worker_id: id("world"),
|
||||||
|
incarnation_id: id("world-1"),
|
||||||
|
worker_threads: 1,
|
||||||
|
rom_path,
|
||||||
|
backend: backend.clone(),
|
||||||
|
client_id: "world".into(),
|
||||||
|
service: "env.world".into(),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
launcher
|
||||||
|
.launch_legacy_agent(LegacyAgentLaunch {
|
||||||
|
session_id: id("s"),
|
||||||
|
agent_id: id("fly"),
|
||||||
|
port_id: id("p1"),
|
||||||
|
incarnation_id: id("fly-1"),
|
||||||
|
worker_threads: 1,
|
||||||
|
dataset_dir: fly_session::legacy_parity::toy::dir(),
|
||||||
|
profile: LegacyProfileKind::Toy,
|
||||||
|
macro_channels: Vec::new(),
|
||||||
|
client_id: "fly".into(),
|
||||||
|
service: "agent.fly".into(),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let mut slot = AgentSlot::new(
|
||||||
|
launcher.worker(&id("fly")).unwrap().worker_ref(),
|
||||||
|
id("fly"),
|
||||||
|
id("p1"),
|
||||||
|
LegacyProfileKind::Toy.profile().asset,
|
||||||
|
fly_session::legacy_parity::LEGACY_SEED,
|
||||||
|
);
|
||||||
|
slot.model_version = gameboy::KERNEL_VERSION.into();
|
||||||
|
slot.plasticity_version = gameboy::PLASTICITY_VERSION.into();
|
||||||
|
let seen = Arc::new(Mutex::new(Seen::default()));
|
||||||
|
let task = Scripted {
|
||||||
|
agent: id("fly"),
|
||||||
|
seen: seen.clone(),
|
||||||
|
evaluations: 0,
|
||||||
|
};
|
||||||
|
let executors: BTreeMap<Id, Box<dyn ActionExecutor>> =
|
||||||
|
BTreeMap::from([(id("fly"), Box::new(Buttons) as Box<dyn ActionExecutor>)]);
|
||||||
|
let mut coordinator = Coordinator::new(
|
||||||
|
launcher.connect("coordinator").await.unwrap(),
|
||||||
|
id("s"),
|
||||||
|
id("e1"),
|
||||||
|
id("ep1"),
|
||||||
|
launcher.worker(&id("world")).unwrap().worker_ref(),
|
||||||
|
vec![slot],
|
||||||
|
Box::new(task),
|
||||||
|
executors,
|
||||||
|
);
|
||||||
|
coordinator.set_environment_config(
|
||||||
|
backend.asset_ref(),
|
||||||
|
fly_session::environment::synthetic_asset("scripted", "scripted-v1"),
|
||||||
|
);
|
||||||
|
coordinator.set_media(
|
||||||
|
&[gameboy::VIEW_ID],
|
||||||
|
&[fly_session::legacy_env::AUDIO_STREAM_ID],
|
||||||
|
);
|
||||||
|
coordinator.set_state_format(STATE_FORMAT_ID);
|
||||||
|
coordinator.set_decision_schema(gameboy::CHANNELS.schema_ref());
|
||||||
|
coordinator
|
||||||
|
.declare_rollback_policy(ROLLBACK_POLICY)
|
||||||
|
.unwrap();
|
||||||
|
coordinator.record_details(true);
|
||||||
|
coordinator
|
||||||
|
.bootstrap()
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|e| panic!("bootstrap: {}", e.error.message));
|
||||||
|
coordinator.disable_pacing();
|
||||||
|
let admissions = coordinator.admissions();
|
||||||
|
assert_eq!(
|
||||||
|
admissions.stimulus_remaining_ms(&id("fly")),
|
||||||
|
None,
|
||||||
|
"no commit yet"
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut actions = Vec::new();
|
||||||
|
for k in 0..9u64 {
|
||||||
|
if k == 2 {
|
||||||
|
// Two sugars before the next commit: the legacy drain admits the first and refuses
|
||||||
|
// the second (its pulse is already active), and so does the session's admission.
|
||||||
|
let mut legacy = flysim::ratelimit::RateLimiter::new(6);
|
||||||
|
let mut remaining = admissions
|
||||||
|
.stimulus_remaining_ms(&id("fly"))
|
||||||
|
.expect("committed");
|
||||||
|
let legacy_answers: Vec<_> = [300.0, 250.0]
|
||||||
|
.iter()
|
||||||
|
.map(|duration: &f64| {
|
||||||
|
let answer = legacy.admit(1_000, remaining);
|
||||||
|
if answer.is_ok() {
|
||||||
|
remaining = remaining.max(*duration);
|
||||||
|
}
|
||||||
|
answer
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let mut sugar =
|
||||||
|
fly_legacy_session::admission::LegacyAdmission::new(admissions.clone(), id("fly"));
|
||||||
|
let first = sugar.sugar(1_000, Some(300.0)).map(|(_, d)| d);
|
||||||
|
let second = sugar.sugar(1_000, Some(250.0)).map(|(_, d)| d);
|
||||||
|
assert_eq!(first, Ok(300.0));
|
||||||
|
assert_eq!(legacy_answers[0], Ok(()));
|
||||||
|
assert_eq!(
|
||||||
|
second.err(),
|
||||||
|
legacy_answers[1].err(),
|
||||||
|
"the second is refused as legacy refuses it"
|
||||||
|
);
|
||||||
|
assert_eq!(admissions.queued(), 1);
|
||||||
|
}
|
||||||
|
let report = coordinator.step().await.unwrap_or_else(|e| {
|
||||||
|
panic!(
|
||||||
|
"{} step {k}: {} ({})",
|
||||||
|
mode.label(),
|
||||||
|
e.error.message,
|
||||||
|
e.detail
|
||||||
|
)
|
||||||
|
});
|
||||||
|
assert_eq!(report.boundary, k + 1);
|
||||||
|
assert!(
|
||||||
|
!report.paused && !report.terminal,
|
||||||
|
"a rollback is not an episode end"
|
||||||
|
);
|
||||||
|
let details = coordinator.take_details().unwrap();
|
||||||
|
if k == 2 {
|
||||||
|
assert_eq!(
|
||||||
|
details.admissions.len(),
|
||||||
|
1,
|
||||||
|
"the sugar is cut into Prepare(2)"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for action in &details.boundary_actions {
|
||||||
|
actions.push((k + 1, action.kind, action.state_digest.clone()));
|
||||||
|
}
|
||||||
|
if k + 1 == 6 {
|
||||||
|
let rollback = details.rollback.as_ref().expect("the rollback's details");
|
||||||
|
assert_eq!(rollback.epoch, id("e1.rb1"));
|
||||||
|
assert_eq!(rollback.observation.boundary, 6);
|
||||||
|
assert!(
|
||||||
|
rollback.observation.audio.is_empty(),
|
||||||
|
"a restore plays no interval"
|
||||||
|
);
|
||||||
|
assert_eq!(rollback.agents.len(), 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
coordinator.epoch(),
|
||||||
|
&id("e1.rb1"),
|
||||||
|
"the session steps on in the new epoch"
|
||||||
|
);
|
||||||
|
assert_eq!(actions.len(), 2);
|
||||||
|
assert_eq!(
|
||||||
|
(actions[0].0, actions[0].1),
|
||||||
|
(3, BoundaryActionKind::SaveSlot)
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
actions[0].2.is_some(),
|
||||||
|
"a save records the saved state's digest"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
(actions[1].0, actions[1].1, actions[1].2.clone()),
|
||||||
|
(6, BoundaryActionKind::Rollback, None)
|
||||||
|
);
|
||||||
|
let phases: Vec<String> = coordinator
|
||||||
|
.trace
|
||||||
|
.phases
|
||||||
|
.iter()
|
||||||
|
.map(|p| format!("{}->{}", p.from, p.to))
|
||||||
|
.collect();
|
||||||
|
assert!(
|
||||||
|
phases.contains(&"Ready(6)->RollingBack(6)".to_owned()),
|
||||||
|
"{phases:?}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
phases.contains(&"RollingBack(6)->Ready(6)".to_owned()),
|
||||||
|
"{phases:?}"
|
||||||
|
);
|
||||||
|
let traced: Vec<(u64, usize)> = coordinator
|
||||||
|
.trace
|
||||||
|
.transitions
|
||||||
|
.iter()
|
||||||
|
.map(|t| {
|
||||||
|
(
|
||||||
|
t.behaviour.acknowledged_boundary,
|
||||||
|
t.behaviour.boundary_actions.len(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.filter(|(_, n)| *n > 0)
|
||||||
|
.collect();
|
||||||
|
assert_eq!(
|
||||||
|
traced,
|
||||||
|
vec![(3, 1), (6, 1)],
|
||||||
|
"the trace carries the boundary actions"
|
||||||
|
);
|
||||||
|
let seen = std::mem::take(&mut *seen.lock().unwrap());
|
||||||
|
let (boundary, restored) = seen.restored.clone().expect("the task rolled back");
|
||||||
|
assert_eq!(boundary, 6);
|
||||||
|
assert_eq!(
|
||||||
|
restored, seen.images[&3],
|
||||||
|
"O'[6] is the world saved at boundary 3"
|
||||||
|
);
|
||||||
|
assert_ne!(
|
||||||
|
restored, seen.images[&6],
|
||||||
|
"and not the one the rollback threw away"
|
||||||
|
);
|
||||||
|
let ended = admissions.take_ended();
|
||||||
|
assert_eq!(ended.len(), 1);
|
||||||
|
assert_eq!(ended[0].1, AdmissionEnd::Applied { boundary: 3 });
|
||||||
|
assert_eq!(
|
||||||
|
admissions.pending_stimulus_ms(&id("fly")),
|
||||||
|
None,
|
||||||
|
"nothing pending once committed"
|
||||||
|
);
|
||||||
|
assert!(admissions.stimulus_remaining_ms(&id("fly")).is_some());
|
||||||
|
let audit = coordinator.audit.join(" ");
|
||||||
|
for needle in [
|
||||||
|
"save-slot:best@3",
|
||||||
|
"restore-slot:best@6",
|
||||||
|
"agent-rollback:fly@6",
|
||||||
|
"rolled-back:best@6",
|
||||||
|
] {
|
||||||
|
assert!(audit.contains(needle), "{needle} in {audit}");
|
||||||
|
}
|
||||||
|
launcher.reap_all(&id("done")).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||||
|
async fn a_save_then_a_rollback_in_process() {
|
||||||
|
run(ExecutionMode::InProcess).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||||
|
async fn a_save_then_a_rollback_as_processes() {
|
||||||
|
if !fly_session::launcher::default_worker_program().is_file() {
|
||||||
|
eprintln!("process mode skipped: no worker program");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
run(ExecutionMode::Process).await;
|
||||||
|
}
|
||||||
126
services/flysim/crates/fly-legacy-session/tests/save_handoff.rs
Normal file
126
services/flysim/crates/fly-legacy-session/tests/save_handoff.rs
Normal file
|
|
@ -0,0 +1,126 @@
|
||||||
|
//! TASK-01 round-2 review notes R2-1 and R2-2 on the session's save hand-off. The toy raw
|
||||||
|
//! composition from power-on (`FLY_ROM`; a build without it skips):
|
||||||
|
//!
|
||||||
|
//! - R2-1: a save begun at boundary k reaches the writer even when the step after it fails, and
|
||||||
|
//! `flush_captures` hands it over while the loop idles (a pause), as the legacy loop's writer
|
||||||
|
//! thread has it from the boundary on.
|
||||||
|
//! - R2-2: `completed_saves` reports every queued save's outcome, a failed one beside the rest.
|
||||||
|
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use fly_legacy_session::composition::{
|
||||||
|
LegacyConfig, LegacySession, StoreConfig,
|
||||||
|
};
|
||||||
|
use fly_session::ExecutionMode;
|
||||||
|
use fly_session::legacy_agent::LegacyProfileKind;
|
||||||
|
use fly_session::legacy_checkpoint::SaveKind;
|
||||||
|
use fly_session::legacy_parity;
|
||||||
|
use fly_session::types::id;
|
||||||
|
use flysim::snapshot::MacroMode;
|
||||||
|
|
||||||
|
async fn session(root: &std::path::Path) -> Option<(LegacySession, StoreConfig)> {
|
||||||
|
let Some(rom_path) = std::env::var_os("FLY_ROM").map(PathBuf::from) else {
|
||||||
|
eprintln!("skipping: FLY_ROM is not set (source bin/rom-env.sh)");
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
let config = LegacyConfig {
|
||||||
|
mode: ExecutionMode::InProcess,
|
||||||
|
rom_path,
|
||||||
|
dataset_dir: legacy_parity::toy::dir(),
|
||||||
|
profile: LegacyProfileKind::Toy,
|
||||||
|
macro_mode: MacroMode::Raw,
|
||||||
|
agent_id: id("fly"),
|
||||||
|
agent_threads: 1,
|
||||||
|
record: true,
|
||||||
|
};
|
||||||
|
let mut session = LegacySession::start(&root.join("run"), config)
|
||||||
|
.await
|
||||||
|
.expect("the session starts");
|
||||||
|
session.bootstrap().await.expect("Ready(0)");
|
||||||
|
let store = StoreConfig {
|
||||||
|
hot_dir: root.join("hot"),
|
||||||
|
durable_dir: root.join("durable"),
|
||||||
|
keep_generations: 4,
|
||||||
|
// Saves only when asked.
|
||||||
|
hot_seconds: 1e9,
|
||||||
|
checkpoint_seconds: 1e9,
|
||||||
|
speed: 1.0,
|
||||||
|
};
|
||||||
|
session.attach_store(&store).expect("the store attaches");
|
||||||
|
Some((session, store))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One step, then the interval save it began (the first boundary is due for a durable one)
|
||||||
|
/// written and collected, so a test starts with nothing queued.
|
||||||
|
async fn warm_up(session: &mut LegacySession) {
|
||||||
|
session.advance().await.expect("a step");
|
||||||
|
session.flush_captures().await.expect("the flush");
|
||||||
|
for outcome in session.completed_saves(true).await {
|
||||||
|
outcome.expect("the first save");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn files_in(dir: &std::path::Path) -> usize {
|
||||||
|
std::fs::read_dir(dir)
|
||||||
|
.map(|entries| entries.filter_map(Result::ok).count())
|
||||||
|
.unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||||
|
async fn a_begun_save_reaches_the_writer_when_the_next_step_fails() {
|
||||||
|
let root = tempfile::tempdir().expect("tmp");
|
||||||
|
let Some((mut session, _)) = session(root.path()).await else { return };
|
||||||
|
warm_up(&mut session).await;
|
||||||
|
for _ in 0..2 {
|
||||||
|
session.advance().await.expect("a step");
|
||||||
|
}
|
||||||
|
session.begin_save(SaveKind::Hot).await.expect("a capture begins");
|
||||||
|
// The next transition fails at its commit.
|
||||||
|
session.coordinator.injections.at_step = 3;
|
||||||
|
session.coordinator.injections.undeclared_stimulus = true;
|
||||||
|
let error = session.advance().await.err().expect("the step fails");
|
||||||
|
assert!(error.starts_with("step ("), "{error}");
|
||||||
|
let outcomes = session.completed_saves(true).await;
|
||||||
|
assert_eq!(outcomes.len(), 1, "the save begun before the failed step was written");
|
||||||
|
let report = outcomes.into_iter().next().unwrap().expect("and it committed");
|
||||||
|
assert!(!report.durable);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||||
|
async fn a_pause_flushes_the_begun_save() {
|
||||||
|
let root = tempfile::tempdir().expect("tmp");
|
||||||
|
let Some((mut session, store)) = session(root.path()).await else { return };
|
||||||
|
warm_up(&mut session).await;
|
||||||
|
session.begin_save(SaveKind::Hot).await.expect("a capture begins");
|
||||||
|
let before = files_in(&store.hot_dir);
|
||||||
|
let queued = session.flush_captures().await.expect("the flush");
|
||||||
|
assert_eq!(queued.len(), 1);
|
||||||
|
let outcomes = session.completed_saves(true).await;
|
||||||
|
assert_eq!(outcomes.len(), 1);
|
||||||
|
assert!(outcomes[0].is_ok());
|
||||||
|
assert!(files_in(&store.hot_dir) > before, "the hot generation is on disk");
|
||||||
|
assert!(
|
||||||
|
session.flush_captures().await.expect("a second flush").is_empty(),
|
||||||
|
"nothing is held twice"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||||
|
async fn every_save_outcome_is_reported_after_a_failure() {
|
||||||
|
let root = tempfile::tempdir().expect("tmp");
|
||||||
|
let Some((mut session, store)) = session(root.path()).await else { return };
|
||||||
|
warm_up(&mut session).await;
|
||||||
|
// The store's hot directory goes away under the writer: every save after it fails. The
|
||||||
|
// first failure must not hide the outcomes behind it.
|
||||||
|
std::fs::remove_dir_all(&store.hot_dir).expect("remove hot");
|
||||||
|
std::fs::write(&store.hot_dir, b"not a directory").expect("block hot");
|
||||||
|
let mut expected = 0;
|
||||||
|
for _ in 0..3 {
|
||||||
|
session.begin_save(SaveKind::Hot).await.expect("begin");
|
||||||
|
session.flush_captures().await.expect("flush");
|
||||||
|
expected += 1;
|
||||||
|
}
|
||||||
|
let outcomes = session.completed_saves(true).await;
|
||||||
|
assert_eq!(outcomes.len(), expected, "one outcome per queued save: {outcomes:?}");
|
||||||
|
assert!(outcomes.iter().all(Result::is_err), "the writes failed: {outcomes:?}");
|
||||||
|
}
|
||||||
823
services/flysim/crates/fly-legacy-session/tests/session_trace.rs
Normal file
823
services/flysim/crates/fly-legacy-session/tests/session_trace.rs
Normal file
|
|
@ -0,0 +1,823 @@
|
||||||
|
//! TASK-01's pre-shadow proof: a whole new-runtime session -- the legacy agent worker (AGENT-01),
|
||||||
|
//! the legacy environment worker (ENV-01) and the `pokered-macros-v1` task and executor in the
|
||||||
|
//! coordinator -- reproduces the legacy loop's `FLY_TRACE` (FND-01) frame by frame: ticks, clock,
|
||||||
|
//! remainder, rates, spikes, decision, joypad mask, macro events, frame, work RAM, rewards, rank,
|
||||||
|
//! slot saves and rollbacks. Where the legacy side is a host run in this process, the ledgers
|
||||||
|
//! (adapter, ratchet, executor) are compared after every boundary too.
|
||||||
|
//!
|
||||||
|
//! Every run is an explicit ROM job (the operator's rom env script, never a download):
|
||||||
|
//!
|
||||||
|
//! - `toy_raw_from_power_on` (`FLY_ROM`): the committed toy connectome in raw mode from power-on,
|
||||||
|
//! with sugar admitted through the coordinator's admission queue.
|
||||||
|
//! - `fafb_service_trace_checkpoints` (`FLY_TASK01_FAFB=1`, `FLY_ENV01_TRACE_DIR`,
|
||||||
|
//! `FLY_DOOR_CHECKPOINT`): the checkpoints of the service's own traces (the FND-01 review's
|
||||||
|
//! `rollback`, `climb` and `r58`: a ratchet rollback, a slot save, two real rewards), for each
|
||||||
|
//! trace's length, against today's legacy loop; the session imported from the same FLYSIM01
|
||||||
|
//! files. `FLY_TASK01_TRACE_LIMIT` caps each.
|
||||||
|
//! - `fafb_reward_segments` (`FLY_TASK01_FAFB=1`): host runs of `LegacyFrame` from stream
|
||||||
|
//! checkpoints, with sugar, in two arms. The brain arm: the adapter ledger thinned so rewards
|
||||||
|
//! fire where the fly already is (new area, exits, new ground, wild wins). The driver arm: the
|
||||||
|
//! brain ticks and decodes as always but the executor is handed the ROM tests' rotation driver's
|
||||||
|
//! decision (`fly_legacy_session::driver`), which walks, talks, fights and picks up, so real
|
||||||
|
//! rewards reach `Agent.Commit`. `FLY_TASK01_SEGMENTS` picks the checkpoints (`name=path,...`),
|
||||||
|
//! `FLY_TASK01_FRAMES` the length.
|
||||||
|
//!
|
||||||
|
//! Execution modes: in-process, then process (the workspace's `fly-session` binary); a build
|
||||||
|
//! without it skips process mode and says so.
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
use fly_legacy_session::admission::LegacyAdmission;
|
||||||
|
use fly_legacy_session::composition::{LegacyConfig, LegacySession, channels_and_hold};
|
||||||
|
use fly_legacy_session::driver::{DecisionDriver, RotationDriver};
|
||||||
|
use fly_legacy_session::task::ledgers_of;
|
||||||
|
use fly_legacy_session::trace::{self, Agreement};
|
||||||
|
use fly_session::ExecutionMode;
|
||||||
|
use fly_session::legacy_agent::LegacyProfileKind;
|
||||||
|
use fly_session::legacy_parity;
|
||||||
|
use fly_session::types::id;
|
||||||
|
use flybrain_core::agent::{AgentConfig, NeuralAgent};
|
||||||
|
use flybrain_core::dataset::{BrainDataset, load_brain_dataset_from_dir};
|
||||||
|
use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros;
|
||||||
|
use flybrain_gb::adapter::GameAdapter;
|
||||||
|
use flybrain_gb::pokemon_red::PokemonRedReward;
|
||||||
|
use flybrain_gb::ratchet::Ratchet;
|
||||||
|
use flybrain_gb::{AdapterLedger, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator};
|
||||||
|
use flysim::config::Config;
|
||||||
|
use flysim::frame::{LegacyFrame, Parts};
|
||||||
|
use flysim::macros::macro_layer;
|
||||||
|
use flysim::snapshot::MacroMode;
|
||||||
|
use flysim::trace::FrameTrace;
|
||||||
|
|
||||||
|
fn rom_path() -> Option<PathBuf> {
|
||||||
|
match std::env::var_os("FLY_ROM") {
|
||||||
|
Some(path) => Some(PathBuf::from(path)),
|
||||||
|
None => {
|
||||||
|
eprintln!("skipping: FLY_ROM is not set (source bin/rom-env.sh)");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fafb() -> Option<PathBuf> {
|
||||||
|
if std::env::var_os("FLY_TASK01_FAFB").is_none() {
|
||||||
|
eprintln!("skipping: FLY_TASK01_FAFB is not set");
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let dir = legacy_parity::fafb_dir();
|
||||||
|
if dir.is_none() {
|
||||||
|
eprintln!("skipping: data/fafb-v783 is not present in this checkout");
|
||||||
|
}
|
||||||
|
dir
|
||||||
|
}
|
||||||
|
|
||||||
|
fn env_usize(name: &str, default: usize) -> usize {
|
||||||
|
std::env::var(name)
|
||||||
|
.ok()
|
||||||
|
.and_then(|v| v.parse().ok())
|
||||||
|
.unwrap_or(default)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn modes() -> Vec<ExecutionMode> {
|
||||||
|
let mut modes = vec![ExecutionMode::InProcess];
|
||||||
|
let program = fly_session::launcher::default_worker_program();
|
||||||
|
if program.is_file() {
|
||||||
|
modes.push(ExecutionMode::Process);
|
||||||
|
} else {
|
||||||
|
eprintln!(
|
||||||
|
"process mode skipped: no worker program at {}",
|
||||||
|
program.display()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
modes
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What each frame admits at its top, in admission order, and whether the rotation driver hands
|
||||||
|
/// the executor its decisions.
|
||||||
|
#[derive(Clone, Debug, Default)]
|
||||||
|
struct Inputs {
|
||||||
|
/// `(frame index from 1, duration ms)`.
|
||||||
|
sugar: Vec<(usize, f64)>,
|
||||||
|
driver: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The legacy loop's one look into a decision: the driver's, when the run has one.
|
||||||
|
struct Driven(Option<RotationDriver>);
|
||||||
|
|
||||||
|
impl flysim::frame::FrameObserver for Driven {
|
||||||
|
fn readout(&mut self, ms: f64, bound: Option<&[String]>, active: &mut Vec<String>) {
|
||||||
|
if let Some(driver) = self.0.as_mut() {
|
||||||
|
driver.readout(ms, bound.unwrap_or(&[]), active);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How a run starts.
|
||||||
|
#[derive(Clone)]
|
||||||
|
enum Start {
|
||||||
|
PowerOn,
|
||||||
|
/// A FLYSIM01 file.
|
||||||
|
Checkpoint(Vec<u8>),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The run's `FLY_TRACE` behaviours and, when it has them, the ledgers after every boundary.
|
||||||
|
struct Run {
|
||||||
|
behaviours: Vec<Value>,
|
||||||
|
ledgers: Vec<String>,
|
||||||
|
/// The bound set of each transition's decision (session runs only).
|
||||||
|
bounds: Vec<Vec<String>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decoder_hold(mode: MacroMode) -> (Vec<&'static str>, f64) {
|
||||||
|
let channels = if mode.dealt() {
|
||||||
|
flybrain_gb::macro_channels("pokemon-red")
|
||||||
|
} else {
|
||||||
|
Vec::new()
|
||||||
|
};
|
||||||
|
let (_, hold) = channels_and_hold(mode);
|
||||||
|
(channels, hold)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The legacy loop in this process: `LegacyFrame` with `FLY_TRACE` on, admitting the inputs at
|
||||||
|
/// the top of each frame as the service's command drain does, the ledgers read after each
|
||||||
|
/// boundary.
|
||||||
|
fn run_legacy(
|
||||||
|
rom: &[u8],
|
||||||
|
data: &Arc<BrainDataset>,
|
||||||
|
start: &Start,
|
||||||
|
mode: MacroMode,
|
||||||
|
frames: usize,
|
||||||
|
inputs: &Inputs,
|
||||||
|
trace_path: &Path,
|
||||||
|
) -> Run {
|
||||||
|
let mut emulator =
|
||||||
|
Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES).expect("binjgb");
|
||||||
|
let mut adapter = PokemonRedReward::new();
|
||||||
|
let mut ratchet = Ratchet::with_policy(adapter.recovery_policy());
|
||||||
|
let mut config = Config::default();
|
||||||
|
config.loop_.game = "pokemon-red".to_owned();
|
||||||
|
config.macros.mode = mode;
|
||||||
|
let (channels, hold_ms) = decoder_hold(mode);
|
||||||
|
let mut agent_config = AgentConfig::with_decoder(gameboy_decoder_config_with_macros(&channels));
|
||||||
|
agent_config.warmup_ms = config.loop_.warmup_ms;
|
||||||
|
let mut agent = NeuralAgent::new(Arc::clone(data), agent_config).expect("an agent");
|
||||||
|
let mut frame =
|
||||||
|
LegacyFrame::new().with_trace(Some(FrameTrace::create(trace_path).expect("a trace")));
|
||||||
|
match start {
|
||||||
|
Start::PowerOn => {
|
||||||
|
frame
|
||||||
|
.initialize(&mut emulator, &mut agent)
|
||||||
|
.expect("the first frame and the warm-up");
|
||||||
|
}
|
||||||
|
Start::Checkpoint(bytes) => {
|
||||||
|
let checkpoint = flysim::store::decode(bytes).expect("FLYSIM01");
|
||||||
|
frame
|
||||||
|
.restore(
|
||||||
|
&mut Parts {
|
||||||
|
agent: &mut agent,
|
||||||
|
emulator: &mut emulator,
|
||||||
|
adapter: &mut adapter,
|
||||||
|
ratchet: &mut ratchet,
|
||||||
|
macros: None,
|
||||||
|
},
|
||||||
|
&checkpoint,
|
||||||
|
)
|
||||||
|
.expect("the checkpoint restores");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut macros = macro_layer(&config, hold_ms, agent.network.rng_state() as u32);
|
||||||
|
if let Some(layer) = macros.as_mut() {
|
||||||
|
let _ = layer.observe(&mut emulator, &AdapterLedger(&adapter), agent.network.ms);
|
||||||
|
}
|
||||||
|
let mut ledgers = Vec::new();
|
||||||
|
let mut observer = Driven(inputs.driver.then(RotationDriver::new));
|
||||||
|
for k in 1..=frames {
|
||||||
|
// The command drain: the sugar admitted for this frame, in admission order.
|
||||||
|
for (_, duration) in inputs.sugar.iter().filter(|(at, _)| *at == k) {
|
||||||
|
agent.network.stimulate(*duration);
|
||||||
|
if let Some(trace) = frame.trace_mut() {
|
||||||
|
trace.sugar(*duration);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut parts = Parts {
|
||||||
|
agent: &mut agent,
|
||||||
|
emulator: &mut emulator,
|
||||||
|
adapter: &mut adapter,
|
||||||
|
ratchet: &mut ratchet,
|
||||||
|
macros: macros.as_mut(),
|
||||||
|
};
|
||||||
|
let transition = frame
|
||||||
|
.transition(&mut parts, &mut observer)
|
||||||
|
.expect("a frame");
|
||||||
|
frame
|
||||||
|
.boundary(&mut parts, &transition.evaluated.progress, transition.ms)
|
||||||
|
.expect("the boundary");
|
||||||
|
ledgers.push(ledgers_of(&adapter, &ratchet, macros.as_ref()));
|
||||||
|
}
|
||||||
|
frame.finish_trace();
|
||||||
|
drop(frame);
|
||||||
|
let text = std::fs::read_to_string(trace_path).expect("the trace reads back");
|
||||||
|
Run {
|
||||||
|
behaviours: trace::behaviours(&text).expect("a FLY_TRACE"),
|
||||||
|
ledgers,
|
||||||
|
bounds: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The same run on the session framework.
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
async fn run_session(
|
||||||
|
mode: ExecutionMode,
|
||||||
|
rom_path: &Path,
|
||||||
|
dataset_dir: &Path,
|
||||||
|
profile: LegacyProfileKind,
|
||||||
|
macro_mode: MacroMode,
|
||||||
|
start: &Start,
|
||||||
|
frames: usize,
|
||||||
|
inputs: &Inputs,
|
||||||
|
) -> Run {
|
||||||
|
let root = tempfile::tempdir().expect("tmp");
|
||||||
|
let config = LegacyConfig {
|
||||||
|
mode,
|
||||||
|
rom_path: rom_path.to_owned(),
|
||||||
|
dataset_dir: dataset_dir.to_owned(),
|
||||||
|
profile,
|
||||||
|
macro_mode,
|
||||||
|
agent_id: id("fly"),
|
||||||
|
agent_threads: 1,
|
||||||
|
record: true,
|
||||||
|
};
|
||||||
|
let mut session = LegacySession::start(root.path(), config)
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|e| panic!("the session starts: {e}"));
|
||||||
|
if inputs.driver {
|
||||||
|
session.task.set_driver(Box::new(RotationDriver::new()));
|
||||||
|
}
|
||||||
|
session
|
||||||
|
.bootstrap()
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|e| panic!("Ready(0): {e}"));
|
||||||
|
if let Start::Checkpoint(bytes) = start {
|
||||||
|
session
|
||||||
|
.import_flysim01(bytes, &id("e2"))
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|e| panic!("the FLYSIM01 import: {e}"));
|
||||||
|
}
|
||||||
|
let mut admission = LegacyAdmission::new(session.coordinator.admissions(), id("fly"));
|
||||||
|
assert!(
|
||||||
|
admission.reward(1.0).is_err(),
|
||||||
|
"the operator reward pulse is refused"
|
||||||
|
);
|
||||||
|
let mut behaviours = Vec::new();
|
||||||
|
let mut ledgers = Vec::new();
|
||||||
|
let mut bounds = Vec::new();
|
||||||
|
for k in 1..=frames {
|
||||||
|
for (_, duration) in inputs.sugar.iter().filter(|(at, _)| *at == k) {
|
||||||
|
admission.replay_sugar(*duration);
|
||||||
|
}
|
||||||
|
let step = session
|
||||||
|
.step()
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|e| panic!("{} frame {k}: {e}", mode.label()));
|
||||||
|
let details = step.details.expect("details are recorded");
|
||||||
|
let [record] = step.records.as_slice() else {
|
||||||
|
panic!("frame {k}: {} task records", step.records.len());
|
||||||
|
};
|
||||||
|
behaviours.push(
|
||||||
|
trace::line(&details, record).unwrap_or_else(|e| panic!("frame {k}: {e}"))["behaviour"]
|
||||||
|
.clone(),
|
||||||
|
);
|
||||||
|
ledgers.push(record.ledgers.clone());
|
||||||
|
bounds.push(record.bound.clone());
|
||||||
|
}
|
||||||
|
let ended = session.coordinator.admissions().take_ended();
|
||||||
|
assert_eq!(
|
||||||
|
ended.len(),
|
||||||
|
inputs.sugar.iter().filter(|(k, _)| *k <= frames).count(),
|
||||||
|
"every admission ended"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
ended
|
||||||
|
.iter()
|
||||||
|
.all(|(_, end)| matches!(end, fly_session::coordinator::AdmissionEnd::Applied { .. })),
|
||||||
|
"and every one was applied"
|
||||||
|
);
|
||||||
|
let uncaptured = session.task.uncaptured_reads();
|
||||||
|
assert!(
|
||||||
|
uncaptured.is_empty(),
|
||||||
|
"the engine read addresses the image does not capture: {:04x?}",
|
||||||
|
uncaptured
|
||||||
|
);
|
||||||
|
session.stop().await;
|
||||||
|
Run {
|
||||||
|
behaviours,
|
||||||
|
ledgers,
|
||||||
|
bounds,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn report(what: &str, agreement: &Agreement, elapsed: std::time::Duration) {
|
||||||
|
eprintln!(
|
||||||
|
"{what} ({elapsed:?}): {} transitions identical ({} sugar, {} rewards {:?}, \
|
||||||
|
{} macro events, {} pressed, {} slot saves, {} rollbacks, {} spikes)",
|
||||||
|
agreement.transitions,
|
||||||
|
agreement.sugar,
|
||||||
|
agreement.rewards,
|
||||||
|
agreement.reward_kinds,
|
||||||
|
agreement.macro_events,
|
||||||
|
agreement.pressed,
|
||||||
|
agreement.saves,
|
||||||
|
agreement.rollbacks,
|
||||||
|
agreement.spikes
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn compare_ledgers(legacy: &[String], session: &[String]) {
|
||||||
|
assert_eq!(legacy.len(), session.len());
|
||||||
|
for (k, (a, b)) in legacy.iter().zip(session).enumerate() {
|
||||||
|
assert_eq!(a, b, "the ledgers after frame {}", k + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||||
|
async fn toy_raw_from_power_on() {
|
||||||
|
let Some(rom_path) = rom_path() else { return };
|
||||||
|
let rom = std::fs::read(&rom_path).expect("the cartridge");
|
||||||
|
let data = Arc::new(load_brain_dataset_from_dir(legacy_parity::toy::dir()).expect("the toy"));
|
||||||
|
let frames = env_usize("FLY_TASK01_TOY_FRAMES", 600);
|
||||||
|
let inputs = Inputs {
|
||||||
|
sugar: vec![(40, 300.0), (frames / 2, 500.0)],
|
||||||
|
driver: false,
|
||||||
|
};
|
||||||
|
let dir = tempfile::tempdir().expect("tmp");
|
||||||
|
let legacy = run_legacy(
|
||||||
|
&rom,
|
||||||
|
&data,
|
||||||
|
&Start::PowerOn,
|
||||||
|
MacroMode::Raw,
|
||||||
|
frames,
|
||||||
|
&inputs,
|
||||||
|
&dir.path().join("trace.jsonl"),
|
||||||
|
);
|
||||||
|
for mode in modes() {
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
let session = run_session(
|
||||||
|
mode,
|
||||||
|
&rom_path,
|
||||||
|
&legacy_parity::toy::dir(),
|
||||||
|
LegacyProfileKind::Toy,
|
||||||
|
MacroMode::Raw,
|
||||||
|
&Start::PowerOn,
|
||||||
|
frames,
|
||||||
|
&inputs,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let agreement = trace::compare(&legacy.behaviours, &session.behaviours, &session.bounds)
|
||||||
|
.unwrap_or_else(|e| panic!("{}: {e}", mode.label()));
|
||||||
|
compare_ledgers(&legacy.ledgers, &session.ledgers);
|
||||||
|
assert_eq!(agreement.sugar, 2);
|
||||||
|
report(
|
||||||
|
&format!("toy raw, {}", mode.label()),
|
||||||
|
&agreement,
|
||||||
|
started.elapsed(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The checkpoints of the service's own traces (the FND-01 review's `rollback` -- a ratchet
|
||||||
|
/// rollback on the first boundary, a real `talk` reward -- `climb` -- a ratchet slot save -- and
|
||||||
|
/// `r58` -- a real `talk` reward -- with their start checkpoints).
|
||||||
|
///
|
||||||
|
/// Those traces were recorded by the service as it stood on 2026-09-23. The macro engine has
|
||||||
|
/// changed since (loop-review rows 59 to 67), so from some frame on they are not what today's
|
||||||
|
/// engine does. The reference is therefore FND-01's harness at this tree -- `LegacyFrame` with
|
||||||
|
/// `FLY_TRACE` on, which FND-01 proved byte-identical to the service's loop -- run here from the
|
||||||
|
/// same checkpoint for the trace's length; the session must match it frame by frame, ledgers
|
||||||
|
/// included. How far the recorded service trace agrees with today's legacy loop is reported, not
|
||||||
|
/// asserted.
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||||
|
async fn fafb_service_trace_checkpoints() {
|
||||||
|
let Some(rom_path) = rom_path() else { return };
|
||||||
|
let Some(dataset) = fafb() else { return };
|
||||||
|
let Some(dir) = std::env::var_os("FLY_ENV01_TRACE_DIR").map(PathBuf::from) else {
|
||||||
|
eprintln!("skipping: FLY_ENV01_TRACE_DIR is not set");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let rom = std::fs::read(&rom_path).expect("the cartridge");
|
||||||
|
let data = Arc::new(load_brain_dataset_from_dir(&dataset).expect("the dataset"));
|
||||||
|
let limit = env_usize("FLY_TASK01_TRACE_LIMIT", usize::MAX);
|
||||||
|
let names: Vec<String> = std::env::var("FLY_TASK01_TRACES")
|
||||||
|
.map(|v| v.split(',').map(str::to_owned).collect())
|
||||||
|
.unwrap_or_else(|_| vec!["rollback".into(), "climb".into(), "r58".into()]);
|
||||||
|
for name in names {
|
||||||
|
let checkpoint = if name == "r58" {
|
||||||
|
std::env::var_os("FLY_DOOR_CHECKPOINT").map(PathBuf::from)
|
||||||
|
} else {
|
||||||
|
Some(dir.join(format!("{name}.checkpoint")))
|
||||||
|
};
|
||||||
|
let Some(checkpoint) = checkpoint.filter(|c| c.is_file()) else {
|
||||||
|
eprintln!("skipping {name}: no checkpoint");
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let text =
|
||||||
|
std::fs::read_to_string(dir.join(format!("{name}.trace.jsonl"))).expect("the trace");
|
||||||
|
let mut service = trace::behaviours(&text).expect("a FLY_TRACE");
|
||||||
|
service.truncate(limit);
|
||||||
|
let frames = service.len();
|
||||||
|
let bytes = std::fs::read(&checkpoint).expect("the checkpoint");
|
||||||
|
let start = Start::Checkpoint(bytes);
|
||||||
|
let tmp = tempfile::tempdir().expect("tmp");
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
let legacy = run_legacy(
|
||||||
|
&rom,
|
||||||
|
&data,
|
||||||
|
&start,
|
||||||
|
MacroMode::Macros,
|
||||||
|
frames,
|
||||||
|
&Inputs::default(),
|
||||||
|
&tmp.path().join("trace.jsonl"),
|
||||||
|
);
|
||||||
|
let agreed = legacy
|
||||||
|
.behaviours
|
||||||
|
.iter()
|
||||||
|
.zip(&service)
|
||||||
|
.take_while(|(today, recorded)| today == recorded)
|
||||||
|
.count();
|
||||||
|
eprintln!(
|
||||||
|
"legacy loop {name}: {frames} frames in {:?}; the recorded service trace agrees with \
|
||||||
|
today's loop for its first {agreed} transitions",
|
||||||
|
started.elapsed()
|
||||||
|
);
|
||||||
|
for mode in modes() {
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
let session = run_session(
|
||||||
|
mode,
|
||||||
|
&rom_path,
|
||||||
|
&dataset,
|
||||||
|
LegacyProfileKind::Production,
|
||||||
|
MacroMode::Macros,
|
||||||
|
&start,
|
||||||
|
frames,
|
||||||
|
&Inputs::default(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let agreement =
|
||||||
|
trace::compare(&legacy.behaviours, &session.behaviours, &session.bounds)
|
||||||
|
.unwrap_or_else(|e| panic!("{name}, {}: {e}", mode.label()));
|
||||||
|
compare_ledgers(&legacy.ledgers, &session.ledgers);
|
||||||
|
report(
|
||||||
|
&format!("service checkpoint {name}, {}", mode.label()),
|
||||||
|
&agreement,
|
||||||
|
started.elapsed(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs `frames` transitions of a booted session with the store attached, recording the
|
||||||
|
/// session's `FLY_TRACE` behaviours, ledgers and bound sets, and every save it took.
|
||||||
|
async fn run_booted(
|
||||||
|
session: &mut LegacySession,
|
||||||
|
frames: usize,
|
||||||
|
) -> (Run, Vec<fly_legacy_session::composition::SaveQueued>) {
|
||||||
|
let mut run = Run {
|
||||||
|
behaviours: Vec::new(),
|
||||||
|
ledgers: Vec::new(),
|
||||||
|
bounds: Vec::new(),
|
||||||
|
};
|
||||||
|
let mut saves = Vec::new();
|
||||||
|
for k in 1..=frames {
|
||||||
|
let (step, saved) = session
|
||||||
|
.advance()
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|e| panic!("frame {k}: {e}"));
|
||||||
|
saves.extend(saved);
|
||||||
|
let details = step.details.expect("details are recorded");
|
||||||
|
let [record] = step.records.as_slice() else {
|
||||||
|
panic!("frame {k}: {} task records", step.records.len());
|
||||||
|
};
|
||||||
|
run.behaviours.push(
|
||||||
|
trace::line(&details, record).unwrap_or_else(|e| panic!("frame {k}: {e}"))["behaviour"]
|
||||||
|
.clone(),
|
||||||
|
);
|
||||||
|
run.ledgers.push(record.ledgers.clone());
|
||||||
|
run.bounds.push(record.bound.clone());
|
||||||
|
}
|
||||||
|
(run, saves)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The SHADOW-01 entry gate: the session runtime boots from a live FLYSIM01 store, runs, saves,
|
||||||
|
/// restarts and restores from its own save, and every segment matches the legacy loop's trace.
|
||||||
|
///
|
||||||
|
/// The store holds one durable generation, a stream checkpoint (the FND-01 review's `rollback`
|
||||||
|
/// file when `FLY_ENV01_TRACE_DIR` is set: a ratchet rollback on the first boundary, so the
|
||||||
|
/// after-rollback durable save is exercised; else `FLY_DOOR_CHECKPOINT`). Process one boots from
|
||||||
|
/// it (the legacy candidate order and gate, `boot`), writes its startup durable save, runs
|
||||||
|
/// `FLY_TASK01_BOOT_FRAMES` transitions with the legacy boundary saves, and shuts down with a
|
||||||
|
/// durable save. Process two boots from the same store and so restores process one's shutdown
|
||||||
|
/// save -- a file the session runtime wrote -- and runs on. The legacy loop runs the first
|
||||||
|
/// segment from the original file and the second from process one's save, which is also the
|
||||||
|
/// proof that the legacy loop reads what the session runtime writes. In-process then process.
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||||
|
async fn fafb_boot_run_save_restore() {
|
||||||
|
let Some(rom_path) = rom_path() else { return };
|
||||||
|
let Some(dataset) = fafb() else { return };
|
||||||
|
// The rollback file (a ratchet rollback on the first boundary), and the live fly's largest
|
||||||
|
// task ledgers: row 64 (42 KB) and the row 65 yard (46 KB), past the 32 KiB TypedValue bound
|
||||||
|
// (TASK-01 review B1). `FLY_TASK01_BOOT_SOURCES` picks others (`name=path,...`).
|
||||||
|
let sources: Vec<(String, PathBuf)> = match std::env::var("FLY_TASK01_BOOT_SOURCES") {
|
||||||
|
Ok(list) => list
|
||||||
|
.split(',')
|
||||||
|
.filter_map(|item| {
|
||||||
|
item.split_once('=')
|
||||||
|
.map(|(n, p)| (n.to_owned(), PathBuf::from(p)))
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
Err(_) => [
|
||||||
|
(
|
||||||
|
"rollback",
|
||||||
|
std::env::var_os("FLY_ENV01_TRACE_DIR")
|
||||||
|
.map(|dir| PathBuf::from(dir).join("rollback.checkpoint")),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"row64",
|
||||||
|
std::env::var_os("FLY_ROW64_CHECKPOINT").map(PathBuf::from),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"row65-yard",
|
||||||
|
std::env::var_os("FLY_ROW65_YARD_CHECKPOINT").map(PathBuf::from),
|
||||||
|
),
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|(name, path)| path.filter(|p| p.is_file()).map(|p| (name.to_owned(), p)))
|
||||||
|
.collect(),
|
||||||
|
};
|
||||||
|
if sources.is_empty() {
|
||||||
|
eprintln!("skipping: no source checkpoint");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let rom = std::fs::read(&rom_path).expect("the cartridge");
|
||||||
|
let data = Arc::new(load_brain_dataset_from_dir(&dataset).expect("the dataset"));
|
||||||
|
let frames = env_usize("FLY_TASK01_BOOT_FRAMES", 900);
|
||||||
|
for (name, source) in sources {
|
||||||
|
let original = std::fs::read(&source).expect("the checkpoint");
|
||||||
|
let decoded = flysim::store::decode(&original).expect("FLYSIM01");
|
||||||
|
let generation = decoded.runtime.generation;
|
||||||
|
eprintln!(
|
||||||
|
"boot source {name}: generation {generation}, task ledger {} bytes of adapter JSON",
|
||||||
|
serde_json::to_vec(&decoded.runtime.reward)
|
||||||
|
.map(|v| v.len())
|
||||||
|
.unwrap_or(0)
|
||||||
|
);
|
||||||
|
for mode in modes() {
|
||||||
|
let root = tempfile::tempdir().expect("tmp");
|
||||||
|
let store = fly_legacy_session::composition::StoreConfig {
|
||||||
|
hot_dir: root.path().join("hot"),
|
||||||
|
durable_dir: root.path().join("durable"),
|
||||||
|
keep_generations: 4,
|
||||||
|
// The intervals are wall clock; a parity run takes its saves at the boundaries the
|
||||||
|
// legacy loop names (startup, a climb, a rollback, shutdown) and not on a timer.
|
||||||
|
hot_seconds: 1e9,
|
||||||
|
checkpoint_seconds: 1e9,
|
||||||
|
speed: 1.0,
|
||||||
|
};
|
||||||
|
flysim::store::Store::new(&store.durable_dir, store.keep_generations)
|
||||||
|
.commit(generation, &original, None)
|
||||||
|
.expect("the seeded store");
|
||||||
|
let config = |mode| LegacyConfig {
|
||||||
|
mode,
|
||||||
|
rom_path: rom_path.clone(),
|
||||||
|
dataset_dir: dataset.clone(),
|
||||||
|
profile: LegacyProfileKind::Production,
|
||||||
|
macro_mode: MacroMode::Macros,
|
||||||
|
agent_id: id("fly"),
|
||||||
|
agent_threads: 1,
|
||||||
|
record: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Process one.
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
let (mut one, boot) = fly_legacy_session::composition::boot(
|
||||||
|
&root.path().join("p1"),
|
||||||
|
config(mode),
|
||||||
|
&store,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|e| panic!("{}: boot one: {e}", mode.label()));
|
||||||
|
match &boot {
|
||||||
|
fly_legacy_session::composition::Boot::Restored { candidate, .. } => {
|
||||||
|
assert_eq!(
|
||||||
|
candidate.generation,
|
||||||
|
Some(generation),
|
||||||
|
"the seeded generation"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
other => panic!("boot one: {other:?}"),
|
||||||
|
}
|
||||||
|
let startup = one.checkpointer().expect("attached").next_generation() - 1;
|
||||||
|
assert!(
|
||||||
|
startup > generation,
|
||||||
|
"the startup save takes a generation above the store's"
|
||||||
|
);
|
||||||
|
let (run_one, saves_one) = run_booted(&mut one, frames).await;
|
||||||
|
let shutdown = one
|
||||||
|
.shutdown_save()
|
||||||
|
.await
|
||||||
|
.expect("the shutdown save")
|
||||||
|
.expect("a store");
|
||||||
|
one.stop().await;
|
||||||
|
assert!(shutdown.durable);
|
||||||
|
let legacy_one = run_legacy(
|
||||||
|
&rom,
|
||||||
|
&data,
|
||||||
|
&Start::Checkpoint(original.clone()),
|
||||||
|
MacroMode::Macros,
|
||||||
|
frames,
|
||||||
|
&Inputs::default(),
|
||||||
|
&root.path().join("legacy-one.jsonl"),
|
||||||
|
);
|
||||||
|
let agreement =
|
||||||
|
trace::compare(&legacy_one.behaviours, &run_one.behaviours, &run_one.bounds)
|
||||||
|
.unwrap_or_else(|e| panic!("{} segment one: {e}", mode.label()));
|
||||||
|
compare_ledgers(&legacy_one.ledgers, &run_one.ledgers);
|
||||||
|
report(
|
||||||
|
&format!("boot {name} segment one, {}", mode.label()),
|
||||||
|
&agreement,
|
||||||
|
started.elapsed(),
|
||||||
|
);
|
||||||
|
eprintln!(
|
||||||
|
" saves: startup g{startup}, during the run {:?}, shutdown g{}",
|
||||||
|
saves_one
|
||||||
|
.iter()
|
||||||
|
.map(|s| (s.generation, s.durable, s.archive_rank))
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
shutdown.generation
|
||||||
|
);
|
||||||
|
if agreement.rollbacks > 0 {
|
||||||
|
assert!(
|
||||||
|
saves_one.iter().any(|s| s.durable),
|
||||||
|
"a rollback is followed by a durable save"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process two: restores process one's shutdown save.
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
let (mut two, boot) = fly_legacy_session::composition::boot(
|
||||||
|
&root.path().join("p2"),
|
||||||
|
config(mode),
|
||||||
|
&store,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|e| panic!("{}: boot two: {e}", mode.label()));
|
||||||
|
let restored_path = match &boot {
|
||||||
|
fly_legacy_session::composition::Boot::Restored { candidate, .. } => {
|
||||||
|
assert_eq!(
|
||||||
|
candidate.generation,
|
||||||
|
Some(shutdown.generation),
|
||||||
|
"the latest save"
|
||||||
|
);
|
||||||
|
candidate.path.clone()
|
||||||
|
}
|
||||||
|
other => panic!("boot two: {other:?}"),
|
||||||
|
};
|
||||||
|
let written = std::fs::read(&restored_path).expect("the session's own save");
|
||||||
|
let (run_two, _) = run_booted(&mut two, frames).await;
|
||||||
|
two.stop().await;
|
||||||
|
let legacy_two = run_legacy(
|
||||||
|
&rom,
|
||||||
|
&data,
|
||||||
|
&Start::Checkpoint(written),
|
||||||
|
MacroMode::Macros,
|
||||||
|
frames,
|
||||||
|
&Inputs::default(),
|
||||||
|
&root.path().join("legacy-two.jsonl"),
|
||||||
|
);
|
||||||
|
let agreement =
|
||||||
|
trace::compare(&legacy_two.behaviours, &run_two.behaviours, &run_two.bounds)
|
||||||
|
.unwrap_or_else(|e| panic!("{} segment two: {e}", mode.label()));
|
||||||
|
compare_ledgers(&legacy_two.ledgers, &run_two.ledgers);
|
||||||
|
report(
|
||||||
|
&format!("boot {name} segment two, {}", mode.label()),
|
||||||
|
&agreement,
|
||||||
|
started.elapsed(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Thins a checkpoint's adapter ledger so the fly earns rewards: the current map is unvisited
|
||||||
|
/// (an `AREA` payout on the first sample), its exits unfound (`boundary`), its ground unwalked
|
||||||
|
/// (`exploration`), and no wild win is a replay (`battle`).
|
||||||
|
fn reward_bearing(bytes: &[u8]) -> Vec<u8> {
|
||||||
|
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!([]);
|
||||||
|
flysim::store::encode(&checkpoint.agent, &checkpoint.runtime).expect("encodes")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||||
|
async fn fafb_reward_segments() {
|
||||||
|
let Some(rom_path) = rom_path() else { return };
|
||||||
|
let Some(dataset) = fafb() else { return };
|
||||||
|
let rom = std::fs::read(&rom_path).expect("the cartridge");
|
||||||
|
let segments: Vec<(String, PathBuf)> = match std::env::var("FLY_TASK01_SEGMENTS") {
|
||||||
|
Ok(list) => list
|
||||||
|
.split(',')
|
||||||
|
.filter_map(|item| {
|
||||||
|
item.split_once('=')
|
||||||
|
.map(|(n, p)| (n.to_owned(), PathBuf::from(p)))
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
Err(_) => [
|
||||||
|
"FLY_DOOR_CHECKPOINT",
|
||||||
|
"FLY_CATCH_CHECKPOINT",
|
||||||
|
"FLY_ENGAGE_CHECKPOINT",
|
||||||
|
// The live fly's largest task ledgers (42 and 46 KB, TASK-01 review B1).
|
||||||
|
"FLY_ROW64_CHECKPOINT",
|
||||||
|
"FLY_ROW65_YARD_CHECKPOINT",
|
||||||
|
]
|
||||||
|
.iter()
|
||||||
|
.filter_map(|var| std::env::var_os(var).map(|p| ((*var).to_owned(), PathBuf::from(p))))
|
||||||
|
.collect(),
|
||||||
|
};
|
||||||
|
let frames = env_usize("FLY_TASK01_FRAMES", 1200);
|
||||||
|
let data = Arc::new(load_brain_dataset_from_dir(&dataset).expect("the dataset"));
|
||||||
|
let arms: Vec<String> = std::env::var("FLY_TASK01_ARMS")
|
||||||
|
.map(|v| v.split(',').map(str::to_owned).collect())
|
||||||
|
.unwrap_or_else(|_| vec!["brain".into(), "driver".into()]);
|
||||||
|
for (segment, path) in segments {
|
||||||
|
for arm in &arms {
|
||||||
|
let name = format!("{segment} {arm}");
|
||||||
|
let original = std::fs::read(&path).expect("the checkpoint");
|
||||||
|
let bytes = if arm == "brain" {
|
||||||
|
reward_bearing(&original)
|
||||||
|
} else {
|
||||||
|
original
|
||||||
|
};
|
||||||
|
let inputs = Inputs {
|
||||||
|
sugar: vec![(10, 400.0), (frames / 2, 250.0)],
|
||||||
|
driver: arm == "driver",
|
||||||
|
};
|
||||||
|
let dir = tempfile::tempdir().expect("tmp");
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
let start = Start::Checkpoint(bytes);
|
||||||
|
let legacy = run_legacy(
|
||||||
|
&rom,
|
||||||
|
&data,
|
||||||
|
&start,
|
||||||
|
MacroMode::Macros,
|
||||||
|
frames,
|
||||||
|
&inputs,
|
||||||
|
&dir.path().join("trace.jsonl"),
|
||||||
|
);
|
||||||
|
eprintln!(
|
||||||
|
"legacy loop {name}: {frames} frames in {:?}",
|
||||||
|
started.elapsed()
|
||||||
|
);
|
||||||
|
for mode in modes() {
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
let session = run_session(
|
||||||
|
mode,
|
||||||
|
&rom_path,
|
||||||
|
&dataset,
|
||||||
|
LegacyProfileKind::Production,
|
||||||
|
MacroMode::Macros,
|
||||||
|
&start,
|
||||||
|
frames,
|
||||||
|
&inputs,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let agreement =
|
||||||
|
trace::compare(&legacy.behaviours, &session.behaviours, &session.bounds)
|
||||||
|
.unwrap_or_else(|e| panic!("{name}, {}: {e}", mode.label()));
|
||||||
|
compare_ledgers(&legacy.ledgers, &session.ledgers);
|
||||||
|
report(
|
||||||
|
&format!("segment {name}, {}", mode.label()),
|
||||||
|
&agreement,
|
||||||
|
started.elapsed(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
265
services/flysim/crates/fly-legacy-session/tests/speed.rs
Normal file
265
services/flysim/crates/fly-legacy-session/tests/speed.rs
Normal file
|
|
@ -0,0 +1,265 @@
|
||||||
|
//! TASK-01 review N5: the session runtime's cost per frame against the legacy loop's, on the same
|
||||||
|
//! box, from the same checkpoint, in the service configuration (no trace, no step details).
|
||||||
|
//!
|
||||||
|
//! `FLY_TASK01_BENCH=1` (plus rom-env and `data/fafb-v783`): the legacy loop (`LegacyFrame`, the
|
||||||
|
//! service's frame, trace off) and the session (agent, world and task under the coordinator,
|
||||||
|
//! details off) each run `FLY_TASK01_BENCH_FRAMES` unpaced frames after a warm-up, with
|
||||||
|
//! `FLY_TASK01_BENCH_THREADS` sweep threads (the release container runs 3). Reported: ms per frame,
|
||||||
|
//! the realtime factor at 1x (one frame is 16.74 ms of game time), and the session's per-method
|
||||||
|
//! latencies from the coordinator's metrics. Then the session runs paced at 1x for the same
|
||||||
|
//! number of frames and reports the realtime factor it held.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
use fly_legacy_session::composition::{LegacyConfig, LegacySession, channels_and_hold};
|
||||||
|
use fly_session::ExecutionMode;
|
||||||
|
use fly_session::legacy_agent::LegacyProfileKind;
|
||||||
|
use fly_session::legacy_parity;
|
||||||
|
use fly_session::types::id;
|
||||||
|
use flybrain_core::agent::{AgentConfig, NeuralAgent};
|
||||||
|
use flybrain_core::dataset::load_brain_dataset_from_dir;
|
||||||
|
use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros;
|
||||||
|
use flybrain_core::lif::SweepPlan;
|
||||||
|
use flybrain_gb::GameAdapter;
|
||||||
|
use flybrain_gb::pokemon_red::PokemonRedReward;
|
||||||
|
use flybrain_gb::ratchet::Ratchet;
|
||||||
|
use flybrain_gb::{AdapterLedger, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator};
|
||||||
|
use flysim::config::Config;
|
||||||
|
use flysim::frame::{LegacyFrame, Parts};
|
||||||
|
use flysim::macros::macro_layer;
|
||||||
|
use flysim::snapshot::MacroMode;
|
||||||
|
|
||||||
|
/// The legacy frame's phases, timed through the one hook the stream itself uses.
|
||||||
|
struct Phases {
|
||||||
|
last: Instant,
|
||||||
|
sums: std::collections::BTreeMap<&'static str, f64>,
|
||||||
|
on: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl flysim::frame::FrameObserver for Phases {
|
||||||
|
fn after(&mut self, phase: flysim::frame::FramePhase, _agent: &mut NeuralAgent) {
|
||||||
|
let now = Instant::now();
|
||||||
|
if self.on {
|
||||||
|
let name = match phase {
|
||||||
|
flysim::frame::FramePhase::Ticked => "legacy.ticks",
|
||||||
|
flysim::frame::FramePhase::Executed => "legacy.decode+execute",
|
||||||
|
flysim::frame::FramePhase::Emulated => "legacy.frame",
|
||||||
|
flysim::frame::FramePhase::Advanced => "legacy.take_frame",
|
||||||
|
flysim::frame::FramePhase::Committed => "legacy.evaluate+commit",
|
||||||
|
};
|
||||||
|
*self.sums.entry(name).or_default() += (now - self.last).as_secs_f64() * 1000.0;
|
||||||
|
}
|
||||||
|
self.last = now;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const FRAME_MS: f64 = 1000.0 * 70_224.0 / 4_194_304.0;
|
||||||
|
|
||||||
|
fn env_usize(name: &str, default: usize) -> usize {
|
||||||
|
std::env::var(name)
|
||||||
|
.ok()
|
||||||
|
.and_then(|v| v.parse().ok())
|
||||||
|
.unwrap_or(default)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||||
|
async fn session_against_legacy_per_frame() {
|
||||||
|
if std::env::var_os("FLY_TASK01_BENCH").is_none() {
|
||||||
|
eprintln!("skipping: FLY_TASK01_BENCH is not set");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let (Some(rom_path), Some(dataset), Some(checkpoint_path)) = (
|
||||||
|
std::env::var_os("FLY_ROM").map(std::path::PathBuf::from),
|
||||||
|
legacy_parity::fafb_dir(),
|
||||||
|
std::env::var_os("FLY_DOOR_CHECKPOINT").map(std::path::PathBuf::from),
|
||||||
|
) else {
|
||||||
|
eprintln!("skipping: FLY_ROM, data/fafb-v783 or FLY_DOOR_CHECKPOINT missing");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let frames = env_usize("FLY_TASK01_BENCH_FRAMES", 1200);
|
||||||
|
let warmup = env_usize("FLY_TASK01_BENCH_WARMUP", 120);
|
||||||
|
let threads = env_usize("FLY_TASK01_BENCH_THREADS", 3);
|
||||||
|
let rom = std::fs::read(&rom_path).unwrap();
|
||||||
|
let bytes = std::fs::read(&checkpoint_path).unwrap();
|
||||||
|
let checkpoint = flysim::store::decode(&bytes).unwrap();
|
||||||
|
|
||||||
|
// ---- The legacy loop: the service's frame, trace off.
|
||||||
|
let data = Arc::new(load_brain_dataset_from_dir(&dataset).unwrap());
|
||||||
|
let mut emulator = Emulator::new(&rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES).unwrap();
|
||||||
|
let mut adapter = PokemonRedReward::new();
|
||||||
|
let mut ratchet = Ratchet::with_policy(adapter.recovery_policy());
|
||||||
|
let mut config = Config::default();
|
||||||
|
config.loop_.game = "pokemon-red".to_owned();
|
||||||
|
config.macros.mode = MacroMode::Macros;
|
||||||
|
let (channels, hold_ms) = channels_and_hold(MacroMode::Macros);
|
||||||
|
let channels: Vec<&str> = channels.iter().map(String::as_str).collect();
|
||||||
|
let mut agent_config = AgentConfig::with_decoder(gameboy_decoder_config_with_macros(&channels));
|
||||||
|
agent_config.warmup_ms = config.loop_.warmup_ms;
|
||||||
|
let mut agent = NeuralAgent::new(Arc::clone(&data), agent_config).unwrap();
|
||||||
|
if threads > 1 {
|
||||||
|
agent.set_sweep_plan(SweepPlan::with_threads(threads).unwrap());
|
||||||
|
}
|
||||||
|
let mut frame = LegacyFrame::new();
|
||||||
|
frame
|
||||||
|
.restore(
|
||||||
|
&mut Parts {
|
||||||
|
agent: &mut agent,
|
||||||
|
emulator: &mut emulator,
|
||||||
|
adapter: &mut adapter,
|
||||||
|
ratchet: &mut ratchet,
|
||||||
|
macros: None,
|
||||||
|
},
|
||||||
|
&checkpoint,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let mut macros = macro_layer(&config, hold_ms, agent.network.rng_state() as u32);
|
||||||
|
if let Some(layer) = macros.as_mut() {
|
||||||
|
let _ = layer.observe(&mut emulator, &AdapterLedger(&adapter), agent.network.ms);
|
||||||
|
}
|
||||||
|
let mut legacy_ms = 0.0;
|
||||||
|
let mut phases = Phases {
|
||||||
|
last: Instant::now(),
|
||||||
|
sums: Default::default(),
|
||||||
|
on: false,
|
||||||
|
};
|
||||||
|
let mut boundary_ms = 0.0;
|
||||||
|
for n in 0..warmup + frames {
|
||||||
|
let started = Instant::now();
|
||||||
|
phases.on = n >= warmup;
|
||||||
|
phases.last = started;
|
||||||
|
let mut parts = Parts {
|
||||||
|
agent: &mut agent,
|
||||||
|
emulator: &mut emulator,
|
||||||
|
adapter: &mut adapter,
|
||||||
|
ratchet: &mut ratchet,
|
||||||
|
macros: macros.as_mut(),
|
||||||
|
};
|
||||||
|
let transition = frame.transition(&mut parts, &mut phases).unwrap();
|
||||||
|
let at = Instant::now();
|
||||||
|
frame
|
||||||
|
.boundary(&mut parts, &transition.evaluated.progress, transition.ms)
|
||||||
|
.unwrap();
|
||||||
|
if n >= warmup {
|
||||||
|
boundary_ms += at.elapsed().as_secs_f64() * 1000.0;
|
||||||
|
}
|
||||||
|
if n >= warmup {
|
||||||
|
legacy_ms += started.elapsed().as_secs_f64() * 1000.0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// What a legacy checkpoint costs the loop: the agent's export (the writer thread encodes).
|
||||||
|
let at = Instant::now();
|
||||||
|
for _ in 0..10 {
|
||||||
|
std::hint::black_box(agent.export_state());
|
||||||
|
}
|
||||||
|
let export_ms = at.elapsed().as_secs_f64() * 100.0;
|
||||||
|
drop(agent);
|
||||||
|
let legacy_per = legacy_ms / frames as f64;
|
||||||
|
for (name, sum) in &phases.sums {
|
||||||
|
eprintln!(
|
||||||
|
" legacy {name:<24} mean {:>8.0} us",
|
||||||
|
sum * 1000.0 / frames as f64
|
||||||
|
);
|
||||||
|
}
|
||||||
|
eprintln!(
|
||||||
|
" legacy boundary mean {:>8.0} us",
|
||||||
|
boundary_ms * 1000.0 / frames as f64
|
||||||
|
);
|
||||||
|
eprintln!(
|
||||||
|
" legacy agent.export_state mean {:>8.0} us (per checkpoint)",
|
||||||
|
export_ms * 1000.0
|
||||||
|
);
|
||||||
|
eprintln!(
|
||||||
|
"legacy loop: {legacy_per:.2} ms/frame over {frames} frames ({threads} threads), realtime factor at 1x {:.2}",
|
||||||
|
(FRAME_MS / legacy_per).min(1.0)
|
||||||
|
);
|
||||||
|
|
||||||
|
// ---- The session, unpaced then paced, in each mode.
|
||||||
|
for mode in [ExecutionMode::InProcess, ExecutionMode::Process] {
|
||||||
|
for paced in [false, true] {
|
||||||
|
let root = tempfile::tempdir().unwrap();
|
||||||
|
let mut session = LegacySession::start(
|
||||||
|
root.path(),
|
||||||
|
LegacyConfig {
|
||||||
|
mode,
|
||||||
|
rom_path: rom_path.clone(),
|
||||||
|
dataset_dir: dataset.clone(),
|
||||||
|
profile: LegacyProfileKind::Production,
|
||||||
|
macro_mode: MacroMode::Macros,
|
||||||
|
agent_id: id("fly"),
|
||||||
|
agent_threads: threads.max(1),
|
||||||
|
record: false,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
session.bootstrap().await.unwrap();
|
||||||
|
session.import_flysim01(&bytes, &id("e2")).await.unwrap();
|
||||||
|
if !paced {
|
||||||
|
session.coordinator.disable_pacing();
|
||||||
|
}
|
||||||
|
for _ in 0..warmup {
|
||||||
|
session.step().await.unwrap();
|
||||||
|
}
|
||||||
|
session.coordinator.metrics.clear();
|
||||||
|
let _ = fly_session::profile::report();
|
||||||
|
let started = Instant::now();
|
||||||
|
for _ in 0..frames {
|
||||||
|
session.step().await.unwrap();
|
||||||
|
}
|
||||||
|
let per = started.elapsed().as_secs_f64() * 1000.0 / frames as f64;
|
||||||
|
if !paced {
|
||||||
|
// What a save costs the loop: the participants' State.Capture at the boundary.
|
||||||
|
let root = tempfile::tempdir().unwrap();
|
||||||
|
session
|
||||||
|
.attach_store(&fly_legacy_session::composition::StoreConfig {
|
||||||
|
hot_dir: root.path().join("hot"),
|
||||||
|
durable_dir: root.path().join("durable"),
|
||||||
|
keep_generations: 2,
|
||||||
|
hot_seconds: 1e9,
|
||||||
|
checkpoint_seconds: 1e9,
|
||||||
|
speed: 1.0,
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
let at = Instant::now();
|
||||||
|
for _ in 0..5 {
|
||||||
|
let ticket = session
|
||||||
|
.queue_save(fly_session::legacy_checkpoint::SaveKind::Hot)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
drop(ticket);
|
||||||
|
}
|
||||||
|
eprintln!(
|
||||||
|
" session save (capture on the loop) mean {:>8.0} us",
|
||||||
|
at.elapsed().as_secs_f64() * 1e6 / 5.0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let factor = FRAME_MS / per;
|
||||||
|
eprintln!(
|
||||||
|
"session {} {}: {per:.2} ms/frame, realtime factor {:.2} ({:.2}x the legacy loop's cost)",
|
||||||
|
mode.label(),
|
||||||
|
if paced { "paced at 1x" } else { "unpaced" },
|
||||||
|
if paced { factor } else { factor.min(1.0) },
|
||||||
|
per / legacy_per
|
||||||
|
);
|
||||||
|
if !paced {
|
||||||
|
for (name, count, mean) in fly_session::profile::report() {
|
||||||
|
eprintln!(
|
||||||
|
" span {name:<22} mean {:>8.0} us n {count}",
|
||||||
|
mean.as_secs_f64() * 1e6
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for name in session.coordinator.metrics.names() {
|
||||||
|
let p = session.coordinator.metrics.percentiles(&name).unwrap();
|
||||||
|
eprintln!(
|
||||||
|
" {name:<24} p50 {:>8.0} us p95 {:>8.0} us n {}",
|
||||||
|
p.p50_us(),
|
||||||
|
p.p95_us(),
|
||||||
|
session.coordinator.metrics.count(&name)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
session.stop().await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
207
services/flysim/crates/fly-legacy-session/tests/speed_ab.rs
Normal file
207
services/flysim/crates/fly-legacy-session/tests/speed_ab.rs
Normal file
|
|
@ -0,0 +1,207 @@
|
||||||
|
//! TASK-01 review N5: the session runtime's cost per frame against the legacy loop's, measured
|
||||||
|
//! A/B-interleaved on one box so both see the same load: chunks of `FLY_TASK01_AB_CHUNK` frames
|
||||||
|
//! of the legacy loop (`LegacyFrame`, the service's frame, trace off) alternate with chunks of the
|
||||||
|
//! session (agent, world and task under the coordinator, service configuration: no details,
|
||||||
|
//! bounded history, snapshots at 30 Hz), both from the same checkpoint with the same sweep threads.
|
||||||
|
//! A shared box's load then shifts both arms alike, and the ratio is the comparison.
|
||||||
|
//!
|
||||||
|
//! `FLY_TASK01_BENCH=1` plus rom-env and `data/fafb-v783`. Reported per execution mode: mean
|
||||||
|
//! ms/frame of each arm, the ratio, the fps each sustains unpaced, and the headroom at 1x (one
|
||||||
|
//! Game Boy frame is 16.74 ms).
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
use fly_legacy_session::composition::{LegacyConfig, LegacySession, channels_and_hold};
|
||||||
|
use fly_session::ExecutionMode;
|
||||||
|
use fly_session::legacy_agent::LegacyProfileKind;
|
||||||
|
use fly_session::legacy_parity;
|
||||||
|
use fly_session::types::id;
|
||||||
|
use flybrain_core::agent::{AgentConfig, NeuralAgent};
|
||||||
|
use flybrain_core::dataset::load_brain_dataset_from_dir;
|
||||||
|
use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros;
|
||||||
|
use flybrain_core::lif::SweepPlan;
|
||||||
|
use flybrain_gb::GameAdapter;
|
||||||
|
use flybrain_gb::pokemon_red::PokemonRedReward;
|
||||||
|
use flybrain_gb::ratchet::Ratchet;
|
||||||
|
use flybrain_gb::{AdapterLedger, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator};
|
||||||
|
use flysim::config::Config;
|
||||||
|
use flysim::frame::{LegacyFrame, Parts};
|
||||||
|
use flysim::macros::{MacroLayer, macro_layer};
|
||||||
|
use flysim::snapshot::MacroMode;
|
||||||
|
|
||||||
|
const FRAME_MS: f64 = 1000.0 * 70_224.0 / 4_194_304.0;
|
||||||
|
|
||||||
|
fn env_usize(name: &str, default: usize) -> usize {
|
||||||
|
std::env::var(name)
|
||||||
|
.ok()
|
||||||
|
.and_then(|v| v.parse().ok())
|
||||||
|
.unwrap_or(default)
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Legacy {
|
||||||
|
emulator: Emulator,
|
||||||
|
adapter: PokemonRedReward,
|
||||||
|
ratchet: Ratchet,
|
||||||
|
agent: NeuralAgent,
|
||||||
|
frame: LegacyFrame,
|
||||||
|
macros: Option<MacroLayer>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Legacy {
|
||||||
|
fn new(
|
||||||
|
rom: &[u8],
|
||||||
|
dataset: &std::path::Path,
|
||||||
|
checkpoint: &flysim::store::Checkpoint,
|
||||||
|
threads: usize,
|
||||||
|
) -> Legacy {
|
||||||
|
let data = Arc::new(load_brain_dataset_from_dir(dataset).unwrap());
|
||||||
|
let mut emulator =
|
||||||
|
Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES).unwrap();
|
||||||
|
let mut adapter = PokemonRedReward::new();
|
||||||
|
let mut ratchet = Ratchet::with_policy(adapter.recovery_policy());
|
||||||
|
let mut config = Config::default();
|
||||||
|
config.loop_.game = "pokemon-red".to_owned();
|
||||||
|
config.macros.mode = MacroMode::Macros;
|
||||||
|
let (channels, hold_ms) = channels_and_hold(MacroMode::Macros);
|
||||||
|
let channels: Vec<&str> = channels.iter().map(String::as_str).collect();
|
||||||
|
let mut agent_config =
|
||||||
|
AgentConfig::with_decoder(gameboy_decoder_config_with_macros(&channels));
|
||||||
|
agent_config.warmup_ms = config.loop_.warmup_ms;
|
||||||
|
let mut agent = NeuralAgent::new(data, agent_config).unwrap();
|
||||||
|
if threads > 1 {
|
||||||
|
agent.set_sweep_plan(SweepPlan::with_threads(threads).unwrap());
|
||||||
|
}
|
||||||
|
let mut frame = LegacyFrame::new();
|
||||||
|
frame
|
||||||
|
.restore(
|
||||||
|
&mut Parts {
|
||||||
|
agent: &mut agent,
|
||||||
|
emulator: &mut emulator,
|
||||||
|
adapter: &mut adapter,
|
||||||
|
ratchet: &mut ratchet,
|
||||||
|
macros: None,
|
||||||
|
},
|
||||||
|
checkpoint,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let mut macros = macro_layer(&config, hold_ms, agent.network.rng_state() as u32);
|
||||||
|
if let Some(layer) = macros.as_mut() {
|
||||||
|
let _ = layer.observe(&mut emulator, &AdapterLedger(&adapter), agent.network.ms);
|
||||||
|
}
|
||||||
|
Legacy {
|
||||||
|
emulator,
|
||||||
|
adapter,
|
||||||
|
ratchet,
|
||||||
|
agent,
|
||||||
|
frame,
|
||||||
|
macros,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn step(&mut self) {
|
||||||
|
let mut parts = Parts {
|
||||||
|
agent: &mut self.agent,
|
||||||
|
emulator: &mut self.emulator,
|
||||||
|
adapter: &mut self.adapter,
|
||||||
|
ratchet: &mut self.ratchet,
|
||||||
|
macros: self.macros.as_mut(),
|
||||||
|
};
|
||||||
|
let transition = self.frame.transition(&mut parts, &mut ()).unwrap();
|
||||||
|
self.frame
|
||||||
|
.boundary(&mut parts, &transition.evaluated.progress, transition.ms)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||||
|
async fn session_against_legacy_interleaved() {
|
||||||
|
if std::env::var_os("FLY_TASK01_BENCH").is_none() {
|
||||||
|
eprintln!("skipping: FLY_TASK01_BENCH is not set");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let (Some(rom_path), Some(dataset), Some(checkpoint_path)) = (
|
||||||
|
std::env::var_os("FLY_ROM").map(std::path::PathBuf::from),
|
||||||
|
legacy_parity::fafb_dir(),
|
||||||
|
std::env::var_os("FLY_DOOR_CHECKPOINT").map(std::path::PathBuf::from),
|
||||||
|
) else {
|
||||||
|
eprintln!("skipping: FLY_ROM, data/fafb-v783 or FLY_DOOR_CHECKPOINT missing");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let frames = env_usize("FLY_TASK01_BENCH_FRAMES", 1800);
|
||||||
|
let chunk = env_usize("FLY_TASK01_AB_CHUNK", 60);
|
||||||
|
let threads = env_usize("FLY_TASK01_BENCH_THREADS", 3);
|
||||||
|
let rom = std::fs::read(&rom_path).unwrap();
|
||||||
|
let bytes = std::fs::read(&checkpoint_path).unwrap();
|
||||||
|
let checkpoint = flysim::store::decode(&bytes).unwrap();
|
||||||
|
for mode in [ExecutionMode::InProcess, ExecutionMode::Process] {
|
||||||
|
let mut legacy = Legacy::new(&rom, &dataset, &checkpoint, threads);
|
||||||
|
let root = tempfile::tempdir().unwrap();
|
||||||
|
let mut session = LegacySession::start(
|
||||||
|
root.path(),
|
||||||
|
LegacyConfig {
|
||||||
|
mode,
|
||||||
|
rom_path: rom_path.clone(),
|
||||||
|
dataset_dir: dataset.clone(),
|
||||||
|
profile: LegacyProfileKind::Production,
|
||||||
|
macro_mode: MacroMode::Macros,
|
||||||
|
agent_id: id("fly"),
|
||||||
|
agent_threads: threads.max(1),
|
||||||
|
record: false,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
session.bootstrap().await.unwrap();
|
||||||
|
session.import_flysim01(&bytes, &id("e2")).await.unwrap();
|
||||||
|
session.coordinator.disable_pacing();
|
||||||
|
// Warm both.
|
||||||
|
for _ in 0..chunk {
|
||||||
|
legacy.step();
|
||||||
|
session.step().await.unwrap();
|
||||||
|
}
|
||||||
|
session.coordinator.metrics.clear();
|
||||||
|
let _ = fly_session::profile::report();
|
||||||
|
let (mut legacy_ms, mut session_ms) = (0.0, 0.0);
|
||||||
|
let mut done = 0;
|
||||||
|
while done < frames {
|
||||||
|
let at = Instant::now();
|
||||||
|
for _ in 0..chunk {
|
||||||
|
legacy.step();
|
||||||
|
}
|
||||||
|
legacy_ms += at.elapsed().as_secs_f64() * 1000.0;
|
||||||
|
let at = Instant::now();
|
||||||
|
for _ in 0..chunk {
|
||||||
|
session.step().await.unwrap();
|
||||||
|
}
|
||||||
|
session_ms += at.elapsed().as_secs_f64() * 1000.0;
|
||||||
|
done += chunk;
|
||||||
|
}
|
||||||
|
let (l, s) = (legacy_ms / done as f64, session_ms / done as f64);
|
||||||
|
eprintln!(
|
||||||
|
"{}: legacy {l:.2} ms/frame ({:.0} fps), session {s:.2} ms/frame ({:.0} fps); session/legacy {:.2}; headroom at 1x legacy {:.2} ms, session {:.2} ms ({done} frames each, {chunk}-frame chunks, {threads} threads)",
|
||||||
|
mode.label(),
|
||||||
|
1000.0 / l,
|
||||||
|
1000.0 / s,
|
||||||
|
s / l,
|
||||||
|
FRAME_MS - l,
|
||||||
|
FRAME_MS - s
|
||||||
|
);
|
||||||
|
for (name, count, mean) in fly_session::profile::report() {
|
||||||
|
eprintln!(
|
||||||
|
" span {name:<26} mean {:>8.0} us n {count}",
|
||||||
|
mean.as_secs_f64() * 1e6
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for name in session.coordinator.metrics.names() {
|
||||||
|
let p = session.coordinator.metrics.percentiles(&name).unwrap();
|
||||||
|
eprintln!(
|
||||||
|
" {name:<24} p50 {:>8.0} us p95 {:>8.0} us n {}",
|
||||||
|
p.p50_us(),
|
||||||
|
p.p95_us(),
|
||||||
|
session.coordinator.metrics.count(&name)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
session.stop().await;
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -312,6 +312,43 @@ pub fn encode_payload(
|
||||||
encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks).map_err(|e| e.to_string())
|
encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks).map_err(|e| e.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A capture's inputs, copied at the boundary so the encoding can run off the endpoint's lock.
|
||||||
|
struct CaptureSnapshot {
|
||||||
|
state: AgentState,
|
||||||
|
agent_id: Id,
|
||||||
|
checkpoint_id: Id,
|
||||||
|
scope: Scope,
|
||||||
|
committed_step: u64,
|
||||||
|
profile: AssetRef,
|
||||||
|
seed: i32,
|
||||||
|
reinforcements: u64,
|
||||||
|
macro_channels: Vec<String>,
|
||||||
|
accumulator: TickAccumulator,
|
||||||
|
context: TypedValue,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CaptureSnapshot {
|
||||||
|
fn encode(&self) -> DomainResult<Vec<u8>> {
|
||||||
|
encode_payload(
|
||||||
|
&self.state,
|
||||||
|
&PayloadIdentity {
|
||||||
|
agent_id: &self.agent_id,
|
||||||
|
checkpoint_id: &self.checkpoint_id,
|
||||||
|
source_scope: &self.scope,
|
||||||
|
committed_step: self.committed_step,
|
||||||
|
profile: &self.profile,
|
||||||
|
seed: self.seed,
|
||||||
|
reinforcements: self.reinforcements,
|
||||||
|
macro_channels: &self.macro_channels,
|
||||||
|
},
|
||||||
|
&self.accumulator,
|
||||||
|
&self.context,
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The reinforcement calls a `FLYAGT01` capture payload records (`learning.updates`).
|
/// The reinforcement calls a `FLYAGT01` capture payload records (`learning.updates`).
|
||||||
pub fn decode_payload_reinforcements(bytes: &[u8]) -> Result<u64, String> {
|
pub fn decode_payload_reinforcements(bytes: &[u8]) -> Result<u64, String> {
|
||||||
let parts = decode_envelope(bytes, PAYLOAD_MAGIC)
|
let parts = decode_envelope(bytes, PAYLOAD_MAGIC)
|
||||||
|
|
@ -1005,7 +1042,9 @@ impl LegacyAgentWorker {
|
||||||
let brain_ticks = accumulator.brain_ticks();
|
let brain_ticks = accumulator.brain_ticks();
|
||||||
let remainder = accumulator.remainder();
|
let remainder = accumulator.remainder();
|
||||||
self.transition_start_ms = agent.network.ms;
|
self.transition_start_ms = agent.network.ms;
|
||||||
|
let ticks_span = crate::profile::span("agent.ticks");
|
||||||
agent.network.step(ticks);
|
agent.network.step(ticks);
|
||||||
|
drop(ticks_span);
|
||||||
if agent.network.ms != brain_ticks as f64 {
|
if agent.network.ms != brain_ticks as f64 {
|
||||||
return Err(applied(
|
return Err(applied(
|
||||||
ErrorCode::Internal,
|
ErrorCode::Internal,
|
||||||
|
|
@ -1110,7 +1149,9 @@ impl LegacyAgentWorker {
|
||||||
}
|
}
|
||||||
let context = self.read_context(¶ms.next_decision_context)?;
|
let context = self.read_context(¶ms.next_decision_context)?;
|
||||||
// The complete request and its owned artifact are validated before anything applies.
|
// The complete request and its owned artifact are validated before anything applies.
|
||||||
|
let read_span = crate::profile::span("agent.read_lcd");
|
||||||
let frame = self.read_lcd(ctx, ¶ms.next_input).await?;
|
let frame = self.read_lcd(ctx, ¶ms.next_input).await?;
|
||||||
|
drop(read_span);
|
||||||
|
|
||||||
self.status.set_state(WorkerState::Committing);
|
self.status.set_state(WorkerState::Committing);
|
||||||
let agent = self.agent.as_mut().expect("initialized");
|
let agent = self.agent.as_mut().expect("initialized");
|
||||||
|
|
@ -1139,7 +1180,9 @@ impl LegacyAgentWorker {
|
||||||
self.transient.location = Some(location);
|
self.transient.location = Some(location);
|
||||||
self.transient.blocked_since_ms = ms;
|
self.transient.blocked_since_ms = ms;
|
||||||
}
|
}
|
||||||
|
let spikes_span = crate::profile::span("agent.spikes");
|
||||||
let spikes = spike_bitset(&agent.network.last_spike_ms, self.transition_start_ms, ms);
|
let spikes = spike_bitset(&agent.network.last_spike_ms, self.transition_start_ms, ms);
|
||||||
|
drop(spikes_span);
|
||||||
// 4. Retain the next context and acknowledge k+1.
|
// 4. Retain the next context and acknowledge k+1.
|
||||||
let digest = context.digest.clone();
|
let digest = context.digest.clone();
|
||||||
self.context = Some(context);
|
self.context = Some(context);
|
||||||
|
|
@ -1152,6 +1195,7 @@ impl LegacyAgentWorker {
|
||||||
decision_context_digest: digest,
|
decision_context_digest: digest,
|
||||||
telemetry: self.telemetry(),
|
telemetry: self.telemetry(),
|
||||||
};
|
};
|
||||||
|
let _seal_span = crate::profile::span("agent.seal_spikes");
|
||||||
let artifact = crate::media::seal_copy(ctx.client, SPIKES_CONTENT_TYPE.to_owned(), &spikes)
|
let artifact = crate::media::seal_copy(ctx.client, SPIKES_CONTENT_TYPE.to_owned(), &spikes)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| applied(e.code, e.message))?;
|
.map_err(|e| applied(e.code, e.message))?;
|
||||||
|
|
@ -1273,7 +1317,8 @@ impl LegacyAgentWorker {
|
||||||
/// The capture payload: `agent_to_chunks` in a checkpoint envelope, plus a `session`
|
/// The capture payload: `agent_to_chunks` in a checkpoint envelope, plus a `session`
|
||||||
/// manifest member with the accumulator, the context and the identities. The readout
|
/// manifest member with the accumulator, the context and the identities. The readout
|
||||||
/// transient is not in it (`legacy-transient-reset`).
|
/// transient is not in it (`legacy-transient-reset`).
|
||||||
fn payload(&self, checkpoint_id: &Id, scope: &Scope, k: u64) -> DomainResult<Vec<u8>> {
|
/// Everything a capture payload is encoded from, copied out of the live agent.
|
||||||
|
fn snapshot(&self, checkpoint_id: &Id, scope: &Scope, k: u64) -> DomainResult<CaptureSnapshot> {
|
||||||
let agent = self.agent.as_ref().expect("initialized");
|
let agent = self.agent.as_ref().expect("initialized");
|
||||||
let accumulator = self.accumulator.as_ref().expect("initialized");
|
let accumulator = self.accumulator.as_ref().expect("initialized");
|
||||||
let context = self.context.as_ref().expect("initialized");
|
let context = self.context.as_ref().expect("initialized");
|
||||||
|
|
@ -1281,23 +1326,19 @@ impl LegacyAgentWorker {
|
||||||
// The session owns the frame remainder, as the legacy loop does (`Sim::checkpoint`).
|
// The session owns the frame remainder, as the legacy loop does (`Sim::checkpoint`).
|
||||||
state.remainder = rational_remainder_to_legacy(&accumulator.remainder())
|
state.remainder = rational_remainder_to_legacy(&accumulator.remainder())
|
||||||
.map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None))?;
|
.map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None))?;
|
||||||
encode_payload(
|
Ok(CaptureSnapshot {
|
||||||
&state,
|
state,
|
||||||
&PayloadIdentity {
|
agent_id: self.config.agent_id.clone(),
|
||||||
agent_id: &self.config.agent_id,
|
checkpoint_id: checkpoint_id.clone(),
|
||||||
checkpoint_id,
|
scope: scope.clone(),
|
||||||
source_scope: scope,
|
|
||||||
committed_step: k,
|
committed_step: k,
|
||||||
profile: &self.profile.asset,
|
profile: self.profile.asset.clone(),
|
||||||
seed: self.seed,
|
seed: self.seed,
|
||||||
reinforcements: self.reinforcements,
|
reinforcements: self.reinforcements,
|
||||||
macro_channels: &self.config.macro_channels,
|
macro_channels: self.config.macro_channels.clone(),
|
||||||
},
|
accumulator: accumulator.clone(),
|
||||||
accumulator,
|
context: context.typed.clone(),
|
||||||
&context.typed,
|
})
|
||||||
None,
|
|
||||||
)
|
|
||||||
.map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn state_capture(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult<HandlerReply> {
|
async fn state_capture(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult<HandlerReply> {
|
||||||
|
|
@ -1323,36 +1364,50 @@ impl LegacyAgentWorker {
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let params: CaptureParams = ctx.params()?;
|
let params: CaptureParams = ctx.params()?;
|
||||||
let previous = self.status.state();
|
// The boundary's state, taken under the endpoint's lock: a copy, as the legacy loop's
|
||||||
self.status.set_state(WorkerState::Capturing);
|
// `export_state` is. Encoding, digesting and sealing it -- milliseconds on the full
|
||||||
let bytes = self.payload(¶ms.checkpoint_id, &scope, k);
|
// connectome -- run after the lock is released (`HandlerReply::deferred`), so the next
|
||||||
let bytes = match bytes {
|
// Prepare does not wait for them (TASK-01 review N5).
|
||||||
Ok(bytes) => bytes,
|
let snapshot = {
|
||||||
Err(e) => {
|
let _span = crate::profile::span("agent.capture.snapshot");
|
||||||
self.status.set_state(previous);
|
self.snapshot(¶ms.checkpoint_id, &scope, k)?
|
||||||
return Err(e);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
let digest = digest_of_bytes(&bytes);
|
|
||||||
let artifact = crate::state::seal_payload(ctx.client, &bytes, &digest).await;
|
|
||||||
self.status.set_state(previous);
|
|
||||||
let artifact = artifact?;
|
|
||||||
let graph = self.graph.as_ref().expect("initialized");
|
let graph = self.graph.as_ref().expect("initialized");
|
||||||
let result = CaptureResult {
|
let compatibility = compatibility_digest(
|
||||||
checkpoint_id: params.checkpoint_id,
|
|
||||||
boundary: k,
|
|
||||||
compatibility_digest: compatibility_digest(
|
|
||||||
&self.config.agent_id,
|
&self.config.agent_id,
|
||||||
&self.profile.asset,
|
&self.profile.asset,
|
||||||
graph,
|
graph,
|
||||||
self.seed,
|
self.seed,
|
||||||
),
|
);
|
||||||
|
let client = ctx.client.clone();
|
||||||
|
Ok(HandlerReply::deferred(Box::pin(async move {
|
||||||
|
let bytes = tokio::task::spawn_blocking(move || {
|
||||||
|
let _span = crate::profile::span("agent.capture.encode");
|
||||||
|
let bytes = snapshot.encode()?;
|
||||||
|
let digest = {
|
||||||
|
let _span = crate::profile::span("agent.capture.digest");
|
||||||
|
digest_of_bytes(&bytes)
|
||||||
|
};
|
||||||
|
Ok::<_, DomainError>((bytes, digest))
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|e| DomainError::new(ErrorCode::Internal, e.to_string(), MutationCertainty::None))?;
|
||||||
|
let (bytes, digest) = bytes?;
|
||||||
|
let artifact = {
|
||||||
|
let _span = crate::profile::span("agent.capture.seal");
|
||||||
|
crate::state::seal_payload(&client, &bytes, &digest).await?
|
||||||
|
};
|
||||||
|
let result = CaptureResult {
|
||||||
|
checkpoint_id: params.checkpoint_id,
|
||||||
|
boundary: k,
|
||||||
|
compatibility_digest: compatibility,
|
||||||
payload: artifact.reference().clone(),
|
payload: artifact.reference().clone(),
|
||||||
};
|
};
|
||||||
Ok(HandlerReply::with_artifacts(
|
Ok(HandlerReply::with_artifacts(
|
||||||
object(result.to_json()),
|
object(result.to_json()),
|
||||||
vec![(crate::state::PAYLOAD_ATTACHMENT.to_owned(), artifact)],
|
vec![(crate::state::PAYLOAD_ATTACHMENT.to_owned(), artifact)],
|
||||||
))
|
))
|
||||||
|
})))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn state_stage_restore(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult<HandlerReply> {
|
async fn state_stage_restore(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult<HandlerReply> {
|
||||||
|
|
|
||||||
|
|
@ -857,10 +857,33 @@ impl LegacyGameboyEnvironment {
|
||||||
client: &flybus::Client,
|
client: &flybus::Client,
|
||||||
audio: Option<Vec<u8>>,
|
audio: Option<Vec<u8>>,
|
||||||
) -> DomainResult<(WorldObservation, Vec<(String, flybus::Artifact)>)> {
|
) -> DomainResult<(WorldObservation, Vec<(String, flybus::Artifact)>)> {
|
||||||
let frame =
|
let image = {
|
||||||
media::seal_copy(client, FRAME_CONTENT_TYPE.to_owned(), &live.framebuffer).await?;
|
let _span = crate::profile::span("env.image");
|
||||||
let image = memory_image(&mut live.emulator).map_err(backend_failure)?;
|
memory_image(&mut live.emulator).map_err(backend_failure)?
|
||||||
let memory = media::seal_copy(client, MEMORY_CONTENT_TYPE.to_owned(), &image).await?;
|
};
|
||||||
|
if let Some(raw) = &audio
|
||||||
|
&& raw.len() % AUDIO_CHANNELS as usize != 0
|
||||||
|
{
|
||||||
|
return Err(backend_failure("binjgb returned half a stereo frame"));
|
||||||
|
}
|
||||||
|
let audio_f32 = audio.as_deref().map(audio_f32le);
|
||||||
|
// The three artifacts are independent: they are sealed concurrently, so the boundary
|
||||||
|
// waits for the router's round trips once rather than three times.
|
||||||
|
let seal_span = crate::profile::span("env.seal");
|
||||||
|
let (frame, memory, samples) = tokio::join!(
|
||||||
|
media::seal_copy(client, FRAME_CONTENT_TYPE.to_owned(), &live.framebuffer),
|
||||||
|
media::seal_copy(client, MEMORY_CONTENT_TYPE.to_owned(), &image),
|
||||||
|
async {
|
||||||
|
match &audio_f32 {
|
||||||
|
Some(bytes) => media::seal_copy(client, AUDIO_CONTENT_TYPE.to_owned(), bytes)
|
||||||
|
.await
|
||||||
|
.map(Some),
|
||||||
|
None => Ok(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
drop(seal_span);
|
||||||
|
let (frame, memory, samples) = (frame?, memory?, samples?);
|
||||||
let view = ViewRef {
|
let view = ViewRef {
|
||||||
view_id: gameboy::VIEW_ID.to_owned(),
|
view_id: gameboy::VIEW_ID.to_owned(),
|
||||||
produced_step: live.boundary,
|
produced_step: live.boundary,
|
||||||
|
|
@ -876,13 +899,8 @@ impl LegacyGameboyEnvironment {
|
||||||
(MEMORY_ATTACHMENT.to_owned(), memory),
|
(MEMORY_ATTACHMENT.to_owned(), memory),
|
||||||
];
|
];
|
||||||
let mut chunks = Vec::new();
|
let mut chunks = Vec::new();
|
||||||
if let Some(raw) = audio {
|
if let (Some(raw), Some(samples)) = (audio, samples) {
|
||||||
if raw.len() % AUDIO_CHANNELS as usize != 0 {
|
|
||||||
return Err(backend_failure("binjgb returned half a stereo frame"));
|
|
||||||
}
|
|
||||||
let frames = (raw.len() / AUDIO_CHANNELS as usize) as u64;
|
let frames = (raw.len() / AUDIO_CHANNELS as usize) as u64;
|
||||||
let samples =
|
|
||||||
media::seal_copy(client, AUDIO_CONTENT_TYPE.to_owned(), &audio_f32le(&raw)).await?;
|
|
||||||
chunks.push(AudioRef {
|
chunks.push(AudioRef {
|
||||||
stream_id: id(AUDIO_STREAM_ID),
|
stream_id: id(AUDIO_STREAM_ID),
|
||||||
first_sample: live.audio_next_sample,
|
first_sample: live.audio_next_sample,
|
||||||
|
|
@ -1030,6 +1048,7 @@ impl LegacyGameboyEnvironment {
|
||||||
let applied_from = live.boundary;
|
let applied_from = live.boundary;
|
||||||
|
|
||||||
// `LegacyFrame::run` and `take_frame`: the joypad, one frame, the frame it drew, its audio.
|
// `LegacyFrame::run` and `take_frame`: the joypad, one frame, the frame it drew, its audio.
|
||||||
|
let frame_span = crate::profile::span("env.frame");
|
||||||
live.buttons = mask;
|
live.buttons = mask;
|
||||||
live.emulator.set_buttons(mask);
|
live.emulator.set_buttons(mask);
|
||||||
live.emulator
|
live.emulator
|
||||||
|
|
@ -1039,6 +1058,7 @@ impl LegacyGameboyEnvironment {
|
||||||
live.framebuffer
|
live.framebuffer
|
||||||
.copy_from_slice(live.emulator.framebuffer());
|
.copy_from_slice(live.emulator.framebuffer());
|
||||||
let audio = live.emulator.take_audio_u8();
|
let audio = live.emulator.take_audio_u8();
|
||||||
|
drop(frame_span);
|
||||||
live.boundary += 1;
|
live.boundary += 1;
|
||||||
live.world_time = live
|
live.world_time = live
|
||||||
.world_time
|
.world_time
|
||||||
|
|
|
||||||
|
|
@ -38,6 +38,7 @@ pub mod measure;
|
||||||
pub mod media;
|
pub mod media;
|
||||||
pub mod metrics;
|
pub mod metrics;
|
||||||
pub mod phase;
|
pub mod phase;
|
||||||
|
pub mod profile;
|
||||||
pub mod publish;
|
pub mod publish;
|
||||||
pub mod rpc;
|
pub mod rpc;
|
||||||
pub mod state;
|
pub mod state;
|
||||||
|
|
|
||||||
|
|
@ -79,6 +79,16 @@ impl Metrics {
|
||||||
pub fn clear(&mut self) {
|
pub fn clear(&mut self) {
|
||||||
self.samples.clear();
|
self.samples.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Bounds every path to between `keep` and `2 * keep` of its newest samples (trimmed in
|
||||||
|
/// batches, so a long run does not shift the vector every step).
|
||||||
|
pub fn truncate(&mut self, keep: usize) {
|
||||||
|
for values in self.samples.values_mut() {
|
||||||
|
if values.len() > 2 * keep {
|
||||||
|
values.drain(..values.len() - keep);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// This process's peak resident set, in KiB, from its own status file.
|
/// This process's peak resident set, in KiB, from its own status file.
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,8 @@
|
||||||
//! Ready(k) / Paused(k) -> Capturing(k) -> same boundary
|
//! Ready(k) / Paused(k) -> Capturing(k) -> same boundary
|
||||||
//! any unresolved partial failure -> Failed -> Restoring(new epoch) -> Paused(k)
|
//! any unresolved partial failure -> Failed -> Restoring(new epoch) -> Paused(k)
|
||||||
//! terminal episode -> Paused(k) -> Resetting(new epoch) -> Ready(0)
|
//! terminal episode -> Paused(k) -> Resetting(new epoch) -> Ready(0)
|
||||||
|
//! declared rollback: Ready(e, k) -> RollingBack(e', k) -> Ready(e', k)
|
||||||
|
//! checkpoint as the start: Ready(0), no transition taken -> Restoring(k) -> Paused(k)
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! A transition the table does not list is a bug, not a recoverable condition, so it returns
|
//! A transition the table does not list is a bug, not a recoverable condition, so it returns
|
||||||
|
|
@ -34,6 +36,9 @@ pub enum Phase {
|
||||||
Restoring(u64),
|
Restoring(u64),
|
||||||
/// `Resetting(k)`: leaving boundary `k` for a new epoch and episode at step 0.
|
/// `Resetting(k)`: leaving boundary `k` for a new epoch and episode at step 0.
|
||||||
Resetting(u64),
|
Resetting(u64),
|
||||||
|
/// A declared rollback policy running at a committed boundary (`step-v1` section 2
|
||||||
|
/// amendment of 2026-09-23): same boundary, new epoch, no capture.
|
||||||
|
RollingBack(u64),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Phase {
|
impl Phase {
|
||||||
|
|
@ -50,6 +55,7 @@ impl Phase {
|
||||||
Phase::Failed => "Failed".to_owned(),
|
Phase::Failed => "Failed".to_owned(),
|
||||||
Phase::Restoring(k) => format!("Restoring({k})"),
|
Phase::Restoring(k) => format!("Restoring({k})"),
|
||||||
Phase::Resetting(k) => format!("Resetting({k})"),
|
Phase::Resetting(k) => format!("Resetting({k})"),
|
||||||
|
Phase::RollingBack(k) => format!("RollingBack({k})"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -115,6 +121,14 @@ impl PhaseMachine {
|
||||||
(Restoring(k), Paused(j)) => k == j,
|
(Restoring(k), Paused(j)) => k == j,
|
||||||
(Paused(k), Resetting(j)) => k == j,
|
(Paused(k), Resetting(j)) => k == j,
|
||||||
(Resetting(_), Ready(0)) => true,
|
(Resetting(_), Ready(0)) => true,
|
||||||
|
// `step-v1` section 2, amendment of 2026-09-23: `Ready(e, k) -> RollingBack(e', k)
|
||||||
|
// -> Ready(e', k)`. The epoch changes, which is the coordinator's; the boundary
|
||||||
|
// does not.
|
||||||
|
(Ready(k), RollingBack(j)) | (RollingBack(k), Ready(j)) => k == j,
|
||||||
|
// A session that bootstrapped and has taken no transition may install a checkpoint
|
||||||
|
// as its start: the legacy composition's FLYSIM01 import (TASK-01). The install is
|
||||||
|
// the group restore of `state-media-v1` section 6 and ends `Paused(k)` like one.
|
||||||
|
(Ready(0), Restoring(_)) => true,
|
||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -150,6 +164,21 @@ impl PhaseMachine {
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_rollback_keeps_its_boundary_and_an_import_starts_from_an_unstepped_zero() {
|
||||||
|
let mut m = PhaseMachine::new();
|
||||||
|
m.to(Phase::Ready(0)).unwrap();
|
||||||
|
m.to(Phase::Restoring(40)).unwrap();
|
||||||
|
m.to(Phase::Paused(40)).unwrap();
|
||||||
|
m.to(Phase::Ready(40)).unwrap();
|
||||||
|
assert!(m.to(Phase::RollingBack(41)).is_err(), "a rollback keeps the boundary");
|
||||||
|
m.to(Phase::RollingBack(40)).unwrap();
|
||||||
|
assert!(m.to(Phase::Capturing(40)).is_err(), "no capture inside a rollback");
|
||||||
|
assert!(m.to(Phase::Preparing(40)).is_err(), "no Prepare before every reply");
|
||||||
|
m.to(Phase::Ready(40)).unwrap();
|
||||||
|
assert!(m.to(Phase::Restoring(3)).is_err(), "only boundary 0 may take a start");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn the_happy_path_walks_the_section_2_diagram() {
|
fn the_happy_path_walks_the_section_2_diagram() {
|
||||||
let mut m = PhaseMachine::new();
|
let mut m = PhaseMachine::new();
|
||||||
|
|
|
||||||
60
services/flysim/crates/fly-session/src/profile.rs
Normal file
60
services/flysim/crates/fly-session/src/profile.rs
Normal file
|
|
@ -0,0 +1,60 @@
|
||||||
|
//! A switchable per-phase timer for measuring the session runtime (TASK-01 review N5).
|
||||||
|
//!
|
||||||
|
//! Off unless `FLY_SESSION_PROFILE` is set when the process starts; off, a span is one relaxed
|
||||||
|
//! atomic load. On, every span adds its duration to a process-wide table that [`report`] reads.
|
||||||
|
//! In-process execution puts the coordinator and every worker in one table; a worker process
|
||||||
|
//! keeps its own. Not a service metric: a measurement tool.
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
use std::sync::atomic::{AtomicU8, Ordering};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
static STATE: AtomicU8 = AtomicU8::new(0); // 0 unknown, 1 off, 2 on
|
||||||
|
static TABLE: Mutex<BTreeMap<&'static str, (u64, Duration)>> = Mutex::new(BTreeMap::new());
|
||||||
|
|
||||||
|
fn on() -> bool {
|
||||||
|
match STATE.load(Ordering::Relaxed) {
|
||||||
|
1 => false,
|
||||||
|
2 => true,
|
||||||
|
_ => {
|
||||||
|
let enabled = std::env::var_os("FLY_SESSION_PROFILE").is_some();
|
||||||
|
STATE.store(if enabled { 2 } else { 1 }, Ordering::Relaxed);
|
||||||
|
enabled
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Times until dropped.
|
||||||
|
pub struct Span(Option<(&'static str, Instant)>);
|
||||||
|
|
||||||
|
/// Starts timing `name`.
|
||||||
|
pub fn span(name: &'static str) -> Span {
|
||||||
|
Span(on().then(|| (name, Instant::now())))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Span {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Some((name, started)) = self.0.take() {
|
||||||
|
let mut table = TABLE
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
|
let entry = table.entry(name).or_insert((0, Duration::ZERO));
|
||||||
|
entry.0 += 1;
|
||||||
|
entry.1 += started.elapsed();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `(name, count, mean)` for every span recorded, then clears the table.
|
||||||
|
pub fn report() -> Vec<(&'static str, u64, Duration)> {
|
||||||
|
let mut table = TABLE
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
|
let out = table
|
||||||
|
.iter()
|
||||||
|
.map(|(name, (count, total))| (*name, *count, *total / (*count).max(1) as u32))
|
||||||
|
.collect();
|
||||||
|
table.clear();
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
@ -69,8 +69,35 @@ pub async fn call(
|
||||||
request_id: DomainRequestId,
|
request_id: DomainRequestId,
|
||||||
want_artifacts: &[String],
|
want_artifacts: &[String],
|
||||||
) -> Result<DomainReply, DomainError> {
|
) -> Result<DomainReply, DomainError> {
|
||||||
|
send(bus, target, method, scope, params, attachments, request_id, want_artifacts)
|
||||||
|
.await?
|
||||||
|
.finish()
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A domain call that has been sent and not yet answered: the bus has it in order, so a call
|
||||||
|
/// sent after it to the same worker is dispatched after it.
|
||||||
|
pub struct SentCall {
|
||||||
|
method: String,
|
||||||
|
pending: flybus::PendingCall,
|
||||||
|
request_id: DomainRequestId,
|
||||||
|
want_artifacts: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sends one domain call without waiting for its reply ([`SentCall::finish`] waits).
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub async fn send(
|
||||||
|
bus: &flybus::Client,
|
||||||
|
target: &WorkerRef,
|
||||||
|
method: &str,
|
||||||
|
scope: Option<Scope>,
|
||||||
|
params: Map<String, Value>,
|
||||||
|
attachments: &[(&str, &flybus::Artifact)],
|
||||||
|
request_id: DomainRequestId,
|
||||||
|
want_artifacts: &[String],
|
||||||
|
) -> Result<SentCall, DomainError> {
|
||||||
let request = SessionRpcRequest { request_id: request_id.clone(), scope, params: Value::Object(params) };
|
let request = SessionRpcRequest { request_id: request_id.clone(), scope, params: Value::Object(params) };
|
||||||
let mut pending = bus
|
let pending = bus
|
||||||
.call(
|
.call(
|
||||||
&target.service,
|
&target.service,
|
||||||
Some(&target.bus_incarnation),
|
Some(&target.bus_incarnation),
|
||||||
|
|
@ -80,26 +107,49 @@ pub async fn call(
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| bus_error(method, &e))?;
|
.map_err(|e| bus_error(method, &e))?;
|
||||||
let result = pending.result().await.map_err(|e| bus_error(method, &e))?;
|
Ok(SentCall {
|
||||||
|
method: method.to_owned(),
|
||||||
|
pending,
|
||||||
|
request_id,
|
||||||
|
want_artifacts: want_artifacts.to_vec(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SentCall {
|
||||||
|
/// Waits for the terminal reply.
|
||||||
|
pub async fn finish(mut self) -> Result<DomainReply, DomainError> {
|
||||||
|
let method = self.method.as_str();
|
||||||
|
let result = self.pending.result().await.map_err(|e| bus_error(method, &e))?;
|
||||||
let outcome = SessionRpcOutcome::from_json(&Value::Object(result.outcome().clone()))
|
let outcome = SessionRpcOutcome::from_json(&Value::Object(result.outcome().clone()))
|
||||||
.map_err(|e| DomainError::invalid(format!("{method}: {e}")))?;
|
.map_err(|e| DomainError::invalid(format!("{method}: {e}")))?;
|
||||||
let mut artifacts = BTreeMap::new();
|
// An independent explicit hold on each wanted attachment, so the handle outlives this
|
||||||
for name in want_artifacts {
|
// delivery and can be forwarded to several Commit calls and to publication. The holds
|
||||||
if let Ok(artifact) = result.artifact(name) {
|
// are independent router round trips, so they are taken concurrently.
|
||||||
// An independent explicit hold, so the handle outlives this delivery and can be
|
let wanted: Vec<(String, flybus::Artifact)> = self
|
||||||
// forwarded to several Commit calls and to publication.
|
.want_artifacts
|
||||||
|
.iter()
|
||||||
|
.filter_map(|name| result.artifact(name).ok().map(|a| (name.clone(), a)))
|
||||||
|
.collect();
|
||||||
|
let retains: Vec<_> = wanted
|
||||||
|
.into_iter()
|
||||||
|
.map(|(name, artifact)| {
|
||||||
|
tokio::spawn(async move {
|
||||||
match artifact.retain().await {
|
match artifact.retain().await {
|
||||||
Ok(hold) => {
|
Ok(hold) => (name, hold),
|
||||||
artifacts.insert(name.clone(), hold);
|
Err(_) => (name, artifact),
|
||||||
}
|
|
||||||
Err(_) => {
|
|
||||||
artifacts.insert(name.clone(), artifact);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let mut artifacts = BTreeMap::new();
|
||||||
|
for retain in retains {
|
||||||
|
if let Ok((name, artifact)) = retain.await {
|
||||||
|
artifacts.insert(name, artifact);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
drop(result);
|
drop(result);
|
||||||
Ok(DomainReply { outcome, request_id, artifacts })
|
Ok(DomainReply { outcome, request_id: self.request_id, artifacts })
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Maps a bus failure onto a domain error, preserving how certain the mutation is.
|
/// Maps a bus failure onto a domain error, preserving how certain the mutation is.
|
||||||
|
|
|
||||||
|
|
@ -110,6 +110,28 @@ pub fn executor_payload(agent_id: &str) -> String {
|
||||||
pub const WORLD_PAYLOAD: &str = "world";
|
pub const WORLD_PAYLOAD: &str = "world";
|
||||||
/// The task ledger's payload name.
|
/// The task ledger's payload name.
|
||||||
pub const TASK_LEDGER_PAYLOAD: &str = "task-ledger";
|
pub const TASK_LEDGER_PAYLOAD: &str = "task-ledger";
|
||||||
|
/// The prefix of the payloads that carry a task ledger's attachments: bytes beside its typed
|
||||||
|
/// value, for a ledger over the 32 KiB `TypedValue` bound (`workers-v1` section 1, "explicit
|
||||||
|
/// artifact-backed schema"; `Task::capture_attachments`). `task-ledger-<name>`.
|
||||||
|
pub const TASK_ATTACHMENT_PREFIX: &str = "task-ledger-";
|
||||||
|
|
||||||
|
/// The payload name of one task ledger attachment.
|
||||||
|
pub fn task_attachment_payload(name: &str) -> String {
|
||||||
|
format!("{TASK_ATTACHMENT_PREFIX}{name}")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The task ledger's attachments among a checkpoint's payloads, by attachment name.
|
||||||
|
pub fn task_attachments(
|
||||||
|
payloads: &std::collections::BTreeMap<String, Vec<u8>>,
|
||||||
|
) -> std::collections::BTreeMap<String, Vec<u8>> {
|
||||||
|
payloads
|
||||||
|
.iter()
|
||||||
|
.filter_map(|(name, bytes)| {
|
||||||
|
name.strip_prefix(TASK_ATTACHMENT_PREFIX).map(|n| (n.to_owned(), bytes.clone()))
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
/// The prior world inspection's payload name.
|
/// The prior world inspection's payload name.
|
||||||
pub const PRIOR_INSPECTION_PAYLOAD: &str = "prior-inspection";
|
pub const PRIOR_INSPECTION_PAYLOAD: &str = "prior-inspection";
|
||||||
/// The coordinator's admission state and event watermarks.
|
/// The coordinator's admission state and event watermarks.
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@
|
||||||
//! writes a controller or neural state directly.
|
//! writes a controller or neural state directly.
|
||||||
|
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
use serde_json::{Map, Value, json};
|
use serde_json::{Map, Value, json};
|
||||||
|
|
||||||
|
|
@ -53,6 +54,48 @@ pub fn controller_schema_ref() -> SchemaRef {
|
||||||
synthetic_schema("arena.controller.v1", 1)
|
synthetic_schema("arena.controller.v1", 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One boundary's inspection as the task and the executor read it: the observation's typed
|
||||||
|
/// `inspection` value plus the bytes of the attachments the task declared
|
||||||
|
/// ([`Task::inspection_attachments`]).
|
||||||
|
///
|
||||||
|
/// An artifact-backed inspection (`gameboy-memory-inspection-v1`: a 64 KiB image per boundary)
|
||||||
|
/// names its bytes by `ArtifactRef`; the coordinator holds the artifact until the transition
|
||||||
|
/// that reads it has been evaluated (`step-v1` section 3, Phase C amendment) and hands the task
|
||||||
|
/// the bytes, so neither the task nor the executor ever reads a live world. The synthetic
|
||||||
|
/// composition declares no attachment, and its inspection derefs to the typed value it always
|
||||||
|
/// was.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Inspection {
|
||||||
|
/// The boundary the observation belongs to.
|
||||||
|
pub boundary: u64,
|
||||||
|
pub value: TypedValue,
|
||||||
|
/// Attachment name to bytes, for the names the task declared.
|
||||||
|
pub attachments: BTreeMap<String, Arc<Vec<u8>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Inspection {
|
||||||
|
/// An inspection with no attachment: the synthetic composition's.
|
||||||
|
pub fn plain(boundary: u64, value: TypedValue) -> Inspection {
|
||||||
|
Inspection { boundary, value, attachments: BTreeMap::new() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::ops::Deref for Inspection {
|
||||||
|
type Target = TypedValue;
|
||||||
|
|
||||||
|
fn deref(&self) -> &TypedValue {
|
||||||
|
&self.value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a task's part of a rollback produced (`step-v1` section 6 amendment, step 3): the next
|
||||||
|
/// decision contexts for the restored boundary, and any events it reports.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct RollbackEvaluation {
|
||||||
|
pub next_contexts: BTreeMap<Id, TypedValue>,
|
||||||
|
pub events: Vec<TaskEvent>,
|
||||||
|
}
|
||||||
|
|
||||||
/// What `Task.bootstrap` produced.
|
/// What `Task.bootstrap` produced.
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct Bootstrap {
|
pub struct Bootstrap {
|
||||||
|
|
@ -70,16 +113,27 @@ pub struct Evaluation {
|
||||||
pub progress: TypedValue,
|
pub progress: TypedValue,
|
||||||
pub events: Vec<TaskEvent>,
|
pub events: Vec<TaskEvent>,
|
||||||
pub episode: Option<EpisodeRequest>,
|
pub episode: Option<EpisodeRequest>,
|
||||||
|
/// Slot saves the transition asks for at the boundary it reached, applied by the coordinator
|
||||||
|
/// after every Commit and before any capture or rollback there (`step-v1` section 3, Phase C
|
||||||
|
/// amendment; environment capability `gameboy-slots-v1`). Empty in every composition that
|
||||||
|
/// declares no slots.
|
||||||
|
pub slot_saves: Vec<Id>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A checkpointable task ledger and the two evaluation entry points.
|
/// A checkpointable task ledger and the two evaluation entry points.
|
||||||
pub trait Task: Send {
|
pub trait Task: Send {
|
||||||
fn schema(&self) -> SchemaRef;
|
fn schema(&self) -> SchemaRef;
|
||||||
|
|
||||||
|
/// The inspection attachments this task and its executor read, which the coordinator asks
|
||||||
|
/// the environment for, holds and hands over as bytes. None by default.
|
||||||
|
fn inspection_attachments(&self) -> Vec<String> {
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
|
||||||
/// Called once, at boundary 0, before any agent is initialized.
|
/// Called once, at boundary 0, before any agent is initialized.
|
||||||
fn bootstrap(
|
fn bootstrap(
|
||||||
&mut self,
|
&mut self,
|
||||||
initial_inspection: &TypedValue,
|
initial_inspection: &Inspection,
|
||||||
bindings: &[PortBinding],
|
bindings: &[PortBinding],
|
||||||
) -> DomainResult<Bootstrap>;
|
) -> DomainResult<Bootstrap>;
|
||||||
|
|
||||||
|
|
@ -87,11 +141,40 @@ pub trait Task: Send {
|
||||||
fn evaluate_transition(
|
fn evaluate_transition(
|
||||||
&mut self,
|
&mut self,
|
||||||
scope: &Scope,
|
scope: &Scope,
|
||||||
old_inspection: &TypedValue,
|
old_inspection: &Inspection,
|
||||||
new_inspection: &TypedValue,
|
new_inspection: &Inspection,
|
||||||
applied_controls: &[PortControl],
|
applied_controls: &[PortControl],
|
||||||
) -> DomainResult<Evaluation>;
|
) -> DomainResult<Evaluation>;
|
||||||
|
|
||||||
|
/// Step 3 of a declared rollback policy, coordinator-local (`step-v1` section 6 amendment):
|
||||||
|
/// the task clears its transient observations and the executor cancels any running action
|
||||||
|
/// and observes the restored boundary, which yields the next decision contexts. `scope` is
|
||||||
|
/// the new epoch at the restored boundary. A task that declares no rollback policy refuses.
|
||||||
|
fn rollback(
|
||||||
|
&mut self,
|
||||||
|
_scope: &Scope,
|
||||||
|
_restored: &Inspection,
|
||||||
|
) -> DomainResult<RollbackEvaluation> {
|
||||||
|
Err(DomainError::before(
|
||||||
|
ErrorCode::Unsupported,
|
||||||
|
"this task declares no rollback policy",
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// After a group restore installed this task's ledger: the restored boundary's inspection
|
||||||
|
/// and the agents' restored brain clock. A task whose executor state is transient
|
||||||
|
/// (`restore: legacy-transient-reset`) re-observes the world here and returns the decision
|
||||||
|
/// contexts it would hand the agents, which the coordinator holds against the ones the
|
||||||
|
/// checkpoint recorded. `None` (the default) means the recorded contexts stand unchecked.
|
||||||
|
fn restored(
|
||||||
|
&mut self,
|
||||||
|
_scope: &Scope,
|
||||||
|
_restored: &Inspection,
|
||||||
|
_clock: &RationalNs,
|
||||||
|
) -> DomainResult<Option<BTreeMap<Id, TypedValue>>> {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
|
||||||
fn progress(&self) -> TypedValue;
|
fn progress(&self) -> TypedValue;
|
||||||
|
|
||||||
/// How many times `evaluate_transition` has run. A transition must evaluate once.
|
/// How many times `evaluate_transition` has run. A transition must evaluate once.
|
||||||
|
|
@ -100,6 +183,35 @@ pub trait Task: Send {
|
||||||
/// The checkpointable ledger at a committed boundary (`workers-v1` section 4).
|
/// The checkpointable ledger at a committed boundary (`workers-v1` section 4).
|
||||||
fn capture(&self) -> DomainResult<TypedValue>;
|
fn capture(&self) -> DomainResult<TypedValue>;
|
||||||
|
|
||||||
|
/// Bytes the ledger carries beside its typed value, by name: for a ledger over the 32 KiB
|
||||||
|
/// `TypedValue` bound, the "explicit artifact-backed schema" of `workers-v1` section 1. A
|
||||||
|
/// checkpoint files each as its own payload (`state::task_attachment_payload`). None by
|
||||||
|
/// default.
|
||||||
|
fn capture_attachments(&self) -> DomainResult<BTreeMap<String, Vec<u8>>> {
|
||||||
|
Ok(BTreeMap::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`Task::validate_restore`] with the ledger's attachments.
|
||||||
|
fn validate_restore_with(
|
||||||
|
&self,
|
||||||
|
state: &TypedValue,
|
||||||
|
attachments: &BTreeMap<String, Vec<u8>>,
|
||||||
|
) -> DomainResult<()> {
|
||||||
|
let _ = attachments;
|
||||||
|
self.validate_restore(state)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`Task::install_restore`] with the ledger's attachments.
|
||||||
|
fn install_restore_with(
|
||||||
|
&mut self,
|
||||||
|
epoch: &Id,
|
||||||
|
state: &TypedValue,
|
||||||
|
attachments: &BTreeMap<String, Vec<u8>>,
|
||||||
|
) -> DomainResult<()> {
|
||||||
|
let _ = attachments;
|
||||||
|
self.install_restore(epoch, state)
|
||||||
|
}
|
||||||
|
|
||||||
/// Validates a captured ledger without installing it, so a group install can fail before
|
/// Validates a captured ledger without installing it, so a group install can fail before
|
||||||
/// anything is changed.
|
/// anything is changed.
|
||||||
fn validate_restore(&self, state: &TypedValue) -> DomainResult<()>;
|
fn validate_restore(&self, state: &TypedValue) -> DomainResult<()>;
|
||||||
|
|
@ -127,7 +239,7 @@ pub trait ActionExecutor: Send {
|
||||||
&mut self,
|
&mut self,
|
||||||
scope: &Scope,
|
scope: &Scope,
|
||||||
decision: &TypedValue,
|
decision: &TypedValue,
|
||||||
current_game_state: &TypedValue,
|
current_game_state: &Inspection,
|
||||||
progress: &TypedValue,
|
progress: &TypedValue,
|
||||||
clock: &RationalNs,
|
clock: &RationalNs,
|
||||||
) -> DomainResult<(ControllerIntent, Vec<TaskEvent>)>;
|
) -> DomainResult<(ControllerIntent, Vec<TaskEvent>)>;
|
||||||
|
|
@ -151,7 +263,7 @@ impl ActionExecutor for IdentityExecutor {
|
||||||
&mut self,
|
&mut self,
|
||||||
_scope: &Scope,
|
_scope: &Scope,
|
||||||
decision: &TypedValue,
|
decision: &TypedValue,
|
||||||
_current_game_state: &TypedValue,
|
_current_game_state: &Inspection,
|
||||||
_progress: &TypedValue,
|
_progress: &TypedValue,
|
||||||
_clock: &RationalNs,
|
_clock: &RationalNs,
|
||||||
) -> DomainResult<(ControllerIntent, Vec<TaskEvent>)> {
|
) -> DomainResult<(ControllerIntent, Vec<TaskEvent>)> {
|
||||||
|
|
@ -294,7 +406,7 @@ impl Task for CounterTask {
|
||||||
|
|
||||||
fn bootstrap(
|
fn bootstrap(
|
||||||
&mut self,
|
&mut self,
|
||||||
initial_inspection: &TypedValue,
|
initial_inspection: &Inspection,
|
||||||
bindings: &[PortBinding],
|
bindings: &[PortBinding],
|
||||||
) -> DomainResult<Bootstrap> {
|
) -> DomainResult<Bootstrap> {
|
||||||
if initial_inspection.schema != inspection_schema() {
|
if initial_inspection.schema != inspection_schema() {
|
||||||
|
|
@ -329,8 +441,8 @@ impl Task for CounterTask {
|
||||||
fn evaluate_transition(
|
fn evaluate_transition(
|
||||||
&mut self,
|
&mut self,
|
||||||
scope: &Scope,
|
scope: &Scope,
|
||||||
old_inspection: &TypedValue,
|
old_inspection: &Inspection,
|
||||||
new_inspection: &TypedValue,
|
new_inspection: &Inspection,
|
||||||
applied_controls: &[PortControl],
|
applied_controls: &[PortControl],
|
||||||
) -> DomainResult<Evaluation> {
|
) -> DomainResult<Evaluation> {
|
||||||
let old = old_inspection.integer("counter").map_err(DomainError::invalid)?;
|
let old = old_inspection.integer("counter").map_err(DomainError::invalid)?;
|
||||||
|
|
@ -445,6 +557,7 @@ impl Task for CounterTask {
|
||||||
progress: self.progress_value(),
|
progress: self.progress_value(),
|
||||||
events,
|
events,
|
||||||
episode,
|
episode,
|
||||||
|
slot_saves: Vec::new(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -113,24 +113,39 @@ impl StatusCell {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The rest of a reply a handler finishes outside the endpoint's lock.
|
||||||
|
pub type DeferredReply =
|
||||||
|
std::pin::Pin<Box<dyn std::future::Future<Output = DomainResult<HandlerReply>> + Send>>;
|
||||||
|
|
||||||
/// What a handler produced: a domain `result` object and the artifacts it attaches.
|
/// What a handler produced: a domain `result` object and the artifacts it attaches.
|
||||||
pub struct HandlerReply {
|
pub struct HandlerReply {
|
||||||
pub result: Map<String, Value>,
|
pub result: Map<String, Value>,
|
||||||
pub artifacts: Vec<(String, flybus::Artifact)>,
|
pub artifacts: Vec<(String, flybus::Artifact)>,
|
||||||
/// True when a failure left the endpoint mutated; the shell reports it as such.
|
/// True when a failure left the endpoint mutated; the shell reports it as such.
|
||||||
pub mutated: bool,
|
pub mutated: bool,
|
||||||
|
/// When set, the reply is this future's: the handler took what it needs from the endpoint
|
||||||
|
/// (a state snapshot at the committed boundary) and the rest -- encoding, digesting and
|
||||||
|
/// sealing a capture payload -- runs after the endpoint's lock is released, so the next
|
||||||
|
/// mutation (the next `Agent.Prepare`) does not wait for it. The bus call is answered
|
||||||
|
/// when it completes, and cached like any other reply.
|
||||||
|
pub deferred: Option<DeferredReply>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HandlerReply {
|
impl HandlerReply {
|
||||||
pub fn new(result: Map<String, Value>) -> HandlerReply {
|
pub fn new(result: Map<String, Value>) -> HandlerReply {
|
||||||
HandlerReply { result, artifacts: Vec::new(), mutated: true }
|
HandlerReply { result, artifacts: Vec::new(), mutated: true, deferred: None }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn with_artifacts(
|
pub fn with_artifacts(
|
||||||
result: Map<String, Value>,
|
result: Map<String, Value>,
|
||||||
artifacts: Vec<(String, flybus::Artifact)>,
|
artifacts: Vec<(String, flybus::Artifact)>,
|
||||||
) -> HandlerReply {
|
) -> HandlerReply {
|
||||||
HandlerReply { result, artifacts, mutated: true }
|
HandlerReply { result, artifacts, mutated: true, deferred: None }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A reply finished by `rest` outside the endpoint's lock ([`HandlerReply::deferred`]).
|
||||||
|
pub fn deferred(rest: DeferredReply) -> HandlerReply {
|
||||||
|
HandlerReply { result: Map::new(), artifacts: Vec::new(), mutated: true, deferred: Some(rest) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The canonical JSON of one method result.
|
/// The canonical JSON of one method result.
|
||||||
|
|
@ -304,6 +319,7 @@ async fn run<E: WorkerEndpoint>(
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
let mut running: Vec<tokio::task::JoinHandle<()>> = Vec::new();
|
let mut running: Vec<tokio::task::JoinHandle<()>> = Vec::new();
|
||||||
|
let order = Arc::new(LockOrder::default());
|
||||||
while let Some(incoming) = service.next().await {
|
while let Some(incoming) = service.next().await {
|
||||||
let method = incoming.method().to_owned();
|
let method = incoming.method().to_owned();
|
||||||
let responder = incoming.responder();
|
let responder = incoming.responder();
|
||||||
|
|
@ -491,9 +507,12 @@ async fn run<E: WorkerEndpoint>(
|
||||||
// original bus call still completes normally. The endpoint mutex, not this loop,
|
// original bus call still completes normally. The endpoint mutex, not this loop,
|
||||||
// enforces one mutation at a time.
|
// enforces one mutation at a time.
|
||||||
running.retain(|task| !task.is_finished());
|
running.retain(|task| !task.is_finished());
|
||||||
|
let ticket = order.issue();
|
||||||
running.push(tokio::spawn(execute(
|
running.push(tokio::spawn(execute(
|
||||||
client.clone(),
|
client.clone(),
|
||||||
endpoint.clone(),
|
endpoint.clone(),
|
||||||
|
order.clone(),
|
||||||
|
ticket,
|
||||||
cache.clone(),
|
cache.clone(),
|
||||||
status.clone(),
|
status.clone(),
|
||||||
worker_id.clone(),
|
worker_id.clone(),
|
||||||
|
|
@ -512,11 +531,73 @@ async fn run<E: WorkerEndpoint>(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Admitted mutations take the endpoint's lock in the order they arrived.
|
||||||
|
///
|
||||||
|
/// Each runs in a task of its own, so the shell keeps reading, and tasks are not scheduled in
|
||||||
|
/// spawn order: without this, a `State.Capture` followed on the wire by the next
|
||||||
|
/// `Agent.Prepare` could find the agent already prepared. A ticket per admitted mutation, taken
|
||||||
|
/// in arrival order, and the lock taken only on the ticket's turn keep the wire's order.
|
||||||
|
#[derive(Default)]
|
||||||
|
struct LockOrder {
|
||||||
|
issued: std::sync::atomic::AtomicU64,
|
||||||
|
turn: std::sync::atomic::AtomicU64,
|
||||||
|
changed: tokio::sync::Notify,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LockOrder {
|
||||||
|
fn issue(&self) -> u64 {
|
||||||
|
self.issued.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn lock_in_turn<'a, E>(
|
||||||
|
&self,
|
||||||
|
ticket: u64,
|
||||||
|
endpoint: &'a tokio::sync::Mutex<E>,
|
||||||
|
) -> tokio::sync::MutexGuard<'a, E> {
|
||||||
|
loop {
|
||||||
|
let changed = self.changed.notified();
|
||||||
|
if self.turn.load(std::sync::atomic::Ordering::SeqCst) == ticket {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
changed.await;
|
||||||
|
}
|
||||||
|
// Queue on the lock first, then hand the turn on: the next ticket queues behind this
|
||||||
|
// one on the (fair) mutex.
|
||||||
|
let lock = endpoint.lock();
|
||||||
|
tokio::pin!(lock);
|
||||||
|
let guard = match futures_poll_once(lock.as_mut()).await {
|
||||||
|
Some(guard) => guard,
|
||||||
|
None => {
|
||||||
|
self.advance();
|
||||||
|
return lock.await;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
self.advance();
|
||||||
|
guard
|
||||||
|
}
|
||||||
|
|
||||||
|
fn advance(&self) {
|
||||||
|
self.turn.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||||
|
self.changed.notify_waiters();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Polls a future once: its output if it is ready, else `None` with the future registered.
|
||||||
|
async fn futures_poll_once<F: std::future::Future + Unpin>(mut f: F) -> Option<F::Output> {
|
||||||
|
std::future::poll_fn(|cx| match std::pin::Pin::new(&mut f).poll(cx) {
|
||||||
|
std::task::Poll::Ready(v) => std::task::Poll::Ready(Some(v)),
|
||||||
|
std::task::Poll::Pending => std::task::Poll::Ready(None),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
/// Runs one admitted mutation, records its reply and answers the bus call.
|
/// Runs one admitted mutation, records its reply and answers the bus call.
|
||||||
#[allow(clippy::too_many_arguments)]
|
#[allow(clippy::too_many_arguments)]
|
||||||
async fn execute<E: WorkerEndpoint>(
|
async fn execute<E: WorkerEndpoint>(
|
||||||
client: flybus::Client,
|
client: flybus::Client,
|
||||||
endpoint: Arc<tokio::sync::Mutex<E>>,
|
endpoint: Arc<tokio::sync::Mutex<E>>,
|
||||||
|
order: Arc<LockOrder>,
|
||||||
|
ticket: u64,
|
||||||
cache: Arc<tokio::sync::Mutex<ResultCache>>,
|
cache: Arc<tokio::sync::Mutex<ResultCache>>,
|
||||||
status: StatusCell,
|
status: StatusCell,
|
||||||
worker_id: Id,
|
worker_id: Id,
|
||||||
|
|
@ -533,7 +614,7 @@ async fn execute<E: WorkerEndpoint>(
|
||||||
let outcome = {
|
let outcome = {
|
||||||
// One mutation at a time: the endpoint mutex is the worker's simulation lock, and it is
|
// One mutation at a time: the endpoint mutex is the worker's simulation lock, and it is
|
||||||
// never held across a bus round trip taken by anything else.
|
// never held across a bus round trip taken by anything else.
|
||||||
let mut e = endpoint.lock().await;
|
let mut e = order.lock_in_turn(ticket, &endpoint).await;
|
||||||
let ctx = HandlerCtx {
|
let ctx = HandlerCtx {
|
||||||
method: &method,
|
method: &method,
|
||||||
request: &request,
|
request: &request,
|
||||||
|
|
@ -542,16 +623,34 @@ async fn execute<E: WorkerEndpoint>(
|
||||||
};
|
};
|
||||||
e.handle(ctx).await
|
e.handle(ctx).await
|
||||||
};
|
};
|
||||||
|
// A deferred reply finishes here, with the endpoint's lock released.
|
||||||
|
let outcome = match outcome {
|
||||||
|
Ok(HandlerReply { deferred: Some(rest), .. }) => rest.await,
|
||||||
|
other => other,
|
||||||
|
};
|
||||||
match outcome {
|
match outcome {
|
||||||
Ok(reply) => {
|
Ok(reply) => {
|
||||||
let outcome = success(&request, &worker_id, &incarnation_id, reply.result.clone());
|
let outcome = success(&request, &worker_id, &incarnation_id, reply.result.clone());
|
||||||
let mut holds = Vec::with_capacity(reply.artifacts.len());
|
// The cache owns its own hold on every artifact, so a replay survives the first
|
||||||
for (name, artifact) in &reply.artifacts {
|
// caller consuming its delivery. The holds are independent router round trips, so
|
||||||
// The cache owns its own hold, so a replay survives the first caller
|
// they are taken concurrently.
|
||||||
// consuming its delivery.
|
let retains: Vec<_> = reply
|
||||||
|
.artifacts
|
||||||
|
.iter()
|
||||||
|
.map(|(name, artifact)| {
|
||||||
|
let (name, artifact) = (name.clone(), artifact.clone());
|
||||||
|
tokio::spawn(async move {
|
||||||
match artifact.retain().await {
|
match artifact.retain().await {
|
||||||
Ok(hold) => holds.push((name.clone(), hold)),
|
Ok(hold) => (name, hold),
|
||||||
Err(_) => holds.push((name.clone(), artifact.clone())),
|
Err(_) => (name, artifact),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let mut holds = Vec::with_capacity(retains.len());
|
||||||
|
for retain in retains {
|
||||||
|
if let Ok(pair) = retain.await {
|
||||||
|
holds.push(pair);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let cached = CachedReply::with_artifacts(outcome.clone(), holds);
|
let cached = CachedReply::with_artifacts(outcome.clone(), holds);
|
||||||
|
|
|
||||||
|
|
@ -25,7 +25,7 @@ both_transports!(
|
||||||
the_committed_snapshot_names_the_boundary_that_just_ended,
|
the_committed_snapshot_names_the_boundary_that_just_ended,
|
||||||
a_terminal_episode_pauses_at_its_own_boundary,
|
a_terminal_episode_pauses_at_its_own_boundary,
|
||||||
a_rollback_request_without_a_declared_policy_fails_the_epoch,
|
a_rollback_request_without_a_declared_policy_fails_the_epoch,
|
||||||
a_declared_rollback_policy_holds_the_session_at_its_boundary,
|
a_declared_rollback_policy_needs_participants_that_apply_it,
|
||||||
status_answers_with_the_committed_boundary,
|
status_answers_with_the_committed_boundary,
|
||||||
a_worker_refuses_a_second_initialize,
|
a_worker_refuses_a_second_initialize,
|
||||||
a_single_agent_composition_runs_the_same_transaction,
|
a_single_agent_composition_runs_the_same_transaction,
|
||||||
|
|
@ -329,9 +329,13 @@ async fn a_rollback_request_without_a_declared_policy_fails_the_epoch(via: Via)
|
||||||
f.shutdown().await;
|
f.shutdown().await;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// With `legacy-ratchet-rollback-v1` declared the request is accepted: the transition commits and
|
/// With `legacy-ratchet-rollback-v1` declared the coordinator runs the policy itself
|
||||||
/// the session holds at its boundary with the request recorded, for the policy to run.
|
/// (`step-v1` section 6 amendment; TASK-01), so a composition may only declare it over
|
||||||
async fn a_declared_rollback_policy_holds_the_session_at_its_boundary(via: Via) {
|
/// participants that can apply it: agents that answer `Agent.Rollback` and a world with
|
||||||
|
/// `gameboy-slots-v1`. The synthetic agents answer neither, so the session never starts --
|
||||||
|
/// rather than accepting a rollback request it cannot apply. (Until TASK-01 the declared request
|
||||||
|
/// paused the session at its boundary.)
|
||||||
|
async fn a_declared_rollback_policy_needs_participants_that_apply_it(via: Via) {
|
||||||
let config = HarnessConfig {
|
let config = HarnessConfig {
|
||||||
terminal: fly_session::task::Terminal::RollbackAfterTransitions(2),
|
terminal: fly_session::task::Terminal::RollbackAfterTransitions(2),
|
||||||
..HarnessConfig::default()
|
..HarnessConfig::default()
|
||||||
|
|
@ -342,13 +346,11 @@ async fn a_declared_rollback_policy_holds_the_session_at_its_boundary(via: Via)
|
||||||
.declare_rollback_policy("legacy-ratchet-rollback-v1")
|
.declare_rollback_policy("legacy-ratchet-rollback-v1")
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(f.harness.coordinator.declare_rollback_policy("reset-everything").is_err());
|
assert!(f.harness.coordinator.declare_rollback_policy("reset-everything").is_err());
|
||||||
within("bootstrap", f.harness.coordinator.bootstrap()).await.unwrap();
|
let err = within("bootstrap", f.harness.coordinator.bootstrap()).await.unwrap_err();
|
||||||
let reports = within("run", f.harness.coordinator.run(4)).await.unwrap();
|
assert_eq!(err.error.code, ErrorCode::Unsupported, "{}", err.error.message);
|
||||||
assert_eq!(reports.len(), 2);
|
assert!(err.error.message.contains("Agent.Rollback"), "{}", err.error.message);
|
||||||
assert!(!f.harness.coordinator.is_fenced());
|
assert!(f.harness.coordinator.is_fenced());
|
||||||
assert_eq!(f.harness.coordinator.phase(), Phase::Paused(2));
|
assert!(f.harness.coordinator.episode_request().is_none());
|
||||||
let request = f.harness.coordinator.episode_request().unwrap();
|
|
||||||
assert_eq!(request.kind, EpisodeRequestKind::Rollback);
|
|
||||||
f.shutdown().await;
|
f.shutdown().await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue