diff --git a/Cargo.lock b/Cargo.lock index 7ca3b48..00cdb75 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1256,7 +1256,9 @@ name = "exec_viz" version = "0.1.0" dependencies = [ "axum", + "rmp-serde", "serde", + "serde_json", "tokio", "tower-http", "trading_data_dag", @@ -3014,6 +3016,25 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rmp" +version = "0.8.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c" +dependencies = [ + "num-traits", +] + +[[package]] +name = "rmp-serde" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155" +dependencies = [ + "rmp", + "serde", +] + [[package]] name = "ron" version = "0.12.2" @@ -4087,7 +4108,7 @@ dependencies = [ [[package]] name = "v_utils" -version = "2.17.3" +version = "2.17.4" dependencies = [ "ahash", "bon", @@ -4133,7 +4154,7 @@ dependencies = [ [[package]] name = "v_utils_macros" -version = "2.12.4" +version = "2.12.5" dependencies = [ "eyre", "heck", diff --git a/Cargo.toml b/Cargo.toml index 76df410..b326678 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,6 +39,7 @@ getrandom = { version = "=0.3.4", features = ["wasm_js"] } gloo-net = { version = "0.7", features = ["http"] } gloo-timers = { version = "0.3", features = ["futures"] } js-sys = "0.3" +rmp-serde = "1" serde = { version = "^1.0.228", features = ["derive"] } serde_json = "^1" tokio = { version = "^1", features = ["full"] } diff --git a/README.md b/README.md index 693c2e1..2c1443e 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ tokio::join!(viz.clone().serve_on(listener), async { **The recording is not on your thread.** A finished tick crosses to a tape thread over a bounded channel, and that thread does the naming, bucketing, thinning and cost accounting; the graph pays a `Display`, a clipped `Debug` and one push, into buffers the tape hands back. `Backpressure` says what a full channel means: `Block` for a replay, which wants the whole tape and whose feed will wait, and `Drop` for a live run, where a fill must never queue behind a study aid — dropped ticks are counted into `ActivationFrame::dropped` rather than passing for a quiet market. -**The tape is the storage.** A live run cannot be re-run, so ticks are kept rather than replayed-by-rewinding. Past `capacity`, the buffer *thins* instead of dropping its front: the newest `capacity / 2` ticks stay whole, and everything older is decimated to every `stride`-th tick (`stride` only doubles). A run many times the capacity stays walkable end to end, with the freshest stretch still tick-exact — where a plain ring would make the beginning of a long recording unreachable for the rest of the run. The per-node series the chart draws is downsampled online into `bucket_ms` buckets and never dropped. +**The tape is the storage.** A live run cannot be re-run, so ticks are kept rather than replayed-by-rewinding. Past `capacity`, the buffer *thins* instead of dropping its front: the newest `capacity / 2` ticks stay whole, and everything older is decimated by *fire* rather than by index — each node keeps one fire in `2^k`, and `k` rises only for whichever node is claiming most of the backbone. So a run many times the capacity stays walkable end to end with its freshest stretch still tick-exact, and the rare event a human scrubs for — the 5-minute bar, the classification — survives the squeeze that the book flood absorbs. See *Picking a `capacity`* below for what to size it to. The per-node series the chart draws is downsampled online into `bucket_ms` buckets and never dropped. #### The view @@ -78,12 +78,75 @@ The DAG panel is DOM-inspector-style and present-moment only: one column per top | `c` | skip to the next `Classify` | | `n` | skip to the next change in the nodes you clicked | +Two things the nav says about a thinned stretch. Where a step covers more than one absolute tick it shows a `×n` next to the position — the resolution the tape is admitting to, rather than a stepper that looks like it is skipping. And a scan that walks a sealed recording to its end without a hit leaves the cursor where it was and reports that it found nothing, instead of answering a failed search by jumping to the end of the run. + An op can name a tick that has not been recorded yet. The server says so (`pending`) rather than blocking, and the control that outran the feed shows a `⟳` while it re-issues itself. #### HTTP `GET /api/topology` · `GET /api/day` · `GET /api/status`, and `POST /api/{step,seek,seek_ts,step_until,step_until_change}`. Shapes live in `exec_viz::api_types`, which both halves compile — the wasm client depends on `exec_viz` with `default-features = false`, leaving just the wire types and none of the axum/tokio server half. +### Picking a `capacity` + +`capacity` is the only number `Viz::new` asks for that has no right answer — it is RAM traded +against reactivity, and the exchange rate is your graph's, not this crate's. What it constrains: + +| | | +|---|---| +| `capacity / 2` | the newest ticks kept **whole** — the stretch that stays tick-exact | +| `capacity / 4` | the ceiling on the thinned *backbone*, and so how deep the squeeze goes | +| `capacity / 2` | the recycle channel's depth: one pass frees between a quarter and a half of the buffer, and the recorder takes all of it back rather than allocating | +| `capacity` | the bound on the carry-forward scan a frame does for every quiet node, which is what landing a cursor costs | + +Thinning is **per node, not per tick**: a pass raises the exponent of whichever node is claiming most +of the backbone until the backbone fits, so a node firing 288 times a day keeps all 288 while the +book-driven flood beside it is decimated. What that means for sizing — **a node's whole run stays +addressable as long as its fires fit inside its max-min fair share of `capacity / 4`.** Rare nodes +are never the ones cut, so in practice the share is the whole backbone minus what the handful of +greedy nodes settle at. In the block below, at `capacity` 20 000 the backbone is 5 000: the two nodes +that each want ~3 000 land on ~1 790 apiece, and everything rarer than that keeps every fire it ever +had. Read the other way: a 5-minute bar over three days is 864 fires and is safe from about 8 000; +over a month it is 8 640 and wants ~65 000. + +Bigger is not free, and the price is not where it looks. Recording cost does not move with +`capacity` at all — the graph thread's leg of a fire is the same two renderings either way. What +moves is the cost of *landing* a cursor, because a frame carries every node's standing value and a +node quiet for a while is found by scanning back for it. + +The block below is one synthetic graph on one machine. `Viz::bytes` is exported so the same reading +can be taken against yours. + + +``` +318420 ticks (2 days at spl's 159210/day), 5 nodes, 107 B/tick of card faces +fires over the run: Book=318420 Screen=3185 Bar:1m=2895 Bar:5m=579 Bar:1h=49 + +footprint — Viz::bytes over the retained ticks + 2048 │▬ 3.0 MB (1477 B/tick) + 8192 │▬▬ 5.4 MB (818 B/tick) + 20000 │▬▬▬▬ 11.3 MB (665 B/tick) + 65536 │▬▬▬▬▬▬▬▬▬▬▬ 33.8 MB (554 B/tick) + 262144 │▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 132.6 MB (524 B/tick) + +reactivity — /api/seek mid-tape *above* a bare 53µs loopback hop, median of 64 + 2048 │▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 13µs + 8192 │▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 13µs + 20000 │▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 13µs + 65536 │▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 14µs + 262144 │▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 34µs + +addressability — fires still reachable by `step_until`, against the run's own + capacity retained Book Screen Bar:1m Bar:5m Bar:1h + 2048 2007 2007/318420 251/3185 231/2895 147/579 49/49 + 8192 6557 6557/318420 691/3185 899/2895 579/579 49/49 + 20000 16951 16951/318420 1796/3185 1784/2895 579/579 49/49 + 65536 61047 61047/318420 3185/3185 2895/2895 579/579 49/49 + 262144 252884 252884/318420 3185/3185 2895/2895 579/579 49/49 +``` + + +Produced by `cargo r --release -p exec_viz --example capacity`, which splices it in here and writes +it to `docs/capacity.txt` — the numbers are read, not typed.
diff --git a/docs/.readme_assets/other.md b/docs/.readme_assets/other.md index e69de29..855949f 100644 --- a/docs/.readme_assets/other.md +++ b/docs/.readme_assets/other.md @@ -0,0 +1,61 @@ +### Picking a `capacity` + +`capacity` is the only number `Viz::new` asks for that has no right answer — it is RAM traded +against reactivity, and the exchange rate is your graph's, not this crate's. What it constrains: + +| | | +|---|---| +| `capacity / 2` | the newest ticks kept **whole** — the stretch that stays tick-exact | +| `capacity / 4` | the ceiling on the thinned *backbone*, and so how deep the squeeze goes | +| `capacity / 2` | the recycle channel's depth: one pass frees between a quarter and a half of the buffer, and the recorder takes all of it back rather than allocating | +| `capacity` | the bound on the carry-forward scan a frame does for every quiet node, which is what landing a cursor costs | + +Thinning is **per node, not per tick**: a pass raises the exponent of whichever node is claiming most +of the backbone until the backbone fits, so a node firing 288 times a day keeps all 288 while the +book-driven flood beside it is decimated. What that means for sizing — **a node's whole run stays +addressable as long as its fires fit inside its max-min fair share of `capacity / 4`.** Rare nodes +are never the ones cut, so in practice the share is the whole backbone minus what the handful of +greedy nodes settle at. In the block below, at `capacity` 20 000 the backbone is 5 000: the two nodes +that each want ~3 000 land on ~1 790 apiece, and everything rarer than that keeps every fire it ever +had. Read the other way: a 5-minute bar over three days is 864 fires and is safe from about 8 000; +over a month it is 8 640 and wants ~65 000. + +Bigger is not free, and the price is not where it looks. Recording cost does not move with +`capacity` at all — the graph thread's leg of a fire is the same two renderings either way. What +moves is the cost of *landing* a cursor, because a frame carries every node's standing value and a +node quiet for a while is found by scanning back for it. + +The block below is one synthetic graph on one machine. `Viz::bytes` is exported so the same reading +can be taken against yours. + + +``` +318420 ticks (2 days at spl's 159210/day), 5 nodes, 107 B/tick of card faces +fires over the run: Book=318420 Screen=3185 Bar:1m=2895 Bar:5m=579 Bar:1h=49 + +footprint — Viz::bytes over the retained ticks + 2048 │▬ 3.0 MB (1477 B/tick) + 8192 │▬▬ 5.4 MB (818 B/tick) + 20000 │▬▬▬▬ 11.3 MB (665 B/tick) + 65536 │▬▬▬▬▬▬▬▬▬▬▬ 33.8 MB (554 B/tick) + 262144 │▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 132.6 MB (524 B/tick) + +reactivity — /api/seek mid-tape *above* a bare 53µs loopback hop, median of 64 + 2048 │▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 13µs + 8192 │▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 13µs + 20000 │▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 13µs + 65536 │▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 14µs + 262144 │▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 34µs + +addressability — fires still reachable by `step_until`, against the run's own + capacity retained Book Screen Bar:1m Bar:5m Bar:1h + 2048 2007 2007/318420 251/3185 231/2895 147/579 49/49 + 8192 6557 6557/318420 691/3185 899/2895 579/579 49/49 + 20000 16951 16951/318420 1796/3185 1784/2895 579/579 49/49 + 65536 61047 61047/318420 3185/3185 2895/2895 579/579 49/49 + 262144 252884 252884/318420 3185/3185 2895/2895 579/579 49/49 +``` + + +Produced by `cargo r --release -p exec_viz --example capacity`, which splices it in here and writes +it to `docs/capacity.txt` — the numbers are read, not typed. diff --git a/docs/.readme_assets/usage.md b/docs/.readme_assets/usage.md index fdff548..375a40d 100644 --- a/docs/.readme_assets/usage.md +++ b/docs/.readme_assets/usage.md @@ -22,7 +22,7 @@ tokio::join!(viz.clone().serve_on(listener), async { **The recording is not on your thread.** A finished tick crosses to a tape thread over a bounded channel, and that thread does the naming, bucketing, thinning and cost accounting; the graph pays a `Display`, a clipped `Debug` and one push, into buffers the tape hands back. `Backpressure` says what a full channel means: `Block` for a replay, which wants the whole tape and whose feed will wait, and `Drop` for a live run, where a fill must never queue behind a study aid — dropped ticks are counted into `ActivationFrame::dropped` rather than passing for a quiet market. -**The tape is the storage.** A live run cannot be re-run, so ticks are kept rather than replayed-by-rewinding. Past `capacity`, the buffer *thins* instead of dropping its front: the newest `capacity / 2` ticks stay whole, and everything older is decimated to every `stride`-th tick (`stride` only doubles). A run many times the capacity stays walkable end to end, with the freshest stretch still tick-exact — where a plain ring would make the beginning of a long recording unreachable for the rest of the run. The per-node series the chart draws is downsampled online into `bucket_ms` buckets and never dropped. +**The tape is the storage.** A live run cannot be re-run, so ticks are kept rather than replayed-by-rewinding. Past `capacity`, the buffer *thins* instead of dropping its front: the newest `capacity / 2` ticks stay whole, and everything older is decimated by *fire* rather than by index — each node keeps one fire in `2^k`, and `k` rises only for whichever node is claiming most of the backbone. So a run many times the capacity stays walkable end to end with its freshest stretch still tick-exact, and the rare event a human scrubs for — the 5-minute bar, the classification — survives the squeeze that the book flood absorbs. See *Picking a `capacity`* below for what to size it to. The per-node series the chart draws is downsampled online into `bucket_ms` buckets and never dropped. ### The view @@ -40,6 +40,8 @@ The DAG panel is DOM-inspector-style and present-moment only: one column per top | `c` | skip to the next `Classify` | | `n` | skip to the next change in the nodes you clicked | +Two things the nav says about a thinned stretch. Where a step covers more than one absolute tick it shows a `×n` next to the position — the resolution the tape is admitting to, rather than a stepper that looks like it is skipping. And a scan that walks a sealed recording to its end without a hit leaves the cursor where it was and reports that it found nothing, instead of answering a failed search by jumping to the end of the run. + An op can name a tick that has not been recorded yet. The server says so (`pending`) rather than blocking, and the control that outran the feed shows a `⟳` while it re-issues itself. ### HTTP diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 461ffcd..a0fd441 100755 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -7,10 +7,17 @@ browser that walks it tick by tick. ## The one idea -**The recording is the storage.** The obvious design — keep the graph, rewind it, re-run -to tick *n* — assumes the run is reproducible. A live feed is not: it happened once. So -every tick is written down as it fires, and every replay control is a cursor move over -that write-down. Nothing is ever recomputed. +**The recording is the storage — and the storage can be a file.** The obvious design — +keep the graph, rewind it, re-run to tick *n* — assumes the run is reproducible. A live +feed is not: it happened once. So every tick is written down as it fires, and every replay +control is a cursor move over that write-down. Nothing is ever recomputed. + +Because the tape is the whole of what a viewer reads, `Viz::save` can put it on disk and +`Viz::load` can open it again — a run recorded today is scrubbable next week, and whether +a UI was attached while it ran is a separate question from whether it was recorded. What +lands is what the tape held: a thinned run saves thinned, because that *is* the recording. +The file is `msgpack` behind a magic + a `TAPE_SCHEMA` that refuses a layout this build +does not read, rather than reinterpreting the bytes. That single choice sets the shape of everything else: @@ -45,7 +52,8 @@ flowchart LR holds the node `topology` (recorded once, on the first tick), the tick ring, the downsampled per-node `series` (`price_node`'s *is* the candle pane), and the cursor. Every replay op — `step`, `seek`, `seek_ts`, `step_until`, `step_until_change` — is a method here that - moves the cursor and returns an `ActivationFrame`. + moves the cursor and returns an `ActivationFrame`. `save` waits out the recording and + writes the tape down; `load` opens one back, sealed, with no recorder. - `server` — axum router and handlers, one thin `Json(...)` line each. Runtime-free: `serve_on` is a plain future taking an already-bound listener, so the app decides where it runs. Also serves the built `exec_viz_web` bundle (`EXEC_VIZ_WEB_DIR`) with an SPA @@ -53,9 +61,9 @@ flowchart LR - `api_types` — the wire shapes, and the only module that compiles without the `server` feature. That split is what lets the wasm client depend on this same crate for its types without dragging axum and tokio onto a wasm target. -- `record` — schema-only: the `runs/{run_id}/` layout and row shapes (orders, fills, - drawings) that sibling strategies each hand-roll today. Writers land with the first - migration onto it. +- `record` — the `runs/{run_id}/` layout: `TAPE_FILE`, plus the row shapes (orders, fills, + drawings) that sibling strategies each hand-roll today. The lanes other than the tape are + still schema-only; their writers land with the first migration onto it. `exec_viz_web` (the wasm front-end, `publish = false` — it is a bundle, not a crate): @@ -77,19 +85,52 @@ unreachable for the rest of the run — and since there is no re-run, unreachabl permanent. Instead, once `capacity` is hit, `Tape::thin` keeps: - the newest `capacity / 2` ticks **whole**, so the fresh stretch stays tick-exact, and -- every `stride`-th tick over everything before them, `stride` a doubling power of two. - -Each pass therefore keeps a subset of what the last one kept, and frees a quarter of the -buffer — one O(capacity) pass per `capacity / 4` ticks. A run many times the capacity is -still walkable end to end, at coarsening resolution. - -Two consequences worth knowing: +- over everything before them, a *backbone* of at most `capacity / 4` ticks — chosen by + fire rather than by index. + +**Decimating by tick index is proximity to the buffer, not to the problem.** What a human +scrubs a tape for is the rare event, and a fixed stride destroys precisely those: at spl's +318k ticks against a 20 000 tape the stride settled on 64, so a 5-minute bar that fired 576 +times over the window kept nine of them, and pressing "next change" crossed five hours per +press. + +So the unit of decimation is the *fire*. Every tick carries a `ranks` column — for each node +that fired on it, `trailing_zeros` of that node's fire ordinal — and "keep one fire in `2^k` +of node `i`" is then the single comparison `ranks[i] > keep[i]`. A tick survives if any node +claims it. `keep` is per node and rises max-min fairly: count the retained fires per node +over the pre-tail stretch, and while the union is over `capacity / 4`, raise the greediest +node's exponent by one. Busy nodes absorb the whole squeeze; a node that never dominates +never loses a fire. + +The rank column is what makes that a *subset filter* rather than a re-selection: it is +computed once, on the tape thread, and the kept sets nest as `k` grows — so each pass still +keeps a subset of what the last one kept, still frees between a quarter and a half of the +buffer, and is still one O(capacity) pass per `capacity / 4` ticks. It rides on `Tick` and +not on `Acts` deliberately: the `Acts` buffers are the graph thread's, recycled across the +handoff, and `Rec::on`/`Rec::drop`/`Recorder::at` — the leg shared with live — are untouched +by any of this. + +A node's very first fire has ordinal 0, whose `trailing_zeros` saturates above every `keep`, +so it survives every squeeze. That is what keeps the front of a long recording addressable +now that no index is privileged. + +What to size `capacity` to is a measurement, not an argument: `exec_viz/examples/capacity.rs` +sweeps it for footprint, cursor latency and per-node addressability, and splices the block +into `docs/.readme_assets/other.md` (raw copy at `docs/capacity.txt`). + +Three consequences worth knowing: - **The cursor is absolute** (an index among all ticks ever opened, not a buffer position), so a thinning pass cannot slide a parked cursor out from under the user. - **A carried-forward value is searched, not stamped.** A quiet node shows its last fired value; `Tape::held` scans back for it rather than remembering a tick number, because a remembered tick can be one a thinning pass has since dropped. +- **A step admits its own width.** Past the capacity one retained step covers several + absolute ticks, so `ActivationFrame::gap` carries how many and the nav shows it. Likewise + `found`: a search that reaches the end of a *sealed* recording without a hit leaves the + cursor alone and says so, rather than answering a failed search by parking the user at the + end of the run. While the tape is still growing that end *is* the resume point, and there + the cursor does move — `pending` says the op will be re-issued from it. The per-node chart series is *not* subject to any of this: it is downsampled online into `bucket_ms` buckets on the way in, and kept for the whole run. diff --git a/docs/capacity.txt b/docs/capacity.txt new file mode 100644 index 0000000..bc93ce3 --- /dev/null +++ b/docs/capacity.txt @@ -0,0 +1,24 @@ +318420 ticks (2 days at spl's 159210/day), 5 nodes, 107 B/tick of card faces +fires over the run: Book=318420 Screen=3185 Bar:1m=2895 Bar:5m=579 Bar:1h=49 + +footprint — Viz::bytes over the retained ticks + 2048 │▬ 3.0 MB (1477 B/tick) + 8192 │▬▬ 5.4 MB (818 B/tick) + 20000 │▬▬▬▬ 11.3 MB (665 B/tick) + 65536 │▬▬▬▬▬▬▬▬▬▬▬ 33.8 MB (554 B/tick) + 262144 │▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 132.6 MB (524 B/tick) + +reactivity — /api/seek mid-tape *above* a bare 53µs loopback hop, median of 64 + 2048 │▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 13µs + 8192 │▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 13µs + 20000 │▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 13µs + 65536 │▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 14µs + 262144 │▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 34µs + +addressability — fires still reachable by `step_until`, against the run's own + capacity retained Book Screen Bar:1m Bar:5m Bar:1h + 2048 2007 2007/318420 251/3185 231/2895 147/579 49/49 + 8192 6557 6557/318420 691/3185 899/2895 579/579 49/49 + 20000 16951 16951/318420 1796/3185 1784/2895 579/579 49/49 + 65536 61047 61047/318420 3185/3185 2895/2895 579/579 49/49 + 262144 252884 252884/318420 3185/3185 2895/2895 579/579 49/49 diff --git a/exec_viz/Cargo.toml b/exec_viz/Cargo.toml index 7a80ee5..55dfdf6 100644 --- a/exec_viz/Cargo.toml +++ b/exec_viz/Cargo.toml @@ -16,14 +16,24 @@ categories.workspace = true default = ["server"] # The recording `Viz` observer + the axum server over it. Native only; with it off the crate is # just `api_types`, which is all the wasm front-end (`exec_viz_web`) needs. -server = ["dep:axum", "dep:tokio", "dep:tower-http", "dep:trading_data_dag"] +server = [ + "dep:axum", + "dep:rmp-serde", + "dep:tokio", + "dep:tower-http", + "dep:trading_data_dag", +] [dependencies] axum = { workspace = true, optional = true } +rmp-serde = { workspace = true, optional = true } serde.workspace = true tokio = { workspace = true, optional = true } tower-http = { workspace = true, optional = true } trading_data_dag = { workspace = true, optional = true } +[dev-dependencies] +serde_json.workspace = true + [lints] workspace = true diff --git a/exec_viz/examples/capacity.rs b/exec_viz/examples/capacity.rs new file mode 100644 index 0000000..21b3927 --- /dev/null +++ b/exec_viz/examples/capacity.rs @@ -0,0 +1,389 @@ +//! What `capacity` buys and what it costs, measured rather than asserted — the `viz_cost.rs` → +//! `cost.json` → `cost.typ` shape from `trading_data`'s spl example, one crate over. +//! +//! The mix is synthetic on purpose: `exec_viz` cannot depend on a strategy that depends on it, so +//! the graph is built straight through the real [`Viz`]/[`Recorder`](exec_viz::Recorder) the way +//! `tape.rs`'s own tests do — a book-driven node firing every tick, a screener every 100, and +//! 1m/5m/1h bar analogues, at spl's measured ~106 B/tick of rendered card faces. What is *not* +//! synthetic is the tape: every reading below comes out of the same thinning pass and the same +//! handlers the browser drives. +//! +//! `cargo r --release -p exec_viz --example capacity` + +use std::{fmt::Write as _, net::SocketAddr, path::Path, time::Instant}; + +use exec_viz::{ + Backpressure, Viz, + api_types::{ActivationFrame, SeekReq, StepReq, StepUntilReq}, +}; +use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; +use trading_data_dag::{Fidelity, Fire, Glance, Observer as _, Plot}; + +/// spl's own, off its `cost.json`: one replayed trading day of BTC book + trades. +const TICKS_PER_DAY: usize = 159_210; +const DAYS: usize = 2; +/// Where a reader's own graph lands is what [`Viz::bytes`] is exported for; this is the one charted. +const GLANCE_BYTES_PER_TICK: usize = 106; +/// spl's `SCROLLBACK` sits third, so the table has a row that is the number in use rather than only +/// powers of two around it. +const CAPS: [usize; 5] = [2_048, 8_192, 20_000, 65_536, 262_144]; +/// Frames per latency reading, parked across the middle of the tape — where a quiet node's +/// carry-forward scan is longest, which is what the reading is about. +const SAMPLES: usize = 64; +const BAR: usize = 44; + +/// A minute of venue time in ticks, at spl's density — the unit the bar analogues are spaced by. +const MIN: usize = TICKS_PER_DAY / 1440; +/// The book node carries the whole per-tick face budget on its own: spl spreads it over four that +/// all fire on nearly every tick, and what the tape holds is the sum either way. +const NODES: [Node; 5] = [ + Node { + name: "Book", + period: 1, + face: GLANCE_BYTES_PER_TICK, + dims: &[4], + }, + Node { + name: "Screen", + period: 100, + face: 24, + dims: &[3], + }, + Node { + name: "Bar:1m", + period: MIN, + face: 24, + dims: &[5], + }, + Node { + name: "Bar:5m", + period: 5 * MIN, + face: 24, + dims: &[5], + }, + Node { + name: "Bar:1h", + period: 60 * MIN, + face: 24, + dims: &[5], + }, +]; +const CARD: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; +const BEGIN: &str = ""; +const END: &str = ""; +fn main() { + // SAFETY: the process is still single-threaded — the runtime below spawns the first thread, and + // the tape thread comes later still. `serve_on` wants a built front-end and a sweep has no use for + // one; every route it asks for answers JSON off the tape. + unsafe { std::env::set_var("EXEC_VIZ_WEB_DIR", std::env::temp_dir()) }; + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("a current-thread runtime asks nothing of the system") + .block_on(sweep()); +} +/// A node of the synthetic mix: fires every `period` ticks, rendering `face` bytes when it does. +struct Node { + name: &'static str, + period: usize, + face: usize, + dims: &'static [usize], +} + +/// One node's card face. Only its width is a measurement — the tape stores the rendering, not the +/// value — so every node renders a slice of one string. +struct Face(&'static str); +impl Glance for Face { + fn glance(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str(self.0) + } +} + +/// One sweep point. +struct Row { + cap: usize, + retained: usize, + bytes: usize, + seek_us: f64, + /// Fires still reachable by `step_until`, positional with [`NODES`]. + reach: Vec, +} + +async fn sweep() { + let ticks = TICKS_PER_DAY * DAYS; + let fires: Vec = NODES.iter().map(|n| ticks.div_ceil(n.period)).collect(); + let mut rows = Vec::new(); + let mut hop_us = 0.0; + for cap in CAPS { + let viz = record(cap, ticks); + let bytes = viz.bytes(); + let listener = Viz::bind(0).await; + let addr = listener.local_addr().expect("a bound listener has an address"); + // Structured: the server future never returns, so `select!` ends exactly when the readings do + // and drops it — no detached task outliving the measurement it was for. + let row = tokio::select! { + () = viz.serve_on(listener) => unreachable!("axum::serve returns only on an error it panics on"), + (row, hop) = read(addr, cap, bytes, ticks) => { hop_us = hop; row } + }; + eprintln!("capacity {cap}: {} retained, {:.1} MB, {:.0}µs", row.retained, row.bytes as f64 / 1e6, row.seek_us); + rows.push(row); + } + + let out = render(&rows, &fires, ticks, hop_us); + print!("{out}"); + let docs = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../docs")); + // Outside `.readme_assets/`: readme-fw warns on every file in there it does not know how to + // assemble, and this is the raw artifact, not a section. + std::fs::write(docs.join("capacity.txt"), &out).expect("write capacity.txt"); + splice(&docs.join(".readme_assets/other.md"), &out); +} + +/// The whole run through the real recorder, sealed — so what is served afterwards is what the +/// thinning passes left, not a tape still being written. +fn record(cap: usize, ticks: usize) -> Viz { + let (viz, mut rec) = Viz::new(None, cap, 60_000, Backpressure::Block); + for i in 0..ticks { + let mut r = rec.at(i as i64 * 1_000_000_000); + for n in &NODES { + let vals = [1.0, 2.0, 3.0, 4.0, 5.0]; + r.on( + n.name, + &[], + &[], + Fire { + glance: &Face(&CARD[..n.face]), + dims: n.dims, + plots: &[Plot::DEFAULT], + clock: None, + fidelity: Fidelity::Exact, + fires: 1, + vals: (i % n.period == 0).then(|| &vals[..n.dims[0]]), + dep_dims: &[], + jac: None, + exact_block: None, + exact: false, + formula: None, + deriv: None, + trace: None, + }, + ); + } + } + rec.seal(); + viz +} + +/// Every reading that is a replay op, taken over the served tape. Hands back the row and the bare +/// loopback round trip the latency in it should be read against. +async fn read(addr: SocketAddr, cap: usize, bytes: usize, ticks: usize) -> (Row, f64) { + let mut api = Api::connect(addr).await; + + // `step(n)` from the front parks at position `min(n, last)`, so the smallest `n` that reaches the + // end names how many ticks the passes left — the one number the wire does not carry outright. + let end = { + api.seek(0).await; + api.step(usize::MAX).await.tick + }; + let (mut lo, mut hi) = (0usize, cap); + while lo < hi { + let mid = lo.midpoint(hi); + api.seek(0).await; + match api.step(mid).await.tick == end { + true => hi = mid, + false => lo = mid + 1, + } + } + let retained = lo + 1; + + let mut hop = Vec::with_capacity(SAMPLES); + for _ in 0..SAMPLES { + let began = Instant::now(); + api.topology().await; + hop.push(began.elapsed()); + } + let mut seek = Vec::with_capacity(SAMPLES); + for i in 0..SAMPLES { + let began = Instant::now(); + // Walking rather than repeating one tick: nothing is cached, but a moving cursor is what the + // reading is about, and a standing one invites the question. + api.seek(ticks / 2 + i).await; + seek.push(began.elapsed()); + } + + // A scan reports whether it reached anything, so the walk ends on the tape saying so rather than + // on a cursor that stopped moving. + let mut reach = Vec::new(); + for n in &NODES { + let start = api.seek(0).await; + let mut hits = usize::from(start.activations.iter().any(|a| a.node == n.name && a.fired)); + //LOOP: bounded by the retained fires of `n`, which is what it is counting. + while api.step_until(n.name).await.found { + hits += 1; + } + reach.push(hits); + } + ( + Row { + cap, + retained, + bytes, + seek_us: median(seek), + reach, + }, + median(hop), + ) +} + +/// Median rather than mean: one scheduler hiccup over a loopback socket is not the tape's cost. +fn median(mut took: Vec) -> f64 { + took.sort_unstable(); + took[took.len() / 2].as_secs_f64() * 1e6 +} + +fn render(rows: &[Row], fires: &[usize], ticks: usize, hop_us: f64) -> String { + let mut s = String::new(); + let per_tick = NODES.iter().map(|n| n.face as f64 / n.period as f64).sum::(); + let w = |s: &mut String, line: std::fmt::Arguments<'_>| s.write_fmt(line).expect("`String`'s `Write` is infallible"); + w( + &mut s, + format_args!( + "{ticks} ticks ({DAYS} days at spl's {TICKS_PER_DAY}/day), {} nodes, {per_tick:.0} B/tick of card faces\n", + NODES.len() + ), + ); + w(&mut s, format_args!("fires over the run:")); + for (n, f) in NODES.iter().zip(fires) { + w(&mut s, format_args!(" {}={f}", n.name)); + } + s.push_str("\n\n"); + + let mut chart = |title: std::fmt::Arguments<'_>, val: &dyn Fn(&Row) -> f64, note: &dyn Fn(&Row, f64) -> String| { + w(&mut s, title); + let max = rows.iter().map(val).fold(0.0f64, f64::max); + for r in rows { + let v = val(r); + let bar = ((v / max) * BAR as f64).round() as usize; + w(&mut s, format_args!(" {:>7} │{:▬7} {:>9}", "capacity", "retained")); + for n in &NODES { + w(&mut s, format_args!(" {:>13}", n.name)); + } + s.push('\n'); + for r in rows { + w(&mut s, format_args!(" {:>7} {:>9}", r.cap, r.retained)); + for (hits, all) in r.reach.iter().zip(fires) { + w(&mut s, format_args!(" {:>13}", format!("{hits}/{all}"))); + } + s.push('\n'); + } + s +} + +/// Splices the block into the hand-written prose, so the prose can say "measured" and mean it. +fn splice(at: &Path, out: &str) { + let md = std::fs::read_to_string(at).expect("other.md is this crate's, and checked in"); + let (head, rest) = md.split_once(BEGIN).unwrap_or_else(|| panic!("{} has no {BEGIN} marker", at.display())); + let (_, tail) = rest.split_once(END).unwrap_or_else(|| panic!("{} has no {END} marker", at.display())); + std::fs::write(at, format!("{head}{BEGIN}\n```\n{out}```\n{END}{tail}")).expect("write other.md"); +} + +/// The browser's door, over one keep-alive connection: the replay ops are the tape's own and this +/// crate exports none of them, which is exactly the position a consumer measuring their own graph is +/// in. Hand-rolled rather than an HTTP client dependency — every request here is a fixed-shape one +/// to a loopback socket, and the sweep issues tens of thousands of them. +struct Api { + sock: tokio::net::TcpStream, + buf: Vec, +} + +impl Api { + async fn connect(addr: SocketAddr) -> Self { + let sock = tokio::net::TcpStream::connect(addr).await.expect("the server bound the address being asked for"); + sock.set_nodelay(true).expect("a connected TCP socket takes TCP_NODELAY"); + Self { sock, buf: Vec::new() } + } + + async fn seek(&mut self, tick: usize) -> ActivationFrame { + self.post("seek", &SeekReq { tick }).await + } + + async fn step(&mut self, n: usize) -> ActivationFrame { + self.post("step", &StepReq { n }).await + } + + async fn step_until(&mut self, node: &str) -> ActivationFrame { + self.post("step_until", &StepUntilReq { node: node.into() }).await + } + + /// Read for its cost and not its answer: the cheapest handler there is, so what it prices is the + /// socket rather than the tape. + async fn topology(&mut self) { + self.send("GET /api/topology HTTP/1.1\r\nHost: t\r\n\r\n").await; + self.recv().await; + } + + async fn post(&mut self, route: &str, body: &impl serde::Serialize) -> ActivationFrame { + let body = serde_json::to_string(body).expect("a request shape serializes"); + let req = format!( + "POST /api/{route} HTTP/1.1\r\nHost: t\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ); + self.send(&req).await; + let body = self.recv().await; + serde_json::from_slice(&body).unwrap_or_else(|e| panic!("/api/{route} answered {}: {e}", String::from_utf8_lossy(&body))) + } + + async fn send(&mut self, req: &str) { + self.sock.write_all(req.as_bytes()).await.expect("the served tape outlives the sweep reading it"); + } + + /// Length-delimited: axum states `content-length` on every response asked for here, so there is no + /// chunked case to carry. + async fn recv(&mut self) -> Vec { + //LOOP: both are bounded by the response the server has already committed to sending. + let head = loop { + if let Some(i) = self.buf.windows(4).position(|w| w == b"\r\n\r\n") { + break i + 4; + } + self.fill().await; + }; + let len: usize = std::str::from_utf8(&self.buf[..head]) + .expect("HTTP headers are ASCII") + .to_ascii_lowercase() + .split_once("content-length: ") + .and_then(|(_, rest)| rest.split_once("\r\n")) + .expect("axum length-delimits every response this asks for") + .0 + .parse() + .expect("a decimal length"); + while self.buf.len() < head + len { + self.fill().await; + } + let body = self.buf[head..head + len].to_vec(); + self.buf.drain(..head + len); + body + } + + async fn fill(&mut self) { + let was = self.buf.len(); + self.buf.resize(was + 16 * 1024, 0); + let n = self.sock.read(&mut self.buf[was..]).await.expect("read the response the server committed to"); + assert!(n > 0, "the server closed the connection mid-sweep"); + self.buf.truncate(was + n); + } +} diff --git a/exec_viz/src/api_types.rs b/exec_viz/src/api_types.rs index 832e904..61aa5fd 100644 --- a/exec_viz/src/api_types.rs +++ b/exec_viz/src/api_types.rs @@ -156,6 +156,13 @@ pub struct ActivationFrame { pub dropped: usize, /// This op ran out of recorded ticks — re-issuing it later will get further. pub pending: bool, + /// The scan this frame answers reached what it was looking for. `true` for every op that is not + /// a scan, so a `false` here is a search that walked to the end of a sealed recording and found + /// nothing — which without saying so reads as a dead key. + pub found: bool, + /// Absolute ticks this retained tick stands for: its distance from the previous retained one, so + /// `1` is a contiguous stretch and anything larger is the resolution thinning has left here. + pub gap: usize, pub ts_ns: i64, pub activations: Vec, } diff --git a/exec_viz/src/cost.rs b/exec_viz/src/cost.rs index acfb407..e273579 100644 --- a/exec_viz/src/cost.rs +++ b/exec_viz/src/cost.rs @@ -30,7 +30,7 @@ pub(crate) const TICK_STRIDE: usize = 64; const WARM: f64 = 8.0; const WARM_GAIN: f64 = 0.3; -#[derive(Default)] +#[derive(Clone, Default, serde::Deserialize, serde::Serialize)] pub(crate) struct Cost { block_n: usize, block_min: f64, diff --git a/exec_viz/src/lib.rs b/exec_viz/src/lib.rs index d2f45d7..d228a70 100644 --- a/exec_viz/src/lib.rs +++ b/exec_viz/src/lib.rs @@ -37,4 +37,6 @@ mod server; #[cfg(feature = "server")] mod tape; #[cfg(feature = "server")] +pub use server::web_dir; +#[cfg(feature = "server")] pub use tape::{Backpressure, Rec, Recorder, Viz}; diff --git a/exec_viz/src/record.rs b/exec_viz/src/record.rs index d0f747c..187c1d8 100644 --- a/exec_viz/src/record.rs +++ b/exec_viz/src/record.rs @@ -8,6 +8,8 @@ use serde::{Deserialize, Serialize}; /// A run dir is `runs/{run_id}/` where `run_id = {version}_{config_hash}` — collision-proof /// across logic and config versions. pub const RUNS_DIR: &str = "runs"; +/// One situation's saved [`Viz`](crate::Viz) tape — see [`Viz::save`](crate::Viz::save). +pub const TAPE_FILE: &str = "tape.bin"; pub const ORDERS_FILE: &str = "orders.parquet"; pub const FILLS_FILE: &str = "fills.parquet"; pub const DRAWINGS_FILE: &str = "drawings.parquet"; diff --git a/exec_viz/src/server.rs b/exec_viz/src/server.rs index 41ff09c..3498a58 100644 --- a/exec_viz/src/server.rs +++ b/exec_viz/src/server.rs @@ -34,7 +34,7 @@ impl Viz { // Dev study tool relaunched constantly: `no-store` everywhere so a cached asset can't // silently break against a new API shape. All payloads here are small. let no_store = SetResponseHeaderLayer::overriding(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); - let web = web_dir(); + let web = web_dir().expect(UNSET); let app = Router::new() .route("/api/topology", get(topology)) .route("/api/day", get(day)) @@ -55,10 +55,14 @@ impl Viz { } } +const UNSET: &str = "EXEC_VIZ_WEB_DIR: point it at a `dx build -p exec_viz_web` bundle"; + /// Root of a built `exec_viz_web` bundle. The app supplies it — this crate ships no front-end, and -/// guessing at a path inside its own checkout is how a stale bundle gets served silently. -fn web_dir() -> PathBuf { - PathBuf::from(std::env::var_os("EXEC_VIZ_WEB_DIR").expect("EXEC_VIZ_WEB_DIR: point it at a `dx build -p exec_viz_web` bundle")) +/// guessing at a path inside its own checkout is how a stale bundle gets served silently. `None` +/// rather than a panic so an app that records with a UI when there is one, and without when there +/// is not, can ask instead of reading this crate's env var behind its back. +pub fn web_dir() -> Option { + std::env::var_os("EXEC_VIZ_WEB_DIR").map(PathBuf::from) } async fn topology(State(v): State) -> impl IntoResponse { @@ -101,7 +105,7 @@ async fn index(method: axum::http::Method) -> impl IntoResponse { if method != axum::http::Method::GET { return (StatusCode::NOT_FOUND, format!("no such route for {method}")).into_response(); } - let path = web_dir().join("index.html"); + let path = web_dir().expect(UNSET).join("index.html"); match tokio::fs::read_to_string(&path).await { Ok(s) => Html(s).into_response(), Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("read {}: {e}", path.display())).into_response(), diff --git a/exec_viz/src/tape.rs b/exec_viz/src/tape.rs index 4771ce2..ff4f62c 100644 --- a/exec_viz/src/tape.rs +++ b/exec_viz/src/tape.rs @@ -9,10 +9,15 @@ //! The two halves do not share a thread. The graph's leg of a fire is one `Glance` appended to a //! recycled column plus one channel push; naming the topology, bucketing the series, thinning and //! the cost statistics all happen on the tape thread, off the trading core. +//! +//! Storage, though, need not be memory: [`Viz::save`] writes the tape down and [`Viz::load`] reads +//! one back, so a run can be looked at after the process that recorded it is gone. use std::{ collections::{HashSet, VecDeque}, fmt::Write as _, + io::{BufReader, BufWriter, Read as _, Write as _}, + path::Path, sync::{ Arc, Mutex, MutexGuard, atomic::{AtomicUsize, Ordering}, @@ -22,6 +27,7 @@ use std::{ time::Instant, }; +use serde::{Deserialize, Serialize}; use trading_data_dag::{Fidelity, Fire, Ink, Observer, Plot, Want}; use crate::{ @@ -33,6 +39,13 @@ use crate::{ /// the one O(capacity) thing the consumer does — is absorbed rather than reflected back at the feed. const QUEUE: usize = 1024; +/// What a tape file opens with, so a file that is not one is refused before it is decoded. +const TAPE_MAGIC: [u8; 8] = *b"EXECVIZT"; +/// The layout of everything after the header. Node names are `type_name` strings and so build-local, +/// but their arrangement is this crate's — bump on any change to [`Acts`], [`Tick`] or [`TapeFile`]. +/// Tagging with the build's commit instead would orphan every tape on an unrelated one. +const TAPE_SCHEMA: u32 = 2; + /// What a full handoff queue means for the tick being recorded. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Backpressure { @@ -46,7 +59,12 @@ pub enum Backpressure { } #[derive(Clone)] -pub struct Viz(Arc>); +pub struct Viz { + tape: Arc>, + /// The tape thread, joinable from the read side: the one recorder is often swallowed by whatever + /// the app hands it to, and then nobody is left holding a [`Recorder::seal`] to wait on. + join: Arc>>>, +} impl Viz { /// `price_node` names an OHLCV node — its recorded series *is* the candle pane, and it is skipped @@ -61,20 +79,24 @@ impl Viz { pub fn new(price_node: Option<&'static str>, capacity: usize, bucket_ms: i64, mode: Backpressure) -> (Self, Recorder) { assert!(capacity > 3 && bucket_ms > 0); let dropped = Arc::new(AtomicUsize::new(0)); - let viz = Self(Arc::new(Mutex::new(Tape { - price_node: price_node.map(str::to_string), - capacity, - bucket_ms, - topology: Vec::new(), - cost: Vec::new(), - ticks: VecDeque::new(), - opened: 0, - stride: 1, - sealed: false, - dropped: dropped.clone(), - series: Vec::new(), - cursor: 0, - }))); + let viz = Self { + tape: Arc::new(Mutex::new(Tape { + price_node: price_node.map(str::to_string), + capacity, + bucket_ms, + topology: Vec::new(), + cost: Vec::new(), + ticks: VecDeque::new(), + opened: 0, + fires: Vec::new(), + keep: Vec::new(), + sealed: false, + dropped: dropped.clone(), + series: Vec::new(), + cursor: 0, + })), + join: Arc::new(Mutex::new(None)), + }; let (tx, rx) = sync_channel(QUEUE); // A thinning pass keeps the newest half whole, so it can never free more than `capacity / 2` at // once and a return channel that deep takes any one pass entire. At [`QUEUE`] it took a seventh @@ -93,12 +115,13 @@ impl Viz { tape.lock().sealed = true; }) .expect("spawn the tape thread"); + *viz.join.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(join); ( - viz, + viz.clone(), Recorder { tx, recycle, - join, + viz, mode, raw: Vec::new(), meta: None, @@ -114,10 +137,103 @@ impl Viz { ) } + /// What the retained ticks cost in memory, allocations included — the reading `capacity` is + /// actually bought with. Exported because the README's advice is measured against one synthetic + /// graph, and this is what lets it be re-measured against yours; `exec_viz`'s own `capacity` + /// example is the first such reader. + /// + /// The per-node chart series and the topology are not in it: neither is bounded by `capacity`. + pub fn bytes(&self) -> usize { + let t = self.lock(); + t.ticks.iter().map(Tick::bytes).sum() + } + + /// Blocks until the recording is over — every recorder dropped or sealed, every handed-off tick + /// absorbed — then writes the tape. What lands is what the tape held: a thinned run saves thinned, + /// because that is the recording. + pub fn save(&self, path: impl AsRef) -> std::io::Result<()> { + self.wait(); + let t = self.lock(); + // What is *addressable*, not what is held: a `total` naming a tick the file does not carry + // would be a tape that reads as truncated mid-walk rather than as one that ends. + let last = t.last(); + let file = TapeFile { + price_node: t.price_node.clone(), + capacity: t.capacity, + bucket_ms: t.bucket_ms, + topology: t.topology.clone(), + cost: t.cost.clone(), + ticks: t.ticks.iter().take(last.map_or(0, |l| l + 1)).cloned().collect(), + opened: t.head(), + fires: t.fires.clone(), + keep: t.keep.clone(), + dropped: t.dropped.load(Ordering::Relaxed), + series: t.series.clone(), + cursor: t.cursor, + }; + + let mut w = BufWriter::new(std::fs::File::create(path)?); + w.write_all(&TAPE_MAGIC)?; + w.write_all(&TAPE_SCHEMA.to_le_bytes())?; + rmp_serde::encode::write(&mut w, &file).map_err(std::io::Error::other)?; + w.flush() + } + + /// A tape read back. Sealed by definition — a file does not grow — so there is no [`Recorder`] + /// and every replay op is addressable from the first request. + pub fn load(path: impl AsRef) -> std::io::Result { + let path = path.as_ref(); + let mut r = BufReader::new(std::fs::File::open(path)?); + let mut magic = [0u8; 8]; + r.read_exact(&mut magic)?; + if magic != TAPE_MAGIC { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, format!("{} is not an exec_viz tape", path.display()))); + } + let mut schema = [0u8; 4]; + r.read_exact(&mut schema)?; + let schema = u32::from_le_bytes(schema); + if schema != TAPE_SCHEMA { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("{} is a schema-{schema} tape and this build reads schema {TAPE_SCHEMA} — re-record it", path.display()), + )); + } + let file: TapeFile = rmp_serde::decode::from_read(&mut r).map_err(std::io::Error::other)?; + + Ok(Self { + tape: Arc::new(Mutex::new(Tape { + price_node: file.price_node, + capacity: file.capacity, + bucket_ms: file.bucket_ms, + topology: file.topology, + cost: file.cost, + ticks: file.ticks.into(), + opened: file.opened, + fires: file.fires, + keep: file.keep, + sealed: true, + dropped: Arc::new(AtomicUsize::new(file.dropped)), + series: file.series, + cursor: file.cursor, + })), + join: Arc::new(Mutex::new(None)), + }) + } + + /// Joins the tape thread, which ends when the last recorder's handoff is closed and drained. The + /// guard is held across the join so a second caller waits rather than racing past a recording that + /// is not over yet; a caller after that finds the slot empty and returns. + fn wait(&self) { + let mut slot = self.join.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(join) = slot.take() { + join.join().expect("the tape thread only ends by running out of ticks"); + } + } + pub(crate) fn lock(&self) -> MutexGuard<'_, Tape> { // Served concurrently with the recording it describes: a panicking handler must not cost the // run its tape. Every op leaves the tape consistent, so the inner value is still readable. - self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner) + self.tape.lock().unwrap_or_else(std::sync::PoisonError::into_inner) } } @@ -128,7 +244,8 @@ pub struct Recorder { /// Drained columns coming back from the tape with their capacities intact, which is what makes a /// fire's rendering a memcpy rather than an allocation. recycle: Receiver, - join: JoinHandle<()>, + /// Only ever waited on — see [`Recorder::seal`]. + viz: Viz, mode: Backpressure, /// The stepped nodes' names, positional. The per-fire step-order check compares against this, and /// its length is what says a node is new and still owes its [`Meta`]. @@ -148,7 +265,6 @@ pub struct Recorder { idx: usize, timed: bool, } - impl Recorder { /// Opens a tick and hands back the observer for it: /// `graph.tick_obs(ts, batches, &mut recorder.at(ts))`. Dropping the returned [`Rec`] — at the end @@ -176,15 +292,33 @@ impl Recorder { /// and `total` stops growing. By value, so the handle you recorded through is spent. A live feed /// never calls this — dropping the recorder says the same thing without the wait. pub fn seal(self) { - let Recorder { tx, join, .. } = self; + let Recorder { tx, viz, .. } = self; drop(tx); - join.join().expect("the tape thread only ends by running out of ticks"); + viz.wait(); } } /// One opened tick's observer. Everything it writes goes into the recorder's recycled buffers; the /// tick crosses to the tape thread when this drops. pub struct Rec<'a>(&'a mut Recorder); +/// [`Tape`]'s persisted fields. Separate rather than serialized in place because two of the tape's +/// are not data: `dropped` is shared with a recorder that no longer exists on the read-back side, and +/// `sealed` is what a file is. +#[derive(Deserialize, Serialize)] +struct TapeFile { + price_node: Option, + capacity: usize, + bucket_ms: i64, + topology: Vec, + cost: Vec, + ticks: Vec, + opened: usize, + fires: Vec, + keep: Vec, + dropped: usize, + series: Vec, + cursor: usize, +} impl Observer for Rec<'_> { /// A Jacobian is read by exactly one thing — [`Tape::frame`], for the single tick a client is @@ -307,7 +441,7 @@ struct TickMsg { /// keeps it by column: a per-node `String` and two `Vec`s were three heap pointers each and the tape /// holds `capacity` ticks of them. Step order is fixed and asserted, so the columns are appended /// front to back and a node is a set of ends into each. -#[derive(Default)] +#[derive(Clone, Default, Deserialize, Serialize)] struct Acts { outs: String, vals: Vec, @@ -357,7 +491,7 @@ impl Acts { } } -#[derive(Clone, Copy, Default)] +#[derive(Clone, Copy, Default, Deserialize, Serialize)] struct Ends { out: u32, vals: u32, @@ -377,11 +511,29 @@ struct ActRef<'a> { exact: bool, } +#[derive(Clone, Deserialize, Serialize)] struct Tick { /// Index among *all* ticks ever opened, so a tick's id survives every thinning pass. abs: usize, ts_ns: i64, acts: Acts, + /// What [`Tape::thin`] decides by, positional with `topology`: `0` where the node did not fire, + /// else `1 + trailing_zeros` of its 0-based fire ordinal. So "keep every `2^k`-th fire of node + /// `i`" is the single comparison `ranks[i] > k`, the kept sets nest as `k` grows, and a node's + /// very first fire (ordinal 0, and the saturating rank that gives) survives every `k`. + /// + /// It rides here and not on [`Acts`] because those buffers are the graph thread's, recycled + /// across the handoff; the ordinal it counts is the tape's. + ranks: Vec, +} +impl Tick { + /// Capacities rather than lengths: the columns arrive from the recycle channel already grown, and + /// what a tick occupies is what it holds onto. + fn bytes(&self) -> usize { + let a = &self.acts; + let col = a.outs.capacity() + (a.vals.capacity() + a.jac.capacity() + a.block.capacity()) * size_of::(); + size_of::() + col + a.widths.capacity() * size_of::() + a.exact.capacity() + a.ends.capacity() * size_of::() + self.ranks.capacity() + } } pub(crate) struct Tape { @@ -395,8 +547,11 @@ pub(crate) struct Tape { ticks: VecDeque, /// Ticks ever absorbed, thinned-away ones included. opened: usize, - /// Spacing of the retained ticks outside the whole-kept tail; a power of two. - stride: usize, + /// Per-node fire count so far, positional with `topology` — what [`Tick::ranks`] is read off. + fires: Vec, + /// Per-node "keep one fire in `2^keep[i]`", positional with `topology` and only ever raised — + /// see [`Tape::thin`]. + keep: Vec, /// The recording is over — see [`Tape::head`]. sealed: bool, /// The recorder's drop tally, shared — see [`Recorder::dropped`]. @@ -437,6 +592,8 @@ impl Tape { }); self.topology.push(topo); self.cost.push(Cost::default()); + self.fires.push(0); + self.keep.push(0); } if let Some(spans) = spans { assert_eq!(spans.len(), self.cost.len(), "a clocked tick clocks every node in it"); @@ -447,8 +604,13 @@ impl Tape { let ms = ts_ns / 1_000_000; let bucket = ms - ms.rem_euclid(self.bucket_ms); + let mut ranks = vec![0u8; self.series.len()]; for (i, s) in self.series.iter_mut().enumerate() { let Some(vals) = acts.get(i).and_then(|a| a.vals) else { continue }; + // Saturated so that ordinal 0 — whose `trailing_zeros` is the word width — outranks every + // `keep`, which is what keeps the front of a long recording addressable. + ranks[i] = 1 + self.fires[i].trailing_zeros().min(63) as u8; + self.fires[i] += 1; match s.points.last_mut() { // `>=`, not `==`: a feed's timestamps do go backwards (a coarse lane landing on an exact // hour boundary weaves ahead of the tape around it), and one non-ascending point makes @@ -465,29 +627,58 @@ impl Tape { debug_assert!(self.ticks.len() < self.capacity); let abs = self.opened; self.opened += 1; - self.ticks.push_back(Tick { abs, ts_ns, acts }); + self.ticks.push_back(Tick { abs, ts_ns, acts, ranks }); freed } - /// What the buffer keeps: the newest `capacity / 2` ticks whole, plus every `stride`-th tick over - /// everything before them. So the freshest stretch is still tick-exact while the run stays - /// walkable end to end — dropping the front instead, as a plain ring does, makes the beginning - /// of a long recording unreachable for the rest of the run. + /// What the buffer keeps: the newest `capacity / 2` ticks whole, plus — over everything before + /// them — every tick some node fired on at a rank the squeeze has not yet reached. So the + /// freshest stretch is still tick-exact while the run stays walkable end to end; dropping the + /// front instead, as a plain ring does, makes the beginning of a long recording unreachable for + /// the rest of the run. + /// + /// Decimating by tick index would be proximity to the buffer rather than to the problem: what a + /// human scrubs a tape for is the rare event, and a fixed stride destroys precisely those — a + /// 5-minute bar firing 288 times a day survives a stride of 64 nine times. So the squeeze is + /// max-min fair instead: raise the greediest node's exponent until the pre-tail union fits, and + /// a node that never dominates never loses a fire. /// - /// `stride` only ever doubles, so each pass keeps a subset of what the last one did, and each - /// leaves a quarter of the buffer free — one O(capacity) pass per `capacity / 4` ticks. + /// `keep` only ever rises, so each pass keeps a subset of what the last one did, and each leaves + /// a quarter of the buffer free — one O(capacity) pass per `capacity / 4` ticks. /// /// The dropped ticks' act buffers go back to the recorder rather than being freed here. fn thin(&mut self) -> Vec { - while self.opened / self.stride > self.capacity / 4 { - self.stride *= 2; - } let whole = self.opened.saturating_sub(self.capacity / 2); - let stride = self.stride; + let pre = self.ticks.iter().take_while(|t| t.abs < whole); + let mut counts = vec![0usize; self.keep.len()]; + // ponytail: recounts rather than tracking retained counts incrementally — it runs once per + // `capacity / 4` ticks and past the first pass converges in zero or one iterations. + //LOOP: each iteration halves one node's share of the backbone, so the union strictly falls. + loop { + counts.iter_mut().for_each(|c| *c = 0); + let mut union = 0; + for t in pre.clone() { + let mut any = false; + for (i, &r) in t.ranks.iter().enumerate() { + if r > self.keep[i] { + counts[i] += 1; + any = true; + } + } + union += usize::from(any); + } + if union <= self.capacity / 4 { + break; + } + let (i, n) = counts.iter().enumerate().max_by_key(|(_, n)| **n).expect("a non-empty union came from some node"); + assert!(*n > 0, "the union counts ticks no node claims"); + self.keep[i] += 1; + } + let mut freed = Vec::new(); let mut kept = VecDeque::with_capacity(self.ticks.len()); for t in self.ticks.drain(..) { - match t.abs >= whole || t.abs % stride == 0 { + match t.abs >= whole || t.ranks.iter().zip(&self.keep).any(|(r, k)| r > k) { true => kept.push_back(t), false => freed.push(t.acts), } @@ -560,6 +751,10 @@ impl Tape { sealed: self.sealed, dropped: self.dropped.load(Ordering::Relaxed), pending: false, + found: true, + // At the buffer's front there is no previous retained tick, so what it stands for is + // everything from the start of the run — which for an unthinned front is the `1` it reads as. + gap: tick.map_or(1, |(p, t)| t.abs + 1 - p.checked_sub(1).map_or(0, |q| self.ticks[q].abs + 1)), ts_ns: tick.map_or(0, |(_, t)| t.ts_ns), activations: tick.map_or_else(Vec::new, |(p, t)| { self.topology @@ -631,7 +826,9 @@ impl Tape { pub(crate) fn step_until(&mut self, node: &str) -> ActivationFrame { match self.topology.iter().position(|n| n.node == node) { Some(i) => self.scan(|t| t.acts.get(i).is_some_and(|a| a.vals.is_some())), - None => self.frame(), + // A name the graph does not carry is still a search that reached nothing — `c` pressed before + // the run has a `Classify` reads the same to the user as one that never fires again. + None => ActivationFrame { found: false, ..self.frame() }, } } @@ -651,6 +848,11 @@ impl Tape { }) } + /// A search that reaches the end of a *sealed* recording without a hit leaves the cursor alone: + /// there is no further Δ to walk to, and parking at `last` would answer a failed search by + /// teleporting the user to the end of the run. While the tape is still growing `last` *is* the + /// resume point — [`crate::api_types::ActivationFrame::pending`] says the op will be re-issued + /// from there — so there it parks. fn scan(&mut self, hit: impl Fn(&Tick) -> bool) -> ActivationFrame { let mut found = false; if let (Some(mut p), Some(last)) = (self.pos(), self.last()) { @@ -661,10 +863,13 @@ impl Tape { break; } } - self.park(p); + if found || !self.sealed { + self.park(p); + } } let mut f = self.frame(); f.pending = !self.sealed && !found; + f.found = found; f } } @@ -820,19 +1025,124 @@ mod tests { rec.at(i * 60 * 1_000_000_000).on("N", &[], &[], fire(&[i as f64])); } rec.seal(); + let walk = walk(&viz); + assert_eq!(walk.first(), Some(&1), "the recording's first tick is addressable"); + assert_eq!(walk.last(), Some(&5000), "and so is its last: {walk:?}"); + assert!(walk.windows(2).all(|w| w[0] < w[1]), "no step stands still: {walk:?}"); + // The freshest stretch is kept whole, so stepping through it moves one tick at a time. + assert!(walk.windows(2).rev().take(8).all(|w| w[1] - w[0] == 1), "{walk:?}"); + } + + /// The reported bug: thinning by tick index keeps ticks at fixed absolute positions, so a node + /// that fires rarely loses its fires to the stride — spl's 5-minute bar fired 576 times over the + /// window and 9 of them stayed addressable. Thinning by *fire* rank, the squeeze lands on the + /// node that can afford it. + #[test] + fn a_rare_node_keeps_its_fires_past_the_capacity() { + const RARE: usize = 500; + const TICKS: usize = 200_000; + // `B`'s whole run has to fit under the backbone ceiling for "keeps every fire" to be a thing the + // tape can offer at all — 400 fires against 1024, the same order of headroom spl's 5-minute bar + // has (576 fires against 5000). + let (viz, mut rec) = Viz::new(None, 4096, 60_000, Backpressure::Block); + for i in 0..TICKS { + let mut r = rec.at(i as i64 * 60 * 1_000_000_000); + r.on("A", &[], &[], fire(&[i as f64])); + // Two `on`s or one is what says a node fired, so `B`'s quiet ticks report nothing at all. + r.on( + "B", + &["A"], + &[false], + Fire { + vals: (i % RARE == 0).then_some(&[1.0]), + ..fire(&[1.0]) + }, + ); + } + rec.seal(); + let mut t = viz.lock(); - assert_eq!(t.seek(0).tick, 1, "the recording's first tick is addressable"); - let mut walk = vec![t.frame().tick]; + t.seek(0); + let mut reached = vec![t.frame().tick - 1]; + //LOOP: walks B's fires; `step_until` stands still once there are none left, which ends it. + loop { + let at = t.step_until("B").tick - 1; + if at == *reached.last().expect("seeded") { + break; + } + reached.push(at); + } + let want: Vec = (0..TICKS).step_by(RARE).collect(); + assert_eq!(reached, want, "every one of B's {} fires is addressable", want.len()); + } + + /// A search is not a seek: reaching the end of a sealed recording without a hit used to park the + /// cursor at that end, so a mistyped node name threw away where the user was reading. + #[test] + fn a_scan_that_finds_nothing_stays_put() { + let (viz, mut rec) = Viz::new(None, 64, 60_000, Backpressure::Block); + for i in 0..500 { + rec.at(i * 60 * 1_000_000_000).on("N", &[], &[], fire(&[i as f64])); + } + rec.seal(); + + let mut t = viz.lock(); + let was = t.seek(300).tick; + let f = t.step_until("Absent"); + assert_eq!(f.tick, was, "a search for a node the graph does not carry moved the cursor"); + assert!(!f.found, "and it reported as though it had reached one"); + // `N` fires every tick, so the one op that *is* a scan with nothing left to find is a scan + // started from the last tick. + t.seek(usize::MAX); + let end = t.frame().tick; + let f = t.step_until("N"); + assert_eq!(f.tick, end); + assert!(!f.found && !f.pending, "a sealed tape with no hit is an answer, not a wait: {f:?}"); + } + + /// A tape read back is the tape that was recorded. Past the capacity on purpose: what survives a + /// save is what the thinning passes left, so the walk is the one thing that can say the file holds + /// the same recording rather than merely the same ticks. + #[test] + fn a_saved_tape_reads_back_as_the_one_recorded() { + let (viz, mut rec) = Viz::new(Some("P"), 64, 60_000, Backpressure::Block); + for i in 0..5000 { + let mut r = rec.at(i * 60 * 1_000_000_000); + r.on( + "P", + &[], + &[], + Fire { + dims: &[5], + ..fire(&[1.0, 2.0, 0.5, i as f64, 10.0]) + }, + ); + r.on("N", &["P"], &[false], fire(&[i as f64])); + } + rec.seal(); + + let path = std::env::temp_dir().join("exec_viz_round_trip.bin"); + viz.save(&path).expect("save"); + let back = Viz::load(&path).expect("load"); + std::fs::remove_file(&path).expect("written above"); + + assert_eq!(back.lock().topology(), viz.lock().topology()); + let (was, is) = (viz.lock().day(), back.lock().day()); + assert_eq!(is.price_node, was.price_node); + assert_eq!(is.series, was.series); + assert_eq!(walk(&back), walk(&viz)); + } + + /// `seek(0)`, then `step(1)` to a standstill: every position the tape is addressable at, in order. + fn walk(viz: &Viz) -> Vec { + let mut t = viz.lock(); + let mut walk = vec![t.seek(0).tick]; loop { let tick = t.step(1).tick; if tick == *walk.last().expect("seeded") { - break; + return walk; } walk.push(tick); } - assert_eq!(*walk.last().expect("seeded"), 5000, "and so is its last: {walk:?}"); - assert!(walk.windows(2).all(|w| w[0] < w[1]), "no step stands still: {walk:?}"); - // The freshest stretch is kept whole, so stepping through it moves one tick at a time. - assert!(walk.windows(2).rev().take(8).all(|w| w[1] - w[0] == 1), "{walk:?}"); } } diff --git a/exec_viz_web/src/views.rs b/exec_viz_web/src/views.rs index cd64a86..775f707 100644 --- a/exec_viz_web/src/views.rs +++ b/exec_viz_web/src/views.rs @@ -138,6 +138,11 @@ pub fn Replay() -> Element { let growing = if f.sealed { "" } else { "+" }; rsx! { span { class: "pos", "event {f.tick}/{f.total}{growing}" } + // Past the capacity a step covers a stretch rather than a tick; saying how wide + // reads as a resolution the tape is admitting to, not as a stepper misbehaving. + if f.gap > 1 { + span { class: "pos", "×{f.gap}" } + } span { class: "pos", "{fmt_ts(f.ts_ns)}" } // A tape the run outran has holes in it; saying so is the difference between // reading a gap as a quiet market and reading it as a gap. @@ -199,6 +204,11 @@ pub fn Replay() -> Element { } } } + // `n`, `b` and `c` all scan, and a scan that walks a sealed recording to its end without a + // hit leaves the cursor where it was — which without this reads as a dead key. + if frame.as_ref().is_some_and(|f| !f.found) { + span { class: "pos warn", "nothing further" } + } span { class: if state::VIEWS().is_empty() { "btn off" } else { "btn" }, onclick: move |_| state::clear_views(),