diff --git a/doc/2026-11-01_design_id557.md b/doc/2026-11-01_design_id557.md new file mode 100644 index 0000000000..3440dc3fb5 --- /dev/null +++ b/doc/2026-11-01_design_id557.md @@ -0,0 +1,342 @@ +# Design: F12.12 per-world memory budget and many-world scale + +- Date: 2026-11-01 +- Status: **design** — implementation and scale measurement remain open on + [#557](https://github.com/developing-today/code/issues/557). +- Issue: [#557 — F12.12 many worlds per node](https://github.com/developing-today/code/issues/557). +- Evidence checkout: `design/id-557` at `3cbab2d9e` (the source locations below + are from this checkout). +- Scope: a decision-ready design only. This note changes no `pkgs/id` behavior. + +## Decision to make + +Define and enforce one finite **total per-world memory budget**, not another +per-guest cap, while preserving durable reopen and refusal semantics. Then +measure **1,000 idle durable worlds plus 100 active worlds** at 20 events/s +each, with p99 command latency below 50 ms and no state loss through eviction, +checkpoint, and reopen. + +The important contract choice is what “memory budget” promises. This design +recommends a deterministic **logical-charge ceiling** for allocations owned by +one world. It is not an RSS guarantee: Rust allocator metadata/fragmentation, +thread stacks, and process-shared runtime caches are outside this per-world +accounting model. The latest #557 resume note explicitly asks for this contract +rather than an RSS estimate or guest-only reservation. + +## Context and current shape + +The issue's acceptance criteria are (1) enforce a per-world total budget with +refusal tests, (2) measure 1,000 idle and 100 active worlds at 20 events/s and +p99 under 50 ms with the F11.8 harness, and (3) prove idle eviction checkpoints +and reopens without loss. The original prerequisite, #539, is now closed; its +benchmark harness and baselines exist. + +### What exists + +- `WorldHub` opens worlds lazily with single-flight initialization, caps open + worlds and sessions, and evicts only idle durable worlds; defaults are 256 + open worlds and 1,024 sessions ([`world_hub.rs:7-19`](../pkgs/id/src/world_hub.rs#L7-L19), + [`world_hub.rs:82-99`](../pkgs/id/src/world_hub.rs#L82-L99), + [`world_hub.rs:472-585`](../pkgs/id/src/world_hub.rs#L472-L585), + [`world_hub.rs:661-709`](../pkgs/id/src/world_hub.rs#L661-L709)). The idle + evictor shuts the service down; durable state remains reopenable by the + `WorldOpener` contract. +- A `WorldLimits` instance bounds several world-level counts and payload sizes + (256 active participants, 1,024 retained events, input/chat/presentation and + snapshot byte limits), but it does not sum them into a total + ([`world/mod.rs:57-101`](../pkgs/id/src/world/mod.rs#L57-L101)). Revoked + capability records remain in `WorldCore.capabilities`; active-participant + admission counts only non-revoked records + ([`world/core.rs:856-930`](../pkgs/id/src/world/core.rs#L856-L930)). +- `SandboxLimits` gives one Wasm guest a 16 MiB default linear-memory maximum, + while `NativeLimits` defaults to a 256 MiB address-space cap + ([`sandbox.rs:18-39`](../pkgs/id/src/sandbox.rs#L18-L39), + [`world_native.rs:32-52`](../pkgs/id/src/world_native.rs#L32-L52)). These are + program-specific bounds, not a combined world budget. The current Wasm + limiter traps growth past that guest limit + ([`sandbox.rs:244-263`](../pkgs/id/src/sandbox.rs#L244-L263)). +- `RuntimeLimits` is the server hard ceiling and `WorldExecutionProfile` + requests per-world program limits beneath it; it has no total-memory field + ([`world_limits.rs:22-58`](../pkgs/id/src/world_limits.rs#L22-L58), + [`world_limits.rs:60-137`](../pkgs/id/src/world_limits.rs#L60-L137)). The CLI + currently exposes the guest-specific Wasm/native limits + ([`cli.rs:1310-1337`](../pkgs/id/src/cli.rs#L1310-L1337)). +- Per-world host memory is spread across `WorldCore` maps/deques, actor maps and + sets, the bounded actor command queue (256), retained session/frame state, + service state and persistence work buffers + ([`world/core.rs:9-42`](../pkgs/id/src/world/core.rs#L9-L42), + [`world/actor.rs:248-286`](../pkgs/id/src/world/actor.rs#L248-L286), + [`world/handle.rs:25-60`](../pkgs/id/src/world/handle.rs#L25-L60), + [`world_session/mod.rs:757-916`](../pkgs/id/src/world_session/mod.rs#L757-L916)). + A frame may be up to 1 MiB and the server-wide session ceiling is 1,024 + ([`frames.rs:16-20`](../pkgs/id/src/frames.rs#L16-L20), + [`world_hub.rs:82-99`](../pkgs/id/src/world_hub.rs#L82-L99)). +- Durable open currently materializes journal entries into a `Vec`; a helper + also reads the complete journal file before parsing it + ([`world_store.rs:59-155`](../pkgs/id/src/world_store.rs#L59-L155), + [`world_store.rs:451-484`](../pkgs/id/src/world_store.rs#L451-L484)). Restore + separately builds core state and a replay vector, while checkpoint/compaction + build replacement entries and encoded bytes + ([`world_store.rs:366-437`](../pkgs/id/src/world_store.rs#L366-L437), + [`world/core.rs:455-559`](../pkgs/id/src/world/core.rs#L455-L559), + [`world_store.rs:200-253`](../pkgs/id/src/world_store.rs#L200-L253)). These + peaks are not bounded by the guest memory limit. +- F11.8 currently reports four microbenchmarks—journal append/fsync, + checkpoint compaction, guest replay, and session fan-out—and its committed + output is median/min, not a many-world p99 workload + ([`world_bench.rs:14-33`](../pkgs/id/benches/world_bench.rs#L14-L33), + [`world_bench.rs:75-87`](../pkgs/id/benches/world_bench.rs#L75-L87), + [`world_bench.rs:242-289`](../pkgs/id/benches/world_bench.rs#L242-L289)). + The baseline notes caution that results are machine-class-specific + ([`BASELINES.md:9-23`](../pkgs/id/benches/BASELINES.md#L9-L23)). + +### Newest recorded decision and ownership note + +The latest implementation resume note on #557 says to use an explicit logical +charge (not an RSS guarantee), a finite server default, and refusal before +growth across runtime/profile limits, journal/checkpoint buffers, world state, +and per-world session admission. Earlier queue notes asked for the same scope; +the newest note controls. #539 is closed, and the issue history records the +separate implementation task 4827 as parked. This design PR does not resume, +modify, or duplicate that task; it records the missing contract and the +remaining benchmark acceptance. + +## Options considered + +| Option | Benefits | Costs / why not the recommendation | +| --- | --- | --- | +| **Guest-only ceiling** (reuse `wasm_memory_bytes` / `native_memory_bytes`) | Small change; existing Wasm trap and native rlimit paths already work. | Does not bound core maps, per-world sessions, journal restore/replay, or checkpoint copies. The latest #557 resume note explicitly rejects this as insufficient. | +| **RSS sampling / OS-level per-world process limit** | Closest to physical memory; easy to explain as a number. | A world is not one isolated process in the Wasm tier; host state and shared runtime allocations are mixed. RSS sampling is delayed/approximate and cannot safely gate a mutation before growth. Native rlimits only cover the worker address space, not host-side world state. It would not establish the requested enforce-before-growth invariant. | +| **One hard process-wide pool shared by all worlds** | Directly constrains node-wide memory and coordinates admission across worlds. | The issue asks for a per-world budget. A node pool is a separate policy and needs decisions about fairness, eviction priority, and what happens to active worlds. It would broaden F12.12 and interact with F12.10's fair scheduler. | +| **Per-world deterministic logical-charge budget** (**recommended**) | One auditable ledger covers program reservation, host-owned state, session allocations and temporary persistence peaks; admission/refusal can happen before mutation; works in tests without relying on allocator/RSS behavior. | It is an accounting contract, not an exact physical-memory cap. It requires explicit charge sites, conservative fixed overheads, and careful temporary reservations. The model must be documented so a charge is never mistaken for RSS. | + +## Recommendation + +Implement the **logical-charge budget** as a per-world hard ceiling, configured +by the server and optionally lowered per world through the existing +`WorldExecutionProfile` surface. Recommend a finite server default of **64 +MiB per world** for the first version. This leaves room above the existing +16 MiB default Wasm linear-memory ceiling: at most 48 MiB remains for the +module, host state, sessions, and temporary work before those charges are +applied. Effective guest/native limits must be lowered if the other charges +leave insufficient headroom. A conservative 100-active-world reservation is +at most 6.25 GiB before actual host charges. It also forces the existing 256 MiB native +address-space request to resolve down to what remains under the world budget; +native remains subject to its OS sandbox and is not claimed to consume exactly +its address-space reservation in RSS. This number is a proposed default, not a +measured fact; see Drew question Q1 below. + +### Accounting contract + +The ledger should have a deterministic `used_bytes <= effective_limit_bytes` +invariant. Charge: + +1. **Program reservation:** reserve the effective Wasm linear-memory ceiling + when the guest is installed/restored, or the effective native worker + address-space ceiling for a native program. There is one active program + tier per world. Count the module artifact's world-owned bytes; do not count + shared process-wide compiler/runtime caches. +2. **Persistent logical state:** serialized payload lengths plus documented + fixed per-entry structural allowances for world-owned retained events, + participants (including revoked records), directory/petname state, + schedules, records snapshots, and actor/service collections. The fixed + allowances are policy constants, not claims about the allocator's exact + layout. Count strings and buffers by logical length, consistently at every + insertion/replacement/removal site. +3. **Session and queued work:** a fixed per-world session charge plus the + application-owned frame/request/response bytes retained after the world is + identified. Reserve the session charge before accepting the session into + world processing; release it when the session exits. The server's + pre-routing handshake buffers remain under the existing global frame and + session ceilings, not attributed to a world. +4. **Transient peak reservations:** reserve before allocating journal parse and + replay state, guest/module restore buffers, snapshot verification, and + checkpoint/compaction replacement buffers. Release when the temporary + allocation is dropped. Compaction must account for the old and replacement + representations coexisting at peak. + +The journal file's on-disk bytes, shared stores, allocator fragmentation, +thread stacks, and process-shared code caches are explicitly outside the +logical-charge promise. Do not read an unbounded journal into a whole-file +`Vec`: stream entries and charge the materialized restore/replay state. If an +existing durable world's state or its required restore peak does not fit, fail +open with a typed resource-budget refusal and leave every durable file intact; +never truncate history to make it fit. + +`RuntimeLimits` supplies the hard total ceiling; `WorldExecutionProfile` may +request a lower total for one world, just as it already requests lower program +limits. Resolve all effective program ceilings beneath both the server ceiling +and the total budget. Persisting the new profile field must follow the journal +rollback contract: old binaries must refuse journals that carry a budget they +would otherwise ignore. The current journal has an explicit header-version +gate and bumps before an incompatible entry is appended +([`world/mod.rs:646-683`](../pkgs/id/src/world/mod.rs#L646-L683), +[`world_store.rs:143-155`](../pkgs/id/src/world_store.rs#L143-L155)); extend +that contract for the new field, including checkpoint profiles. + +### Refusal and recovery behavior + +- **Refuse before growth or durable mutation.** A request that would exceed + the ledger is rejected before journal append, state mutation, or session + admission. It must not partially apply and must not poison a healthy world. +- **Typed, recoverable refusal.** Add a resource-budget result distinguishable + from `UnknownWorld`, `Busy`, open-world-limit refusal, and storage failure. + A denied new lease/open gets a safe “world is at its memory budget” response; + an over-budget durable restore stays closed and retryable after configuration + changes. +- **No automatic eviction for an in-world overage.** Existing idle eviction + can free an open-world slot, but it cannot silently change or evict an active + world to admit one of that world's allocations. A later retry can succeed + after a temporary reservation/session is released or the administrator + raises the configured budget. +- **Guest trap remains distinct.** If guest execution exceeds its resolved + Wasm/native execution bound, preserve the existing guest failure semantics; + a host-side logical-charge refusal is not a guest trap and does not poison + the program. +- Expose `limit_bytes`, current/high-water charged bytes, and refusal count in + the existing per-world stats/metrics surface. These are logical accounting + metrics, not an RSS gauge. `WorldMetrics` already aggregates fixed-size + atomic counters/histograms and is surfaced by `id world stats` + ([`world/metrics.rs:81-105`](../pkgs/id/src/world/metrics.rs#L81-L105)). + +## Invariants + +1. For every open world, `charged_bytes <= effective_world_budget_bytes` at + every externally observable point, including restore and compaction peaks. +2. Every charged allocation has one owner and one documented reserve/release + path; failed reservations allocate nothing and leave no leaked charge. +3. Refused mutations do not alter core state, guest state, journal contents, + sequence numbers, or acknowledgements. Retrying after resources are released + is allowed. +4. A session is never admitted to a world unless its per-world reservation + succeeds; the process-wide session ceiling continues to apply too. +5. A world restored under a smaller budget either fits fully or refuses open; + it never drops journal entries, participants, replay inputs, or checkpoint + data to squeeze under the new limit. +6. Checkpoint/eviction/reopen reproduces the same sequence and program records + as the pre-eviction world. Budget checks do not weaken the existing + write-before-acknowledge journal contract + ([`world/actor.rs:375-393`](../pkgs/id/src/world/actor.rs#L375-L393)). +7. The 1,000 idle worlds are durable worlds available on disk and are not + required to have 1,000 resident actors. The benchmark uses lazy open and + idle eviction to keep only resident worlds charged; it exercises 1,000 + distinct idle worlds plus 100 simultaneously active leased worlds. This is + the interpretation recommended by F12.12's lazy-open/eviction design + ([`.opencode/plans/phase-12-platform-flexibility.md:19-20,51`](../.opencode/plans/phase-12-platform-flexibility.md#L19)). +8. The p99 threshold is measured from actual command-latency samples under the + declared workload, not inferred from the existing microbench medians. + +## Acceptance criteria for implementation + +- [ ] A finite server default and lower per-world request are validated; zero, + overflow, or requests above the server ceiling are rejected/clamped according + to the existing profile policy. +- [ ] Documentation names every charge category, exclusions, fixed overheads, + native reservation semantics, and that the contract is not RSS. +- [ ] Tests cover empty/default state, allocation within budget, refusal at the + exact boundary, refused-operation atomicity, reservation release and + successful retry, session release, open refusal, and restore refusal without + modifying durable files. +- [ ] Tests cover Wasm growth, native worker limit resolution, retained + world-state growth, queued/session buffers, journal restore/replay, snapshot + verification, and checkpoint/compaction peak reservations. +- [ ] Journal compatibility tests prove an older binary rejects a persisted + total-budget profile/checkpoint rather than silently ignoring the budget; + current and older journals without the field still restore. +- [ ] Stats report configured limit, current and high-water logical charge, + and refusal count without describing them as physical memory. +- [ ] Benchmark creates 1,000 durable idle worlds plus 100 active worlds, + sustains 20 accepted events/s per active world, and reports per-command p50, + p95 and p99; p99 is below 50 ms on the named reference machine. +- [ ] Under that workload, force idle eviction and reopen/checkpoint cycles; + compare sequence and records before and after and prove no acknowledged + event is lost. Record machine, toolchain, workload duration, and results + alongside the F11.8 baseline output. +- [ ] On budget exhaustion the node remains responsive, existing worlds remain + reachable, and only the over-budget operation/open is refused. + +## Phased implementation plan + +Each phase is a separately testable, mergeable change. The benchmark phase is +the final issue-level acceptance; earlier enforcement phases can merge without +claiming that scale acceptance is complete. + +1. **Budget contract and profile compatibility.** Add the logical-charge type, + finite server ceiling, optional lower per-world profile request, validation + and resolution; document the 64 MiB proposed default. Extend journal version + gating for a persisted profile/checkpoint budget and add compatibility + fixtures. No charge site may claim full enforcement yet. **Done:** pure + resolution/boundary tests and old/new journal compatibility tests pass. +2. **World-owned state accounting.** Add the per-world ledger and charge + `WorldCore`/`WorldActor`/service-owned retained state. Refactor growth + operations to reserve before state or journal mutation; make budget refusal + typed and recoverable. Include fixed actor collections and records/directory + state. **Done:** within-limit, exact-boundary, refusal atomicity, release, + retry, and node-still-responsive tests pass. +3. **Program and persistence peaks.** Apply the remaining budget to Wasm memory + and native worker reservations, module installation/restore, streamed + journal restore/replay, snapshot verification, and checkpoint/compaction + temporary buffers. Oversize restore refuses without rewriting storage. + **Done:** sandbox/native limit tests, bounded restore and checkpoint-peak + tests, reopen/no-loss tests, and journal rollback tests pass. +4. **Hub and session admission plus observability.** Integrate budget-aware + single-flight open and per-world session permits in `WorldHub`/session + routing, retain the existing global ceilings and idle durable eviction, + expose logical usage/refusals in stats. **Done:** concurrent first-open, + per-world admission/refusal/recovery, and global/session ceiling regression + tests pass. +5. **Many-world benchmark and recorded result.** Extend F11.8 with the + 1,000-idle + 100-active workload, 20 events/s per active world, real + latency samples/p99, and eviction/checkpoint/reopen integrity checks. Run + the full workload on the documented reference machine; commit the result + and machine metadata. **Done:** the stated p99 target passes and the + sequence/records comparisons prove no loss. If it fails, record the result + and tune only the measured bottleneck; do not call the acceptance complete. + +The workload phase extends rather than replaces the existing four baselines: +the current harness reports only median/min microbenchmark output +([`world_bench.rs:75-87`](../pkgs/id/benches/world_bench.rs#L75-L87)); the +benchmark notes require machine-class metadata and prohibit committing +`--quick` smoke numbers as baselines ([`BASELINES.md:43-66`](../pkgs/id/benches/BASELINES.md#L43-L66)). + +## Questions for Drew + +**Q1 — Per-world default.** Should v1 ship with a 64 MiB logical budget per +world, or choose 32 MiB / 128 MiB? **Recommendation: 64 MiB**: it is four +times the current default Wasm linear-memory ceiling, leaves 48 MiB of +logical-charge room beyond that guest reservation for module and other charges, +and caps 100 maximum-reserved active worlds at 6.25 GiB. +This is a proposed policy value, not an observed benchmark result. + +**Q2 — Meaning of “1,000 idle.”** Should the workload mean 1,000 durable worlds +present on disk and mostly evicted, plus 100 active worlds, or 1,000 idle +actors resident at the same time as 100 active actors? **Recommendation: the +first interpretation.** It follows F12.12's lazy-open/idle-eviction mechanism +and tests 1,100 worlds total without requiring 1,100 simultaneous resident +slots (the current default open-world ceiling is 256). If Drew chooses the +second, the benchmark must explicitly raise that ceiling and will be a +different resident-memory target. + +No other decision is left for Drew: the newest #557 resume note already +specifies logical charging rather than RSS, and the refusal, persistence, and +eviction invariants above are implementation contracts. + +## Non-goals + +- No node-wide memory pool or cross-world fair scheduler (F12.10 owns that + policy); no promise that aggregate process RSS is bounded by the sum of + logical charges. +- No disk quota for journals, modules, records documents, or world storage. +- No eviction of an active world or silent journal truncation to satisfy a + budget. +- No implementation changes in this design PR, and no change to #557's open + status. + +## References + +- [Issue #557 and its latest recorded resume decision](https://github.com/developing-today/code/issues/557). +- [F12.12 Phase 12 plan](../.opencode/plans/phase-12-platform-flexibility.md#L19). +- [`world_hub.rs`](../pkgs/id/src/world_hub.rs), [`world_limits.rs`](../pkgs/id/src/world_limits.rs), + [`world/core.rs`](../pkgs/id/src/world/core.rs), [`world/actor.rs`](../pkgs/id/src/world/actor.rs), + [`sandbox.rs`](../pkgs/id/src/sandbox.rs), [`world_store.rs`](../pkgs/id/src/world_store.rs), + and [`benches/world_bench.rs`](../pkgs/id/benches/world_bench.rs), all at the evidence checkout above.