viv icon indicating copy to clipboard operation
viv copied to clipboard

Host-supplied RNG / seed hook for deterministic runs

Open possibly opened this issue 7 months ago • 1 comments

Problem

Viv-runtime calls Math.random() directly in several places with no way to inject a seeded RNG:

  • src/interpreter/interpreter.ts — chance-gated expressions
  • src/role-caster/casting.ts — role assignment dice
  • src/utils/general-utils.ts — ID generation, shuffles, Gumbel noise, Box-Muller sampling

Because the host adapter can't override any of this, the same world setup + same inputs produce a different action trace on every run.

Why it matters

This blocks several downstream workflows:

  • Snapshot / golden-file testing against visualizers and other UIs (exact action counts, memory salience, sifting-match tallies all drift between runs).
  • Deterministic replay of a known-interesting run for debugging or demos.
  • CI integration tests on host apps — forces every assertion down to loose ranges and substring matches, losing signal.

In practice it means anyone building tooling on top of Viv has to commit opaque binary fixtures and regenerate them by hand, instead of deriving them from a reproducible seed.

Suggested shape

Either (or both) of:

  1. initializeVivRuntime({ contentBundle, adapter, seed: 42 }) — single entry point, runtime threads a seeded PRNG through its callsites.
  2. An optional rng: () => number and/or provisionID: () => UID on HostApplicationAdapter — host retains full control, can wire in its own seeded generator.

Option 2 composes more cleanly with hosts that already have their own RNG (e.g. game engines).

Context

Versions: compiler 0.11.1, runtime 0.10.2.

possibly avatar Apr 23 '26 02:04 possibly

@possibly This one has been on my to-do list for a minute now, so thanks for the nudge!

You can now supply an RNG via the optional rng() adapter function, with seeding and state maintenance being the host application's responsibility. If it's present, Viv will call this function whenever it needs a random number.

The update is shipped in runtime v0.11.0: npm install @siftystudio/viv-runtime@latest.

One consideration here: determinism in Viv will still break down if some external force, like a player, introduces nondeterminism into either the storyworld state or the host's invocation of Viv. For instance, if a player interaction causes a character to act on a timestep when they otherwise wouldn't have, that character will use up random numbers they otherwise wouldn't have used, leading to stream divergence.

To solve this, Viv would need to a) allow hosts to expose keyed RNGs, and b) generate per-event keys, so that characters make the same decisions on the same events, even if new events were introduced relative to a previous run. The latter bit is a fairly big lift, not addressed here, but it's on my list.

james-owen-ryan avatar May 15 '26 08:05 james-owen-ryan