Appearance
Space, routing, and capacity
The environment has two independent parts: a graph for movement and facilities for activities. Nodes and edges determine where a person can travel. Facilities attach to access nodes and determine what the person can do there. Multiple facilities may share a node while retaining separate capacities and activity offerings.
Geometry and connectivity
Coordinates use local Cartesian metres. Applications convert geographic coordinates before constructing input. Edges explicitly provide their length; the engine does not infer distance from their endpoint coordinates or polyline shape.
Only node references establish connectivity. Crossing lines, overlapping shapes, or identical coordinates do not join edges. Direction, enabled, and permitted modes also affect reachability. A connected-looking diagram can still have no usable route for a particular person. Elevation is geometric data; there is no automatic slope, stair, or accessibility penalty.
See the graph JSON contract for field definitions.
Routes and transport modes
For each mode enabled in the scenario and available to the agent, the router finds a shortest path using free-flow travel minutes. Without a timetable, each trip uses one graph mode throughout; transfer nodes alone do not create an itinerary. An optional mobility.timetable supplies dated walking, waiting, riding and transfer legs. See travel policies.
text
edge minutes = (mode-specific override OR length / speed / 60) + fixed penalty
mode comparison cost = route minutes + boarding penalty − agent mode preferenceA positive mode preference reduces that mode's comparison cost; it does not make the person physically travel faster. The feasible mode with the lowest comparison cost wins for legacy graph routing, with mode-ID tie-breaking. Optional mobility.travelChoice instead samples feasible alternatives reproducibly. Boarding penalty is added once per trip. Pathfinding uses stable shortest-path ordering and caches routes within the run.
Scheduled transit uses timetable waiting rather than adding the generic boarding penalty again. Household vehicles track location and reservations when their policy is enabled. These calculations are not a pedestrian collision solver, traffic signal model, transit vehicle crowding model, or demographic-specific speed model.
Three meanings of capacity
| Capacity | Meaning |
|---|---|
Facility capacity | Nominal number of people simultaneously present; also the denominator for reported facility commitment ratios. |
Facility anchorCapacity | Optional nominal assignment capacity for homes and overlapping fixed anchors; defaults to facility capacity. It does not replace the physical occupancy check during travel. |
Edge capacityPersonsPerHour | Throughput reference for flow ratios and congestion. It does not create a hard admission gate or waiting queue on the edge. |
The hard facility slot count is:
text
floor(nominal capacity × maximum capacity ratio)A facility's maximumCapacityRatio overrides scenario.behavior.maximumCapacityRatio; if neither is supplied, the ratio is 1. A nominal capacity of 10 with ratio 1.3 permits 13 committed people, but still reports utilization against 10. This is a modeling allowance, not a safety standard.
Occupancy and reservations
Occupancy counts people physically present. Reservations count committed inbound slots and held return slots during declared breaks. Admission checks their sum.
For a normal trip, the engine reserves the destination before departure, releases origin occupancy, then exchanges the destination reservation for occupancy at arrival. A break also holds a slot at the anchor so another person cannot take the return place. An ordinary activity completion leaves occupancy unchanged; the next departure or presence exit releases it.
Initial placement must fit hard capacity or the run fails. During execution, unavailable destinations lead to recorded unmet choices or rejected trips; the engine does not maintain a waiting list or automatically retry every minute.
Availability periods use an inclusive start and exclusive end. The engine checks opening at anchor assignment and at choice/departure time; it does not guarantee a whole visit fits inside opening hours or evict people when a facility closes. Author schedules and dwell accordingly.
Congestion
For modes listed in scenario.mobility.congestion.modes, traversal duration is adjusted using already recorded edge entries in the independent congestion window:
text
hourly volume = prior planned entries × 60 / scenario.mobility.congestion.windowMinutes
volume/capacity = hourly volume / edge capacityPersonsPerHour
factor = 1 + alpha × (volume/capacity)^beta
actual edge minutes = base travel minutes × factor + fixed penaltyThe default coefficients are alpha = 0.15 and beta = 4; explicit scenario settings control them. The current traveler is recorded after its factor is calculated. Edge counts combine modes and directions, so this is shared edge pressure rather than a lane-by-lane traffic model. Shared household passengers contribute person counts without creating additional vehicle movements or congestion entries.
The engine calculates all traversals for a trip at departure, using entries already recorded by earlier processed trips, including their later edge entries. It does not recalculate the route or traversal times as later demand appears. Routes and agenda feasibility use free-flow estimates; realized congestion can make an arrival later or shorten remaining dwell. This is an order-sensitive approximation, not dynamic traffic assignment. Congestion windows default to five minutes and align with the run start. Changing the observation interval changes reporting resolution only; changing the congestion window is a modeling change. Future planned entries removed by an interruption no longer influence subsequent departure calculations. Already calculated trips are not rerouted.
Model boundaries
A facility tagged gateway can offer activities outside the modeled district. Choice and anchor assignment prefer reachable in-model candidates; gateways form a fallback tier within the candidates considered. A gateway trip records travel to that boundary and activity there. It supplies no regional network, onward journey, or inferred external destination. Entry/exit schedules separately describe when a person is present in the modeled area.
Use behavior and interpretation for destination choice and scheduling, and reading results to distinguish traffic, occupancy, and unmet demand.
Regional routing storage
Timetables using graph-lazy-v1 store routing adjacency in packed arrays of graph-edge indices and direction bits. This includes reverse walking adjacency used for transit egress. Origin insertion order, stable edge ordering, directions and costs are preserved; this changes storage rather than mode choice or travel behavior. Returned routes and replay edge identities remain unchanged.
The graph and node index are still retained, and shortest-path searches have their own memory requirements. Packed adjacency is not a guarantee that an arbitrary regional simulation fits in memory. Other scenarios keep map-based adjacency; inputs with duplicate or dangling node identities also retain legacy handling.
Run node --expose-gc --import tsx tools/benchmark-routing-storage.ts map and repeat with packed to compare retained forward-adjacency storage on the same synthetic graph. Compare the reported arc hashes before interpreting memory measurements. This benchmark excludes the shared graph and node index and does not measure complete simulation peaks or transit feasibility.
Regional disconnected-route rejection
Packed regional routing lazily builds mode-specific weak-component labels before point routing. Nodes in different components cannot have a directed route, so the router returns the same unreachable result without expanding a full search tree. Nodes in the same component still use the ordinary directed search; a component match never establishes one-way reachability. Disabled edges and other modes do not join components. Reverse views share the same labels.
The labels retain four bytes per graph node per queried mode. Construction uses an additional temporary four bytes per node for union sizes, and scans the source edges once per queried mode. This adds initialization work and memory; regional benchmarks must establish the benefit. Legacy adjacency handling and route tie ordering are unchanged. This optimization does not accelerate timetable search itself or establish full-simulation performance.
Infeasible arrival-deadline searches
After searching the constant-deadline window, arrival-deadline routing may need an exhaustive scan of earlier departures because the maximum journey duration makes feasibility nonmonotonic. For tails of at least eight candidates, it first runs an earliest-departure feasibility search bounded only by the arrival deadline. Failure rejects the entire tail. Success still requires the ordinary scan with all duration limits; the relaxed itinerary is never returned to the simulation. Transfer restrictions, accessibility and boarding limits apply to both searches. This shortcut targets impossible connections, not changes to mode preferences.
For validated packed regional graphs, the result's disconnected-network warning reuses the router's node index and counts weak components with typed arrays (five temporary bytes per node). It avoids constructing a second adjacency map. All enabled edges count regardless of mode or direction, exactly as in the legacy warning. Unvalidated indices retain the legacy calculation.
Transferring a batch graph
new Simulation({ graph, graphOwnership: 'transfer', facilities, scenario }) is an opt-in ownership transfer for exclusively owned batch inputs. It validates and replaces individual graph rows before validating graph-wide references, avoiding a second complete row collection during construction. The successful constructor freezes the transferred arrays. The caller must relinquish all use of those arrays immediately, including after a validation failure, which may leave partially normalized rows. Frozen arrays cannot be transferred. Retained references to original individual rows are not frozen or modified, but retaining them defeats the intended memory saving.
The default graphOwnership: 'copy' retains existing detached-copy behavior.
For regional inputs, await Simulation.create(options, signal) uses the same normalization and ownership rules but yields to the event loop every 100,000 rows. This gives the runtime collection opportunities and observes cancellation between batches without forced garbage collection or a Node-specific API. The synchronous constructor remains available. Transfer relinquishes the arrays on failure or cancellation as well as success; do not reuse partially normalized inputs. Default copy mode preserves caller-owned arrays and records. Do not edit inputs while asynchronous creation is in progress.
On this immutable path, normalized mode arrays may share frozen storage. A bounded per-construction cache preserves the exact sequence, including order and duplicates; it never freezes caller-owned arrays. Ordinary mutable graph parsing and decoded results retain independent arrays. This reduces repetitive allocation without changing feasible modes or their ordering. Small scalar-only extension records may also share frozen storage, with a bounded per-construction cache. Property order and signed zero are preserved; nested or large metadata is not interned. Mutable parsing and decoded results continue to detach these records.
Asynchronous creation also yields between cross-reference validation, facility parsing, scenario preparation and freezing. A standard Scenario already owns validated, deeply frozen configuration; asynchronous construction reuses that internal snapshot instead of allocating another copy. Public Scenario.toJSON() and ordinary run results remain detached. Overridden serializers retain their detached-and-frozen behavior. Graph rows freeze in batches of 100,000; nested data within one row remains synchronous. The array containers freeze after their contents. Cancellation may therefore leave transferred arrays partially normalized or frozen; they remain relinquished. Individual schema checks and overridden scenario copying/freezing are synchronous, so cancellation is cooperative rather than immediate. Yielding is not a memory ceiling and does not establish full-population performance. The expanded regional diagnostic supports testing this path, but packaged public construction and complete execution/export/playback remain required integration gates.
Both paths apply the same node/edge schemas, defaults, strict graph shape, duplicate-ID checks and reference checks. Facilities remain detached. Returned ordinary run results still contain mutable detached graph copies; this option addresses construction memory only and does not eliminate result-copy or routing-index costs.
Canonical hashing buffers JSON tokens inside the iterative traversal before yielding chunks. It retains complete-token UTF-8 boundaries, numeric-key ordering and the existing FNV-1a hash contract. This reduces iterator and key-filter allocations; it does not omit graph data from provenance or change historical checksums.
Graph validation uses an exact open-addressed row-index table for large ID collections, retaining row offsets in a typed array instead of another collection of strings. Collisions compare the original normalized IDs; this is not a probabilistic duplicate filter. Small graphs retain Set-based checks. Duplicate and dangling-reference errors keep their existing paths and ordering.
Combined timetable-reference validation and routing reuse the same compact lookup strategy for large node/edge collections. Lookups retain original row identity and Map-compatible last-write behavior; schema-level duplicate rejection is unchanged. Small collections use Maps built without intermediate tuple arrays.
Regional routing retains at most four mode frontiers and twenty million total frontier-node slots. Expanded graphs reduce the retained mode count (for example, two frontiers for 8.4 million nodes) instead of switching to object-heavy search at five million nodes. Graphs exceeding the aggregate allowance still use the point-to-point fallback. This bound covers dense buffers, not every route-search allocation; measured process memory remains the operational limit.
Walking-transfer cache entries are built directly from the selected shortest-path predecessor tree. Shared branches are retained once instead of expanding every stop path and compressing those overlapping paths afterward. Stop order, selected parallel edges and cumulative accessibility are unchanged. Both initial and cached results expand geometry lazily into independently mutable arrays. Retained view metadata counts toward the existing cache budget. This changes preparation work, not travel costs or route selection.
Bounded walking-tree searches can traverse packed adjacency with a callback that exposes the existing edge and its endpoints. They allocate a predecessor arc only when a relaxation improves a node. Iterable traversal remains available, and both paths preserve stable edge order, reverse direction and distance/edge-ID ties.
For local batch jobs, simulation.runWithSharedGraph(options) returns the same simulation data with an explicitly read-only, deeply frozen input graph. The graph may be shared by successive results and remains valid after disposal. Agents, trips and other result records retain their usual detached semantics. Ordinary run(options) still returns mutable, detached graph records. Shared graph results are not available in worker execution mode.
encodeRun and saveRun accept either result form. Export reuses only a graph identity registered after Simulation validation and deep freezing; user-provided flags or frozen arbitrary objects do not bypass validation. Combined input references and all other fields remain validated. Decoding incrementally normalizes the privately decoded graph before checking combined references, preserving mutable decoded results without a second simultaneous graph copy.
Small headers retain grabm-chunked-gzip and its single base64 header string. Headers exceeding 3 MiB compressed use grabm-chunked-gzip-v2: header is an ordered array of independently base64-encoded pieces of one gzip stream, each at most 4 MiB of text. Decoding feeds their bytes to one streaming decompressor and checks the gzip CRC, size and canonical result checksum. This avoids the runtime's single-string limit for regional networks. Result-array segments and canonical checksums retain their existing meaning. The current decoder reads both formats; older engine versions cannot read v2 headers. Hosts must preserve the format tag and header array when transporting or importing archives.
Compressed pieces and decoded result arrays still consume memory; regional round-trip scale verification remains separate from these ownership guarantees.
Shared graph results can also be passed directly to analyzeRun. Custom analytics registries may use MetricRegistry<SharedGraphRunResult> to expose the read-only graph contract to their plugins. The default registry type remains RunResult for existing callers. Analysis output owns its mode arrays; it does not return mutable aliases into the shared frozen graph.
Regional execution indexes
Regional execution uses compact row-index lookups for node positions, routing indices and sparse observation membership instead of duplicating every graph ID in additional JavaScript maps or sets. Duplicate and missing-ID lookup behavior is preserved; graph validation remains authoritative. Routing origin order uses typed storage and retains first-seen traversal order, including reverse views. These changes do not remove network records or change route tie-breaking. Sparse observations still reject unknown edges and retain existing zero reconstruction.
Evicting a regional mode frontier reuses its dense buffers after resetting all search state, adjacency and mode costs. Cycling through more modes than the retention limit does not allocate another full-network workspace. This preserves route ordering and the existing retained-node budget; it does not establish a regional runtime bound.
Canonical streaming serialization reuses JSON tokens for at most 256 property names of at most 128 characters per traversal. The cache retains no graph rows and changes neither canonical bytes nor checksums. Longer or additional names are serialized normally.
Measured regional integration checkpoint
An external PreFORM diagnostic on October 19, 2026 used engine revision 42c707a, 8,423,265 nodes, 23,547,736 edges, 16,625 dated transit journeys and 32 calibration households (88 people). Public asynchronous initialization, shared-graph execution and archive export completed within a 20 GiB V8 heap: 39 minutes 51 seconds total, with 18.81 GiB peak sampled resident memory. A fresh-process public decode verified the complete canonical checksum and graph counts in 7 minutes 31 seconds, peaking at 17.39 GiB. Decoded records retained the ordinary mutable ownership contract.
This is an external integration checkpoint, not a bundled benchmark or a runtime guarantee. Concurrent host activity affected timing. It does not establish 12 GiB worker readiness, full-population performance, application playback, or behavioral agreement with travel reference data. Hosts must measure their complete publication pipeline and reserve realistic memory before admitting concurrent regional jobs; a successful archive export alone is insufficient.
Walking accessibility analysis
Walking accessibility uses a reverse multi-source shortest-path search for each activity with resident demand. The search stops only after every demanded origin has a settled nearest-destination distance; unreachable origins require exhausting the reachable network. Activities without demand retain their reported destination counts but do not run a search. Mean nearest time remains unbounded, even though coverage is reported at 5, 10, and 15 minutes. This optimization does not change simulation mode choice or trip routing. Regional runtime improvement has not yet been measured.
Scheduling progress
Daily event preparation reports progress after each batch of eight agents and checks cancellation between those batches. The original agent, event and random stream order is preserved. This fraction counts prepared agents; it is not an elapsed-time estimate. Shared household departure coordination runs before the agent batches, and an individual route search can still be long. These updates do not claim interruption inside a synchronous route search or lower routing cost.
Incremental frontier allocation
Incremental regional searches use packed adjacency's visitor traversal. Improving predecessors retain existing graph-edge references and numeric node indices; examined arcs no longer require a separate temporary object and generator yield. A four-byte predecessor index per node replaces individually allocated retained arc objects. Reset clears edge references before reusing the numeric buffer. Iterable adjacency remains a supported fallback. Expansion order, equal-cost edge tie-breaking, deferred target expansion and returned paths remain unchanged.
A 30,000-node synthetic comparison against the previous implementation preserved all route hashes across four alternating passes, removing 1,079,652 temporary yielded arc objects per pass. This counts one allocation category, not total heap allocation. Regional runtime improvement remains unverified; a live regional event sample motivating this change spent roughly 47% of sampled time in garbage collection and 27% in incremental expansion.
A separate 100,000-node retained-allocation experiment preserved route hashes while reducing the dominant sampled predecessor allocation from about 4.7 MB to a small residual. The added numeric buffer occupies 0.4 MB and was allocated before sampling. This experiment excludes graph preallocations and discarded objects; it does not establish total memory savings or regional runtime gains.
An earlier incremental priority queue optimization swapped entries using local references, avoiding a temporary destructuring array per heap swap. A 100,000-node synthetic allocation sample with collected objects included preserved route hashes and estimated 214 MB before versus 134 MB after this change. Those estimates describe one synthetic workload, not retained heap size or a regional speedup. The change was motivated by a live scheduling sample dominated by routing allocation and garbage collection; regional verification remains necessary.
Each frontier also reuses one synchronous arc-relaxation callback. Expansion updates its current distance before visiting arcs, instead of allocating a new closure and captured context for every expanded node. Four alternating 100,000-node fixture passes preserved route hashes and estimated 133–134 MB of allocations before versus 13–14 MB after callback reuse. These sampling results include collected objects and exclude preallocated buffers. Full regional runtime, memory and completed-result verification remain separate gates.
Graph-derived transfer cache entries reuse frozen metadata views. Geometry getters return fresh arrays only when an itinerary is materialized; the cache never keeps expanded paths. The bounded cache charges eight additional logical units per transfer for retained view metadata, alongside the compact tree. This reduces repeated view allocation without changing transfer costs, order or accessibility. The independent mutable views used by other compact-transfer consumers retain their existing behavior. Regional runtime gains require a full-scale measurement.
The current frontier queue stores node indices and distances in parallel numeric arrays, removing the short-lived object previously allocated for each successful relaxation. It preserves duplicate heap entries, distance/node-ID ordering, equal-cost edge selection and deferred target expansion. Both arrays are cleared on reset; no extra per-graph-node buffer is introduced. A 10,000-node grid with 80 origins, 480 queries and 798,347 expansions produced identical route hashes. One allocation sample including collected objects measured about 55.3 MB for the object queue and 34.0 MB for the numeric queue. This is a synthetic allocation comparison, not a regional runtime guarantee. The completed regional predecessor profile spent 36.8% of its post-constructor sampled time in garbage collection; that profile alone cannot attribute all collection cost to the queue.
Packed adjacency also accepts an already-known origin index when the caller shares the exact node-index object. Otherwise it returns control to the existing string-based traversal. Improving relaxations reuse the expanding predecessor index when its string identity matches, retaining the original lookup fallback for other adjacency implementations. This introduces no per-node or per-edge buffer. A synthetic 480-query grid preserved route hashes and 798,347 expansions while reducing index lookups from 4,890,211 to 3,201,480. These exact operation counts do not establish regional runtime gains.
Validated regional graphs now share two numeric edge-endpoint arrays across all mode adjacencies and reversed views. Searches can visit numeric neighbors without rehashing node IDs for each relaxation. The shared cache retains exactly eight bytes per source graph edge (about 179 MiB for 23.5 million edges), rather than separate neighbor arrays per mode or directed arc. Graph edges, node ordering, mode filtering, stable arc order and cost evaluation are unchanged. A different edge-array or node-index identity falls back to the existing string traversal. Legacy graphs with duplicate or dangling IDs still use their original router.
Generated multimode/reversed graphs check exact paths and expansion order, including zero costs and equal edge IDs. A synthetic 480-query grid preserves route hashes and 798,347 expansions while reducing search index lookups from 3,201,480 to 39,432. This is operation-count evidence, not a regional runtime result; the added memory must remain inside the registered process limits.