Appearance
Stored datasets and buffered replay
Small runs can stay in memory. Large applications can execute and prepare a dataset on their backend, then send the browser a reference instead of a complete result. These are portable library components: your application owns job scheduling, authentication, URLs, storage durability, admission limits, and retention.
Try the optional Docker backend example to submit jobs and replay stored resources over HTTP using npm run up and npm run down.
Prepare on the backend
ts
import type { SimulationInputData } from '@grabm/abm'
import { runToDataset, createFileDatasetReader } from '@grabm/abm/node'
import { openRunDataset } from '@grabm/abm/datasets'
/** The directory must not exist; its parent must exist. The host owns authorization and retention. */
export async function prepareStoredRun(input: SimulationInputData, directory: string) {
const reference = await runToDataset(input, directory)
const source = await openRunDataset(
createFileDatasetReader(reference.directory),
reference,
)
try {
const firstWindow = await source.window(source.scene.startMinute)
return { reference, summary: source.summary, firstWindow }
} finally {
source.dispose()
}
}runToDataset owns a disposable Node child process. Computation and preparation stay inside that process; only a manifest reference returns to the parent. The output directory must be new, and its parent must already exist. Cancellation terminates the process and removes its unpublished output. maxHeapMb optionally sets its V8 old-space ceiling; it is not a total process-memory ceiling.
The engine still holds its complete state and result in memory. Backend storage does not make execution out-of-core. Measure representative workloads before choosing job concurrency or process limits. The library does not install a server or database.
Connect your own storage
writeRunDataset(result, writer) prepares an existing result. A writer implements write(key, Uint8Array, signal) and cleanup(), owning one fresh dataset namespace. It must not expose partial resource writes. Resources are written before manifest.json; the manifest is the publication marker. Failed preparation calls cleanup(). Keep cleanup restricted to that dataset; object-store hosts can separately collect abandoned unpublished namespaces after a process crash.
ByteReader.read(key, signal) returns resource bytes. The package supplies MemoryDatasetStore, createFileDatasetReader, and createHttpReader. HTTP hosts can supply their own fetch function for authentication. Resource URLs must stay within the dataset base URL. Serve immutable resource bytes without rewriting them.
ts
import { createHttpReader, openRunDataset } from '@grabm/abm/datasets'
const source = await openRunDataset(
createHttpReader('https://example.com/datasets/run-123/'),
{ manifestKey: 'manifest.json', runHash: savedRunHash },
{ cacheBytes: 64 * 1024 * 1024 },
)
const detail = await source.agent(source.scene.agents[0].id)
// Dispose when the final owner releases this source.
source.dispose()What is stored
The schema-described manifest indexes input, provenance/summary/prepared analytics, static graph and slim agents, replay windows, and agent/trip detail pages. JSON resources are independently gzip-compressed and verified with SHA-256. The complete archive used by encodeRun is not required for replay.
Replay windows start at five minutes and subdivide when dense, down to approximately one second. Resources default to a four-MiB uncompressed limit; detail pages also split by size. An oversized single record, input, static scene, or minimum window fails explicitly instead of creating an unreadable dataset. Increase maxResourceBytes with matching reader limits only after measuring the workload. These limits also mean this first format is not suitable for arbitrarily large individual records.
Playback and inspection
createMemoryRunSource(result) and openRunDataset(reader, reference) implement the same RunDataSource: scene, summary, window, agent, trip, and disposal. Inspection histories are fetched on demand, not included in every replay window.
ts
const layer = new ReplayLayer({ scene: threeScene, source })
const controller = new PlaybackController({
startMinute: source.scene.startMinute,
endMinute: source.scene.endMinute,
simulationMinutesPerSecond: 10,
prepareFrame: (minute, signal) => layer.prepareFrame(minute, signal),
onFrame: (minute) => layer.seek(minute),
})
// Cleanup order: clock, rendering objects, then caller-owned source.
controller.dispose()
layer.dispose()
source.dispose()The controller holds its clock and last frame while data buffers. Its state exposes buffering and error; retry() retries the pending time. Included playback controls show buffering and a retry action. Obsolete seeks are cancelled and cannot overwrite the latest frame. A source owns one playhead; use separate sources for independent simultaneous playheads.
The stored reader retains an LRU temporal cache, defaulting to 64 MiB, and prefetches the next window when it fits beside the active one. Retained decoded size is estimated as four times the uncompressed JSON bytes. This is accounting, not a measured JavaScript heap guarantee. cacheUsage and staticBytes report separate estimates. Detail pages are not cached by the source (inspectionBytes is zero); callers own their returned details. Static data, caller-held frames/details, parsing/decompression temporaries, rendering resources, and browser overhead remain outside the temporal budget. Readers reject windows larger than their budget and resources larger than their read limit.
Application architecture
PreFORM's existing backend jobs and windowed playback demonstrate this ownership split. Its deployment, package versions and adapters are maintained in that repository. A host can call the Node helper from its existing job runner, store the reference in its own database, and serve dataset resources through its API. The optional backend example demonstrates the public interfaces without introducing PreFORM types or a deployment requirement into the library.
Conditioned presence and source labels
Datasets preserve optional conditioned presence intervals in scene agents and source journey labels in trip detail. Use the supported replay readers and position sampling so repeated visits disappear between exit and re-entry. A first initialObservation begins presence only at its supplied departure. Older inputs without these optional fields retain their existing interpretation. When inspecting records, distinguish source primary mode/purpose from the executed local leg; see result accounting.