diff --git a/doc/2026-10-17T16-30-00Z_fix_territory_view_fuel/2026-10-17T16-30-00Z_fix_territory_view_fuel.md b/doc/2026-10-17T16-30-00Z_fix_territory_view_fuel/2026-10-17T16-30-00Z_fix_territory_view_fuel.md new file mode 100644 index 0000000000..a7abd7d198 --- /dev/null +++ b/doc/2026-10-17T16-30-00Z_fix_territory_view_fuel/2026-10-17T16-30-00Z_fix_territory_view_fuel.md @@ -0,0 +1,192 @@ +# Fix: territory's view ran out of fuel with six or more seats + +See the [Phase 11 foundations plan](../../.opencode/plans/phase-11-foundations.md) and the [perf budgets record](../2026-10-17T15-30-00Z_feature_world_perf_budgets/2026-10-17T15-30-00Z_feature_world_perf_budgets.md), which measured the problem and left it open. + +## Intent + +`examples/territory` allows eight seats. Its styled view cost about 6.5M fuel on +an empty board and about 0.8M more per seat, so with six or more seats it +exhausted the 10M default limit and trapped. A trapped view poisons the world. +The earlier claim that territory fits with all eight seats was wrong. This +change makes the full house fit with room to spare, makes the shared `Screen` +code cheaper for every app, and guards the full house in `FUEL_BUDGETS`. + +## Reproduction + +`territory_view_fits_the_default_fuel_with_every_seat_taken` joins eight players +by presence events, has each act so each gets a seat, and claims 14 cells per +seat (112 of 128 cells). Before the fix: + +``` +a full territory view must not trap: guest `plaza_view` failed (trap or fuel exhausted) + ... territory.wasm!roc__proc_15fb + ... territory.wasm!host.plaza_view +``` + +`print_territory_view_fuel_by_seats` (ignored; `TERRITORY_WASM=FILE` measures a +variant build) prints the view fuel by seat count. + +## Where the fuel went + +I built variants of territory's `view` that stop after each stage and measured +each at 0, 2, and 8 seats. Two facts decide everything: + +1. **The checked-in module was built by an older Roc.** The repository pins Roc + `nightly-2026-10-04-130536d` (`nix/roc.nix`, the example READMEs), but the + checked-in `territory.wasm` matched the output of the `nightly-2026-08-10` + compiler exactly (6,544,819 fuel on the empty board, to the instruction). + The pinned compiler builds the **same, unchanged source** into a module that + costs 2.34M on the empty board and 3.24M with eight full seats. +2. **The remaining cost is in `Screen`, in three places.** + +Fuel by stage, view only, in thousands (stale compiler / pinned compiler; the +unchanged territory source and the original `Screen.roc`): + +| Stage added (cumulative) | Empty, stale | Empty, pinned | 8 seats, pinned | +| ------------------------------------------------------------------ | --------------------: | ----------------------: | --------------: | +| `Screen.new`, `boxed`, `render_json` of a constant picture | not measured | 1 | 1 | +| build 128 `{ ch, fg, bg, bold }` records, `put_row` x8, plain text | 4,017 | 540 | 574 | +| `render_json` instead of `render_plain` (quote + style spans) | 5,324 | 1,976 | 2,208 | +| status line (`put_text`, one list update per character) | 6,545 | 2,343 | 2,324 | +| scoreboard, one `put_text` per seat | 6,545 + 0.8M per seat | 2,343 + ~0.11M per seat | 3,239 | + +Reading the table: + +- **Per-character list updates were the dominant cost under the stale + compiler.** `put_text` and `put_row` update `cells` with `List.set` while the + accumulator still holds the list, so each update copied the 456-cell list + (3.5M for the 128 grid cells alone, about 50k for each scoreboard + character). The pinned compiler updates in place, which is why rebuilding + alone removes about 4.2M. +- **Building the per-cell records** costs about 4.1k per cell (526k for 128): + `bytes_to_str([b])` allocates a list and validates it for every cell. +- **`render_json` costs about 1.4M for a 24x19 screen**, mostly `json_quote`, + which folds every byte into a list through a second per-byte fold, and + `row_styles_json`, which builds an indexed record list per row. +- **Each seat adds about 0.11M with the pinned compiler**: roughly 30k for the + per-cell `cursor_at` scan of the seat list and the rest for the scoreboard + line (`put_text`, 15 to 29 characters at about 5k each). + +## The fix + +Three changes, in order of reach: + +1. **Rebuild with the pinned Roc.** The checked-in modules for every example + that imports `Screen` (`territory`, `roc-screen`, `roc-grid`) are rebuilt + with the pinned nightly, as the READMEs say to. Not a source change; worth + about 4.2M for territory. +2. **`Screen.json_quote` skips its per-byte fold for text that needs no + escaping** (the common case). This helps every app that calls + `render_json`: with the original `Screen.roc` and the same compiler, + roc-screen's view went 252k to 124k, its layout 560k to 378k, and roc-grid's + view 696k to 391k. Output is byte for byte the same. +3. **`Screen.render_rows_json` and `Screen.box_edge`** build the screen + document from whole rows: each row is a list of `{ text, style }` pieces, + padded or cut to the width. No per-cell record list exists. Equal adjacent + styles merge and the default style writes no span, so the document equals + what `render_json` writes for the same picture. Territory uses it: the + boxed border is two `box_edge` strings, each grid row is `|`, a few style + runs, `|`, and each scoreboard line is one piece. The existing + `Screen.new`/`put_text`/`put_row`/`render_json` API is untouched. + +Territory's picture did not change. The boxed grid, per-seat colours, inverted +cursor, free count, and one scoreboard line per seat remain, and I compared the +view JSON of the old source (pinned compiler) and the new source byte for byte +across six states (0 to 8 seats, 0 to 14 cells per seat): identical. +`territory_scoreboard_lines_are_cut_at_the_screen_width` pins the rows for a +seat with a long name, which the screen clips to 24 columns. + +## Results + +View fuel, default limit 10,000,000: + +| Territory view | Before (checked in) | Pinned compiler, old source | After (this change) | +| ----------------- | ------------------: | --------------------------: | ------------------: | +| empty board | 6,544,819 | 2,343,322 | 964,367 | +| 1 seat, 1 cell | 7,112,842 | 2,438,218 | 1,034,195 | +| 2 seats, 14 cells | 7,798,938 | 2,572,204 | 1,132,099 | +| 4 seats, 14 cells | 9,069,083 | 2,793,480 | 1,293,209 | +| 8 seats, 1 cell | trap (10M) | 3,071,268 | 1,468,278 | +| 8 seats, 14 cells | trap (10M) | 3,239,531 | 1,611,425 | + +The full-house view is **16 percent** of the limit (target: at most 40 +percent), and the empty board is 9.6 percent. + +Shared `Screen` apps (worst view / layout, scripted state): + +| Example | View before | View after | Layout before | Layout after | +| ---------- | ----------: | ---------: | ------------: | -----------: | +| roc-screen | 257,078 | 123,675 | 1,192,583 | 378,384 | +| roc-grid | 981,969 | 391,196 | 981,300 | 389,763 | + +Their drop is partly the compiler (original `Screen.roc`, pinned compiler: +252k / 560k and 696k / 695k) and partly `json_quote`. + +## Guarding it + +- `territory_view_fits_the_default_fuel_with_every_seat_taken` fails if the + full-house view traps or uses more than 40 percent of the limit. +- `checked_in_examples_stay_within_fuel_budgets` gets a `territory-full` + entry (`drive_territory_full`: eight seats, 14 cells each) alongside the + two-seat `territory` entry. Same rule: baseline plus 25 percent, rounded up + to 100,000. Its view budget is 2.1M, its worst update 1.1M (one 29-key + input), records 0.6M. +- Re-baselined rows, and why: `territory` (stale to pinned compiler plus the + new view), `roc-screen` and `roc-grid` (pinned compiler plus `json_quote`). + Small calls (init, wants, snapshot, restore) moved by a few hundred fuel with + the compiler and keep their 100,000 budget. + +## Compiler hazard found on the way + +Using a `Str` again after passing it to `Str.to_utf8` corrupts memory in the +pinned nightly's wasm backend: a first version of the `json_quote` fast path +returned the original `text`, and roc-screen and roc-grid then rendered rows +made of other allocations (`roc test` on `Screen.roc` passed, the sandbox +tests failed). The code now reads the bytes once and rebuilds the `Str` from +them. This is recorded in `examples/roc-world/README.md`. Territory's earlier +rows did not show it because small strings are stored inline. + +## Limits + +- Fuel scales with state. The view costs about 0.96M on an empty board and + about 0.08M per seat after that; a larger board or longer scoreboard would add more. The + budget covers eight seats and 112 of 128 cells, not every possible state. +- Records is now the second-largest call at the full house (437k), and update + with a long key string reaches 831k. Both are far from the limit. +- `render_rows_json` counts columns as Unicode scalar values, like `chars`. + It does not measure double-width glyphs; the host still validates the + document and rejects a row whose display width does not fill the screen. +- Builds of the same source gave different bytes on some runs here (the first + build after other builds differed from later, mutually identical ones), so do + not compare the checked-in `.wasm` files by hash. Fuel counts are exact for + the checked-in bytes. +- The other examples (`roc-counter`, `tic-tac-toe`, `roc-chat`, `lounge`) do + not import `Screen`; I did not rebuild them, and they may also have been + built by the older compiler. + +## Follow-ups + +- **A view trap should degrade to an error screen instead of poisoning the + world.** Not changed here: the poisoning behaviour is unchanged. +- Check that the other checked-in modules were built with the pinned Roc and + add a check that fails when a module's compiler differs from `nix/roc.nix`. +- Consider moving `roc-screen` and `roc-grid` to `render_rows_json`, and + `put_grid` to a row path; both still build per-cell records. +- Crowded-state budgets for the other examples (the earlier record's + follow-up now holds for territory only). + +## Progress + +- 2026-10-17: reproduced with a failing eight-seat test; attributed the cost; + rebuilt `territory`, `roc-screen`, and `roc-grid` with the pinned compiler; + added `json_quote` fast path, `render_rows_json`, `box_edge`; moved + territory's view to the row path; added the full-house guard and + re-baselined. Phase 11: territory's fuel follow-up from the perf budgets + record is closed; the view-trap degradation follow-up is open. + +## References + +- [Phase 11 foundations plan](../../.opencode/plans/phase-11-foundations.md) (not in this worktree; its "Phase 11 progress" list takes the Progress entry above) +- [Perf budgets record](../2026-10-17T15-30-00Z_feature_world_perf_budgets/2026-10-17T15-30-00Z_feature_world_perf_budgets.md) +- `pkgs/id/examples/roc-world/Screen.roc`, `pkgs/id/examples/territory/main.roc` +- `pkgs/id/src/sandbox.rs`: `crowd_territory`, `drive_territory_full`, `FUEL_BUDGETS` diff --git a/pkgs/id/examples/roc-grid/roc-grid.wasm b/pkgs/id/examples/roc-grid/roc-grid.wasm index dd02574b56..6ed52ec455 100755 Binary files a/pkgs/id/examples/roc-grid/roc-grid.wasm and b/pkgs/id/examples/roc-grid/roc-grid.wasm differ diff --git a/pkgs/id/examples/roc-screen/roc-screen.wasm b/pkgs/id/examples/roc-screen/roc-screen.wasm index 8c03b97c10..b96f5f7e56 100755 Binary files a/pkgs/id/examples/roc-screen/roc-screen.wasm and b/pkgs/id/examples/roc-screen/roc-screen.wasm differ diff --git a/pkgs/id/examples/roc-world/README.md b/pkgs/id/examples/roc-world/README.md index d7ac49e35d..2695c2ce53 100644 --- a/pkgs/id/examples/roc-world/README.md +++ b/pkgs/id/examples/roc-world/README.md @@ -108,6 +108,12 @@ elements in some module compositions (observed while building positional access beyond index 1; prefer `after`/`between`-style extraction for now and re-check with a newer nightly before relying on it. +A second one, found while making `Screen` cheaper: using a `Str` again after +passing it to `Str.to_utf8` corrupts memory in that backend (`roc test` does +not show it; the wasm build returns rows made of other allocations). Read the +bytes once and rebuild the `Str` from them when you need both, as +`Screen.json_quote` does. + `snapshot`/`restore` let the host trim a world's journal. Without them a world restarts by replaying every input it ever received; with them the host periodically replaces the journal's history by a checkpoint holding diff --git a/pkgs/id/examples/roc-world/Screen.roc b/pkgs/id/examples/roc-world/Screen.roc index 7d888fbefb..073cbc16d0 100644 --- a/pkgs/id/examples/roc-world/Screen.roc +++ b/pkgs/id/examples/roc-world/Screen.roc @@ -17,8 +17,11 @@ Screen := { ## Split text into one string per Unicode scalar value. chars : Str -> List(Str) - chars = |text| { - split = List.fold(Str.to_utf8(text), { done: [], current: [] }, |acc, byte| { + chars = |text| split_chars(Str.to_utf8(text)) + + split_chars : List(U8) -> List(Str) + split_chars = |bytes| { + split = List.fold(bytes, { done: [], current: [] }, |acc, byte| { if byte >= 128 and byte < 192 { { done: acc.done, current: List.append(acc.current, byte) } } else if List.is_empty(acc.current) { @@ -137,19 +140,121 @@ Screen := { render_json = |screen| { rows = List.map(range(0, screen.height), |row| json_quote(row_text(screen, row))) styles = List.map(range(0, screen.height), |row| row_styles_json(screen, row)) - width = screen.width.to_str() - height = screen.height.to_str() - row_json = Str.join_with(rows, ",") - styles_json = Str.join_with(styles, ",") - prefix = Str.concat("{\"kind\":\"screen\",\"version\":1,\"width\":", width) - with_height = Str.concat(prefix, Str.concat(",\"height\":", height)) + document_json(screen.width, screen.height, Str.join_with(rows, ","), Str.join_with(styles, ",")) + } + + document_json : U64, U64, Str, Str -> Str + document_json = |width, height, row_json, styles_json| { + prefix = Str.concat("{\"kind\":\"screen\",\"version\":1,\"width\":", width.to_str()) + with_height = Str.concat(prefix, Str.concat(",\"height\":", height.to_str())) with_rows = Str.concat(with_height, Str.concat(",\"rows\":[", Str.concat(row_json, "]"))) Str.concat(with_rows, Str.concat(",\"styles\":[", Str.concat(styles_json, "]}"))) } + ## The same document as `render_json`, built from whole rows instead of a + ## cell list. Each entry of `rows` is one screen row: pieces of text with + ## one style each, laid end to end. A row is padded with spaces to `width` + ## columns and cut off at it; missing rows are blank and rows past + ## `height` are dropped. A column is one Unicode scalar value, as in + ## `chars`. Adjacent pieces with equal styles merge, and the default style + ## (all zero) writes no span, so the output matches `render_json` for the + ## same picture. Cost grows with the number of pieces, not the number of + ## cells, so prefer a few long pieces per row to one piece per cell. + render_rows_json : U64, U64, List(List({ text : Str, style : { fg : U8, bg : U8, bold : Bool } })) -> Str + render_rows_json = |width, height, rows| { + built = List.map(range(0, height), |row| { + pieces = match List.get(rows, row) { + Ok(found) => found + Err(_) => [] + } + build_row(width, pieces) + }) + texts = List.map(built, |row| json_quote(row.text)) + styles = List.map(built, |row| Str.concat("[", Str.concat(Str.join_with(row.spans, ","), "]"))) + document_json(width, height, Str.join_with(texts, ","), Str.join_with(styles, ",")) + } + + ## One row of `render_rows_json`: its padded text and its style spans. + build_row : U64, List({ text : Str, style : { fg : U8, bg : U8, bold : Bool } }) -> { text : Str, spans : List(Str) } + build_row = |width, pieces| { + start = { text: "", spans: [], x: 0, run_x: 0, run_len: 0, fg: 0, bg: 0, bold: Bool.False } + done = List.fold(pieces, start, |acc, piece| { + fitted = fit(piece.text, width - acc.x) + style = piece.style + if fitted.columns == 0 { + acc + } else if acc.run_len > 0 and style.fg == acc.fg and style.bg == acc.bg and style.bold == acc.bold { + { text: Str.concat(acc.text, fitted.text), spans: acc.spans, x: acc.x + fitted.columns, run_x: acc.run_x, run_len: acc.run_len + fitted.columns, fg: acc.fg, bg: acc.bg, bold: acc.bold } + } else { + spans = close_run(acc.spans, acc.run_x, acc.run_len, acc.fg, acc.bg, acc.bold) + { text: Str.concat(acc.text, fitted.text), spans: spans, x: acc.x + fitted.columns, run_x: acc.x, run_len: fitted.columns, fg: style.fg, bg: style.bg, bold: style.bold } + } + }) + padding = Str.join_with(List.repeat(" ", width - done.x), "") + { + text: Str.concat(done.text, padding), + spans: close_run(done.spans, done.run_x, done.run_len, done.fg, done.bg, done.bold), + } + } + + ## `text` cut to at most `room` columns, with the columns it kept. + ## The text is only read through its bytes: using a `Str` again after + ## `Str.to_utf8` consumed it corrupts memory in the wasm backend. + fit : Str, U64 -> { text : Str, columns : U64 } + fit = |text, room| { + bytes = Str.to_utf8(text) + columns = List.count_if(bytes, |byte| byte < 128 or byte >= 192) + if columns <= room { + { text: bytes_to_str(bytes), columns: columns } + } else { + { text: Str.join_with(List.take_first(split_chars(bytes), room), ""), columns: room } + } + } + + ## Append the span of a finished run, unless it is empty or default-styled. + close_run : List(Str), U64, U64, U8, U8, Bool -> List(Str) + close_run = |spans, x, length, fg, bg, bold| { + if length == 0 or (fg == 0 and bg == 0 and bold == Bool.False) { + spans + } else { + List.append(spans, style_span_json(x, length, fg, bg, bold)) + } + } + + ## The top or bottom edge of a box `w` columns wide: `+---+`, with `title` + ## written over it from the third column and cut off before the corner. + ## Use it with `render_rows_json` where `boxed` would need a cell list. + box_edge : U64, Str -> Str + box_edge = |w, title| { + if w < 2 { + "" + } else { + edge = chars(Str.concat("+", Str.concat(Str.join_with(List.repeat("-", w - 2), ""), "+"))) + if w < 4 or title == "" { + Str.join_with(edge, "") + } else { + label = List.take_first(chars(title), w - 3) + tail = List.drop_first(edge, 2 + List.len(label)) + Str.join_with(List.concat(List.concat(List.take_first(edge, 2), label), tail), "") + } + } + } + json_quote : Str -> Str json_quote = |text| { - escaped = List.fold(Str.to_utf8(text), [], |out, byte| { + # Read the text only through its bytes: using `text` again after + # `Str.to_utf8` consumed it corrupts memory in the wasm backend. + bytes = Str.to_utf8(text) + if List.any(bytes, |byte| byte == 34 or byte == 92 or byte < 32) { + Str.concat("\"", Str.concat(escape_bytes(bytes), "\"")) + } else { + Str.concat("\"", Str.concat(bytes_to_str(bytes), "\"")) + } + } + + escape_bytes : List(U8) -> Str + escape_bytes = |bytes| { + escaped = List.fold(bytes, [], |out, byte| { next = if byte == 34 { [92, 34] } else if byte == 92 { @@ -171,7 +276,7 @@ Screen := { } List.fold(next, out, |acc, value| List.append(acc, value)) }) - Str.concat("\"", Str.concat(bytes_to_str(escaped), "\"")) + bytes_to_str(escaped) } hex_digit : U8 -> U8 @@ -271,3 +376,9 @@ expect Screen.render_plain(Screen.boxed(Screen.new(6, 3), 0, 0, 6, 3, "t")) == " expect Screen.render_json(Screen.put_text(Screen.new(2, 1), 0, 0, "ok", { fg: 0, bg: 0, bold: Bool.False })) == "{\"kind\":\"screen\",\"version\":1,\"width\":2,\"height\":1,\"rows\":[\"ok\"],\"styles\":[[]]}" expect Screen.render_json(Screen.put_text(Screen.new(3, 1), 0, 0, "abc", { fg: 196, bg: 0, bold: Bool.True })) == "{\"kind\":\"screen\",\"version\":1,\"width\":3,\"height\":1,\"rows\":[\"abc\"],\"styles\":[[{\"x\":0,\"length\":3,\"fg\":196,\"bg\":0,\"bold\":true}]]}" expect Screen.json_quote("a\"\\\n") == "\"a\\\"\\\\\\n\"" +expect Screen.render_rows_json(4, 1, [[{ text: "ab", style: { fg: 0, bg: 0, bold: Bool.False } }]]) == "{\"kind\":\"screen\",\"version\":1,\"width\":4,\"height\":1,\"rows\":[\"ab \"],\"styles\":[[]]}" +expect Screen.render_rows_json(3, 2, [[{ text: "a", style: { fg: 196, bg: 0, bold: Bool.True } }, { text: "bc", style: { fg: 196, bg: 0, bold: Bool.True } }]]) == "{\"kind\":\"screen\",\"version\":1,\"width\":3,\"height\":2,\"rows\":[\"abc\",\" \"],\"styles\":[[{\"x\":0,\"length\":3,\"fg\":196,\"bg\":0,\"bold\":true}],[]]}" +expect Screen.render_rows_json(3, 1, [[{ text: "a\"", style: { fg: 0, bg: 0, bold: Bool.False } }, { text: "xyz", style: { fg: 2, bg: 0, bold: Bool.False } }]]) == "{\"kind\":\"screen\",\"version\":1,\"width\":3,\"height\":1,\"rows\":[\"a\\\"x\"],\"styles\":[[{\"x\":2,\"length\":1,\"fg\":2,\"bg\":0,\"bold\":false}]]}" +expect Screen.box_edge(8, "ti") == "+-ti---+" +expect Screen.box_edge(6, "toolong") == "+-too+" +expect Screen.box_edge(4, "") == "+--+" diff --git a/pkgs/id/examples/territory/main.roc b/pkgs/id/examples/territory/main.roc index 94798c03b0..e36df6feea 100644 --- a/pkgs/id/examples/territory/main.roc +++ b/pkgs/id/examples/territory/main.roc @@ -60,23 +60,44 @@ update = |model, pid, ev| view : Model -> Str view = |model| { - screen = Screen.boxed(Screen.new(24, 19), 0, 0, 18, 10, "territory") - with_cells = List.fold(row_indices, screen, |acc, y| { - row = List.map(column_indices, |x| { - b = cell_byte(model, x, y) - st = style_for_cell(b) - { ch: bytes_to_str([b]), fg: st.fg, bg: st.bg, bold: st.bold } - }) - Screen.put_row(acc, y + 1, 1, row) - }) + plain = { fg: 0, bg: 0, bold: Bool.False } + edge = [{ text: Screen.box_edge(18, "territory"), style: plain }] + bottom = [{ text: Screen.box_edge(18, ""), style: plain }] + grid_rows = List.map(row_indices, |y| grid_row(model, y)) free = RocGrid.count(model.grid, empty) - status_text = "free=${free.to_str()} [hjkl/space]" - with_status = Screen.put_text(with_cells, 0, 10, status_text, { fg: 0, bg: 0, bold: Bool.False }) - with_scores = List.fold_with_index(model.seats, with_status, |acc, seat, i| - Screen.put_text(acc, 0, 11 + i, seat_line(model, seat), mark_style(seat.mark))) - Screen.render_json(with_scores) + status = [{ text: "free=${free.to_str()} [hjkl/space]", style: plain }] + scores = List.map(model.seats, |seat| [{ text: seat_line(model, seat), style: mark_style(seat.mark) }]) + rows = List.concat(List.concat([edge], grid_rows), List.concat([bottom, status], scores)) + Screen.render_rows_json(24, 19, rows) +} + +## One boxed grid row as styled pieces: the borders, then the cells with equal +## styles merged into runs, so a row costs a handful of pieces and not 16 cells. +grid_row : Model, U64 -> List({ text : Str, style : { fg : U8, bg : U8, bold : Bool } }) +grid_row = |model, y| { + plain = { fg: 0, bg: 0, bold: Bool.False } + bytes = List.map(column_indices, |x| cell_byte(model, x, y)) + List.concat([{ text: "|", style: plain }], List.append(style_runs(bytes), { text: "|", style: plain })) +} + +## Group consecutive bytes that share a style into one piece of text. +style_runs : List(U8) -> List({ text : Str, style : { fg : U8, bg : U8, bold : Bool } }) +style_runs = |bytes| { + start = { runs: [], run: [], style: { fg: 0, bg: 0, bold: Bool.False } } + done = List.fold(bytes, start, |acc, b| { + style = style_for_cell(b) + if List.is_empty(acc.run) or same_style(style, acc.style) { + { runs: acc.runs, run: List.append(acc.run, b), style: style } + } else { + { runs: List.append(acc.runs, { text: bytes_to_str(acc.run), style: acc.style }), run: [b], style: style } + } + }) + if List.is_empty(done.run) { done.runs } else { List.append(done.runs, { text: bytes_to_str(done.run), style: done.style }) } } +same_style : { fg : U8, bg : U8, bold : Bool }, { fg : U8, bg : U8, bold : Bool } -> Bool +same_style = |a, b| a.fg == b.fg and a.bg == b.bg and a.bold == b.bold + ## Everything here is derived from the grid and the seats, so the record ## is a pure function of the state a snapshot already carries. ## This program renders the same layout at any viewport. diff --git a/pkgs/id/examples/territory/territory.wasm b/pkgs/id/examples/territory/territory.wasm index 9273e74f9d..1c6644d64e 100755 Binary files a/pkgs/id/examples/territory/territory.wasm and b/pkgs/id/examples/territory/territory.wasm differ diff --git a/pkgs/id/src/sandbox.rs b/pkgs/id/src/sandbox.rs index dec828b145..54cb18c0b3 100644 --- a/pkgs/id/src/sandbox.rs +++ b/pkgs/id/src/sandbox.rs @@ -1850,14 +1850,38 @@ mod tests { host_event(world, &joined(1, "ann")); host_event(world, &joined(2, "bob")); // The opening of a two-player game: each seat has claimed a few - // cells. A crowded late game costs more; see the record's headroom - // section. + // cells. `territory-full` budgets the crowded game. for (participant, moves) in [(1u64, "l "), (2, " "), (2, "l "), (2, "hj "), (1, "j ")] { world.update(participant, moves.as_bytes()).unwrap(); } } - fn examples() -> [Example; 7] { + /// A crowded territory game: `seats` players join, then each claims + /// `per_seat` cells along its own row, so every seat is online with a + /// cursor on the board and the grid is mostly claimed. + fn crowd_territory(world: &mut WorldInstance, seats: u64, per_seat: usize) { + for id in 1..=seats { + host_event( + world, + &format!( + r#"{{"cap":"players","event":"joined","participant":{{"id":{id},"name":"p{id}"}}}}"# + ), + ); + } + for id in 1..=seats { + let mut keys = "j".repeat(usize::try_from(id - 1).unwrap()); + keys.push(' '); + keys.push_str(&"l ".repeat(per_seat.saturating_sub(1))); + world.update(id, keys.as_bytes()).unwrap(); + } + } + + /// Territory at its seat limit with most of the board claimed. + fn drive_territory_full(world: &mut WorldInstance) { + crowd_territory(world, 8, 14); + } + + fn examples() -> [Example; 8] { [ Example { name: "roc-counter", @@ -1894,6 +1918,11 @@ mod tests { wasm: include_bytes!("../examples/territory/territory.wasm"), drive: drive_territory, }, + Example { + name: "territory-full", + wasm: include_bytes!("../examples/territory/territory.wasm"), + drive: drive_territory_full, + }, ] } @@ -1982,22 +2011,22 @@ mod tests { ("tic-tac-toe", GuestCall::Wants, 100_000), // baseline 1664 ("tic-tac-toe", GuestCall::Snapshot, 100_000), // baseline 769 ("tic-tac-toe", GuestCall::Restore, 100_000), // baseline 14204 - ("roc-screen", GuestCall::Init, 100_000), // baseline 1215 - ("roc-screen", GuestCall::Update, 100_000), // baseline 11491 - ("roc-screen", GuestCall::View, 400_000), // baseline 257078 - ("roc-screen", GuestCall::Layout, 1_500_000), // baseline 1192583 - ("roc-screen", GuestCall::Records, 100_000), // baseline 2795 - ("roc-screen", GuestCall::Wants, 100_000), // baseline 733 - ("roc-screen", GuestCall::Snapshot, 100_000), // baseline 870 - ("roc-screen", GuestCall::Restore, 100_000), // baseline 3243 - ("roc-grid", GuestCall::Init, 100_000), // baseline 1242 - ("roc-grid", GuestCall::Update, 100_000), // baseline 5035 - ("roc-grid", GuestCall::View, 1_300_000), // baseline 981969 - ("roc-grid", GuestCall::Layout, 1_300_000), // baseline 981300 - ("roc-grid", GuestCall::Records, 100_000), // baseline 1664 - ("roc-grid", GuestCall::Wants, 100_000), // baseline 737 - ("roc-grid", GuestCall::Snapshot, 100_000), // baseline 1143 - ("roc-grid", GuestCall::Restore, 100_000), // baseline 5688 + ("roc-screen", GuestCall::Init, 100_000), // baseline 1573 + ("roc-screen", GuestCall::Update, 100_000), // baseline 13141 + ("roc-screen", GuestCall::View, 200_000), // baseline 123675 + ("roc-screen", GuestCall::Layout, 500_000), // baseline 378384 + ("roc-screen", GuestCall::Records, 100_000), // baseline 3217 + ("roc-screen", GuestCall::Wants, 100_000), // baseline 904 + ("roc-screen", GuestCall::Snapshot, 100_000), // baseline 1061 + ("roc-screen", GuestCall::Restore, 100_000), // baseline 4129 + ("roc-grid", GuestCall::Init, 100_000), // baseline 1585 + ("roc-grid", GuestCall::Update, 100_000), // baseline 6150 + ("roc-grid", GuestCall::View, 500_000), // baseline 391196 + ("roc-grid", GuestCall::Layout, 500_000), // baseline 389763 + ("roc-grid", GuestCall::Records, 100_000), // baseline 2232 + ("roc-grid", GuestCall::Wants, 100_000), // baseline 1082 + ("roc-grid", GuestCall::Snapshot, 100_000), // baseline 1341 + ("roc-grid", GuestCall::Restore, 100_000), // baseline 4953 ("roc-chat", GuestCall::Init, 100_000), // baseline 1271 ("roc-chat", GuestCall::Update, 200_000), // baseline 89763 ("roc-chat", GuestCall::View, 100_000), // baseline 5997 @@ -2014,16 +2043,106 @@ mod tests { ("lounge", GuestCall::Wants, 300_000), // baseline 194873 ("lounge", GuestCall::Snapshot, 100_000), // baseline 70261 ("lounge", GuestCall::Restore, 100_000), // baseline 33299 - ("territory", GuestCall::Init, 100_000), // baseline 1255 - ("territory", GuestCall::Update, 100_000), // baseline 64520 - ("territory", GuestCall::View, 9_800_000), // baseline 7798929 - ("territory", GuestCall::Layout, 9_800_000), // baseline 7798260 - ("territory", GuestCall::Records, 100_000), // baseline 56536 - ("territory", GuestCall::Wants, 100_000), // baseline 2444 - ("territory", GuestCall::Snapshot, 100_000), // baseline 7794 - ("territory", GuestCall::Restore, 100_000), // baseline 21745 + ("territory", GuestCall::Init, 100_000), // baseline 1593 + ("territory", GuestCall::Update, 100_000), // baseline 68643 + ("territory", GuestCall::View, 1_500_000), // baseline 1134256 + ("territory", GuestCall::Layout, 1_500_000), // baseline 1133740 + ("territory", GuestCall::Records, 100_000), // baseline 58449 + ("territory", GuestCall::Wants, 100_000), // baseline 3375 + ("territory", GuestCall::Snapshot, 100_000), // baseline 10713 + ("territory", GuestCall::Restore, 100_000), // baseline 23335 + ("territory-full", GuestCall::Init, 100_000), // baseline 1593 + ("territory-full", GuestCall::Update, 1_100_000), // baseline 831551 + ("territory-full", GuestCall::View, 2_100_000), // baseline 1611425 + ("territory-full", GuestCall::Layout, 2_100_000), // baseline 1612121 + ("territory-full", GuestCall::Records, 600_000), // baseline 436803 + ("territory-full", GuestCall::Wants, 100_000), // baseline 3375 + ("territory-full", GuestCall::Snapshot, 100_000), // baseline 12801 + ("territory-full", GuestCall::Restore, 100_000), // baseline 32317 ]; + #[test] + fn territory_view_fits_the_default_fuel_with_every_seat_taken() { + let wasm = include_bytes!("../examples/territory/territory.wasm"); + let limits = SandboxLimits::default(); + let runner = Sandbox::compile(wasm, limits).unwrap(); + let mut live = runner.instantiate(7).unwrap(); + crowd_territory(&mut live, 8, 14); + let view = live + .view() + .unwrap_or_else(|error| panic!("a full territory view must not trap: {error:#}")); + let view = String::from_utf8(view).unwrap(); + let surface = crate::world_presentation::parse_surface(&view).unwrap(); + let Some(crate::world_presentation::WorldSurface::Screen(screen)) = surface else { + panic!("territory must return a structured screen: {view}"); + }; + let rows: Vec = screen + .cells + .chunks(usize::from(screen.width)) + .map(|row| row.iter().map(|cell| cell.symbol.as_str()).collect()) + .collect(); + let text = rows.join("\n"); + assert!(text.contains("free=16"), "{text}"); + assert!(text.contains("H p8 14 online"), "{text}"); + // One view may use at most 40 percent of the limit, so a full + // house leaves room for growth. + let spent = live.last_fuel(GuestCall::View); + assert!( + spent <= limits.fuel * 2 / 5, + "a full-house view used {spent} of {} fuel", + limits.fuel + ); + } + + #[test] + fn territory_scoreboard_lines_are_cut_at_the_screen_width() { + let wasm = include_bytes!("../examples/territory/territory.wasm"); + let runner = Sandbox::compile(wasm, SandboxLimits::default()).unwrap(); + let mut live = runner.instantiate(7).unwrap(); + host_event( + &mut live, + r#"{"cap":"players","event":"joined","participant":{"id":1,"name":"abcdefghijklmnopqrst"}}"#, + ); + live.update(1, b" ").unwrap(); + let view = String::from_utf8(live.view().unwrap()).unwrap(); + let surface = crate::world_presentation::parse_surface(&view).unwrap(); + let Some(crate::world_presentation::WorldSurface::Screen(screen)) = surface else { + panic!("territory must return a structured screen: {view}"); + }; + let rows: Vec = screen + .cells + .chunks(usize::from(screen.width)) + .map(|row| row.iter().map(|cell| cell.symbol.as_str()).collect()) + .collect(); + // Names keep 16 bytes; "A " + 16 + " 1 " leaves three columns of "online". + assert_eq!(rows[11], "A abcdefghijklmnop 1 onl", "{rows:?}"); + assert_eq!(rows[0], "+-territory------+ "); + assert_eq!(rows[9], "+----------------+ "); + assert_eq!(rows[10], "free=127 [hjkl/space] "); + assert_eq!(rows[1], "|a...............| "); + assert_eq!(rows[12], " ".repeat(24)); + } + + #[test] + #[ignore = "prints territory view fuel by seat count"] + fn print_territory_view_fuel_by_seats() { + // `TERRITORY_WASM=FILE` measures a variant build instead. + let wasm = match std::env::var_os("TERRITORY_WASM") { + Some(path) => std::fs::read(path).unwrap(), + None => include_bytes!("../examples/territory/territory.wasm").to_vec(), + }; + let runner = Sandbox::compile(&wasm, SandboxLimits::default()).unwrap(); + for (seats, per_seat) in [(0, 0), (1, 1), (2, 14), (4, 14), (8, 1), (8, 14)] { + let mut live = runner.instantiate(7).unwrap(); + crowd_territory(&mut live, seats, per_seat); + let outcome = live.view().map_or("trap", |_| "ok"); + println!( + "seats={seats} per_seat={per_seat} view={outcome} fuel={}", + live.last_fuel(GuestCall::View) + ); + } + } + #[test] fn checked_in_examples_stay_within_fuel_budgets() { let mut failures = Vec::new();