Skip to content

Input traces: record a session's inputs by tick and replay them exactly (R49) - #1168

Merged
transfix merged 3 commits into
masterfrom
feat/input-trace
Nov 14, 2026
Merged

transfix merged 3 commits into
masterfrom
feat/input-trace

Conversation

@transfix

Copy link
Copy Markdown
Owner

R49 of the GRL-SNAM Laboratory spec (modernization/grl-snam-laboratory-camera-rigs-and-base-nav-demo.md, §7 and §9 Phase 6), the libcvc core: record a session's input trace and seed, then replay it deterministically, so a live session becomes a regression benchmark. This is Phase 5a of the plan for proving the learners learn (doc 35). GRL-SNAM's live --record-trace / --replay-trace (Phase 5b) builds on it.

The format: cvc.input_trace/v1 (docs/INPUT_TRACE.md), JSON lines:

{"schema":"cvc.input_trace/v1","header":{seed, dt, fixed_dt, phase, start_tick, world_id, world, agents, settings, watch, build, meta}}
{"tick":120,"set":{"path":"nav.vehicle.vmax","value":"6"}}
{"tick":300,"event":{"name":"nav.retarget","args":{"agent":2,"goal":[0.5,-0.25]}}}
{"tick":306,"check":"sha256:..."}
{"end":{"tick":1200,"ticks":1200,"hash":"sha256:..."}}
  • The header holds the starting state:
    • the world id, and the world itself where libcvc can build it;
    • each agent's start, goal and policy (sha256:<hex> or default);
    • the watched keys' values at the start;
    • the libcvc build that recorded it.
  • Records are stamped with the world_clock tick. A record at tick T was made after quantum T and before quantum T + 1, so the first step after T sees it.
  • The end holds the tick count and the final state hash.
  • Numbers are exact. Doubles are written shortest round-trip, so float32 knobs come back bit for bit. A 64-bit seed is written whole.

The library (cvc/core/input_trace.h) depends on no simulation.

  • input_trace reads and writes the format. A bad file is refused, naming the line.
  • input_trace_recorder is a plain object the host owns (an app, a Runtime, a Python host), with no statics. It watches prefixes of the app's state tree (default nav, nav_plant, run, world):
    • outputs are skipped: keys whose access property is telemetry, and sim_world's published nav.agents and nav.settings;
    • host verbs go in with event(name, args), and state hashes with check(hash);
    • on_write (the default) stamps a write as it lands. on_sample records what changed when the host calls sample(), for a host whose inputs come from another thread;
    • a clock that goes back breaks the recording, and finish() says so.
  • input_trace_player puts the clock in replay mode and moves it itself:
    • rewind() goes to the start tick and writes the header's settings;
    • apply_due() writes the sets to the tree, and hands the events to a handler or returns them;
    • next_quantum() moves the clock one tick on;
    • verify(hash) compares against the checks and the end, and keeps the first tick that differed;
    • run() and advance() loop for a C++ host. A Python host steps quantum by quantum.

A sim_world's trace (cvc/nav/sim_world_trace.h):

  • trace_header(world, options) describes a kinematic world before its first step. It records:

    • the whole config;
    • the truth and prior maps, run-length coded with their sha256;
    • the planes, the colours and each agent's policy;
    • the agents' starts and goals as the normalized floats the drive keeps.

    A world v1 cannot rebuild is refused with the reason. allow_incomplete instead records it for a host that rebuilds the world itself.

  • world_from_trace(header, library, policy_files) rebuilds the world. policy_files swaps in another build of a policy.

  • state_hash(world) is sha256 over the tick and each agent's id, position, goal, heading, speed, mode and reached flag (their bits).

  • nav's verbs as events: trace_retarget, trace_set_pose, trace_override and trace_add_obstacle, with apply_trace_event to play them back.

  • replay_trace(app, trace) is the headless replay.

  • sim_world gains read accessors for its normalized columns (positions_normalized, goals_normalized, headings, speeds_normalized) and prior().

cvc trace info | verify (cvc-cli). The logic is in the library: cvc::describe(trace) and cvc::nav::replay_trace.

  • info prints the world, the step, the span, the agents and their policies, and the inputs by key and by verb.
  • verify replays headlessly and compares every hash. It exits 1 when the replay departs, naming the tick.
  • --policy INDEX=FILE replays on another build of a policy. --threads N sets the threads a step runs on.

pycvc (pycvc_trace.i):

  • input_trace, input_trace_recorder(app, clock[, watch, ignore, skip_telemetry, on_sample]) and input_trace_player(app, clock, trace). Both keep the app alive.
  • The nav side: nav_trace_header(sim, world_id, seed=, policies=), nav_trace_state_hash, the nav_trace_* verbs and nav_trace_apply_event.
  • nav_sim_world_from_trace(header) returns a sim_world handle.
  • nav_trace_replay(app, trace, keep_poses=) returns a dict with the result and, with keep_poses, the poses as numpy.

Limits (v1), also in the docs:

  • The kinematic plant only. A plant, terrain, a material stack, per-agent vehicle columns or a multi-disc body is refused.
  • Jolt is deterministic only within one binary, so a Jolt trace could replay only on the build that recorded it. The header's build says which build that was.
  • No going backwards. sim_world has no save/restore, so seeking backwards rebuilds the world and re-simulates from tick 0 (rewind()).
  • Host-side behaviour is not recorded. An external force, yielding, routes and intents are the host's to record as its own events.

Tests (Linux Release, gcc 13):

  • input_trace_test, 7 tests:
    • the lines round-trip byte for byte: a seed past 2^63, NaN, a denormal, escapes, CRLF and blank lines;
    • the parse errors name their line;
    • the recorder records only the watched, changed, non-telemetry keys, at their ticks, and the file matches the trace;
    • on_sample keeps the last value before a sample;
    • a clock that goes back breaks the recording;
    • a toy simulation replays byte for byte, through the file too, and quantum by quantum after a rewind();
    • a perturbed set departs at the step that consumes it, and the first check that disagrees is the first after that step.
  • nav_trace_test, 6 tests, on a 64 x 64 kinematic world with three agents, sensing on:
    • the header rebuilds the world: same hash at the start and after 120 steps;
    • a live session replays to byte-identical poses at every step, and the same hash. The session is 600 uneven frames on a live clock (13.3 s, 221 steps), with UI writes to nav.*, a retarget and an obstacle between frames, and the world pulled before each step and published after each frame. It replays headlessly from memory and from the file, and on 4 threads too;
    • a perturbed trace diverges at the right tick: a changed retarget at the first check after it, a changed top speed at the first check after the step that consumes it;
    • two policy builds differ only where the policy differs (acceptance test 6). Agent 2 drives a policy file that a second build changes near walls. Its coefficients first differ at step 53 and its pose departs at step 55. It never departs before the coefficients do. Agents 1 and 3 match the live run for all 221 steps;
    • worlds v1 cannot rebuild are refused or marked, and a host's own event stops the headless replay with its name;
    • nav's events apply by agent id, and malformed ones are refused.
  • cvc_cli_test: CvcCliTest.TraceInfoAndVerifyReplayASession checks that info and verify exit 0 on a recorded session, verify exits 1 on a perturbed one, and bad arguments are refused.
  • pycvc_input_trace (test_pycvc_input_trace.py):
    • it records a session through state_set and the verbs;
    • nav_trace_replay matches;
    • a Python host loop with the player ends on byte-identical poses;
    • a perturbed trace departs;
    • the error cases are refused.
  • clang-format 18 on the changed lines: clean.

The release (3.7.15 in the plan) is Joe's call.

…ly (R49)

cvc.input_trace/v1 (docs/INPUT_TRACE.md), JSON lines: a header with the
starting state (seed, dt, the world, the agents' starts, goals and policy
hashes, the watched settings, the build), set and event records stamped
with the world_clock tick, optional state-hash checks, and an end with the
final hash.

cvc/core/input_trace.h: the format; input_trace_recorder, a host-owned
object that watches prefixes of the app's state tree (outputs skipped by
their access property) and takes the host's events; input_trace_player,
which plays them back at their ticks with the clock in replay mode and
compares the hashes.

cvc/nav/sim_world_trace.h: a kinematic sim_world's header and rebuild, its
state hash, nav's verbs as events, and the headless replay. cvc-cli
`trace info|verify` and the pycvc binding (pycvc_trace.i) use them.

Tests: a live session on a small world replays to byte-identical poses and
the same hash; a perturbed trace departs at the step that consumes the
perturbation; one trace on two policy builds departs only for the agent on
the changed policy, never before its coefficients differ.
trace_json::value kept an object's members as (key, value) pairs inside
value itself, so std::pair needed value complete before it was: GCC
deferred that, clang does not (the clang-tsan lane). The members are now
a key list beside the values.

A number was read with an istream, and libc++'s refuses a subnormal as
out of range (the macOS lanes failed the round trip of 1e-310). strtod
reads it, with the classic-locale istream left for a locale whose
decimal point is not '.'.
@transfix
transfix merged commit a286873 into master Nov 14, 2026
30 of 33 checks passed
@transfix
transfix deleted the feat/input-trace branch November 14, 2026 06:33
transfix added a commit that referenced this pull request Nov 14, 2026
Both conflicts are two features added side by side, kept both:
- src/cvc-cli/main.cpp: the includes for param_cli.h (cvc skeleton) and
  input_trace.h (cvc trace).
- src/cvc-cli/cvc_cli_test.cpp: the cvc skeleton tests, then the cvc trace
  tests.
transfix added a commit that referenced this pull request Nov 14, 2026
#1203 gives every cvc command its app as an argument and removes cvc_app().
- src/cvc-cli/main.cpp: the conflict was cmd_skeleton beside
  cmd_tetrahedralize2's new signature; kept both, and cmd_skeleton takes
  cvc::app & like the rest.
- cmd_trace (#1168) still had the old signature and called cvc_app(), so
  master's cvc-cli does not build; it takes cvc::app & too, the same change
  as the separate fix for master.
transfix added a commit that referenced this pull request Nov 14, 2026
…le-pick-upload

Conflicts, each side kept:
- ImGuiBackend.h: master's set_clipboard on the document's app, then this branch's pick_files
  and begin_frame.
- net_intrinsics.cpp: master's net verbs on the app with its OpenUrlLimit, then this branch's
  http-upload provider.

The upload follows #1203: perform() and http_starts_async() take the app, and the started
upload's StartedRequest gets the app it starts on (its go() calls cvc::net::start(*app, ...)).

Master's ariadne_runtime_test doesn't build: #1180's three rich-text cases call load_string
with one argument, and #1203 made it take the app. They pass their test's app now.
transfix added a commit that referenced this pull request Nov 14, 2026
… app

#1203 gives every cvc command its app as an argument, removes cvc_app() and
makes cvc::ariadne::load_string take the app. It merged after #1168 and #1180,
whose new code still used the old forms, so master does not build:
- src/cvc-cli/main.cpp: cmd_trace (#1168) takes cvc::app & like the other
  commands and replays on it, not cvc_app().
- src/cvc/tests/ariadne_runtime_test.cpp: #1180's three AriadneRichText
  tests pass their app to load_string; each already makes one.
transfix added a commit that referenced this pull request Nov 14, 2026
…ted-gas

#1197 is in master as its squash, so the conflicts were #1197's own lines
against this branch's changes to them: this branch's are kept.

Two compile breaks on master, fixed here as #1203 fixed its own callers:
- ariadne_wasm_browser_test.cpp (#1197) called register_script_engine(engine)
  and unregister_script_engine("wasm"), which #1203 removed: the fixture
  registers nothing, as each test's AppRuntime calls use_script_engine.
- ariadne_runtime_test.cpp (#1180) called load_string(yaml), which #1203
  made load_string(app, yaml): the three calls pass the test's app.
transfix added a commit that referenced this pull request Nov 14, 2026
Master gained #1203 (this branch's base), #1192 (state_exec Stage S,
several steps a pick) and ten others.

Conflicts, both #1192's run code against this branch's registry work:
- async_scheduler.cpp: the slice setters from #1192, set_cycle_registry
  from here (it also gives the evaluator the registry). The cycle check
  takes the registry in the evaluation context (the one given, else its
  evaluator's own) where #1192 fell back to the thread's own, which this
  branch removes; collect_cycles_if_due now takes a registry. A run's
  steps go through the same context as its first; step_run's drain check
  is check_not_in_kernel, as step_once's is.
- state_exec_groups_test.cpp: OC01's caller-pumped case keeps #1192's one
  step a pick and this branch's watched group. The file's note on leaks no
  longer speaks of a thread's own registry.

Semantic, not textual:
- #1192's Slices tests: SL04's spin-step and SL08's heavy take call_args
  and reach their context through it (eval_deadline_check(a.context()),
  a.context()->data), as this branch's other natives do.
- cvc-cli's trace command (#1168) takes its app, and #1180's three
  rich-text tests pass theirs to load_string. Both landed after #1203's
  last master merge and still used what #1203 removed, so master does not
  build at 7ead20e or 69c7091; #1225 makes the same change there.

Checked on Windows (MSVC Release): full build; groups 28/28; Slices and
run-budget tests 19/19; rich text and heap 10/10; the cycle collector and
registry tests, pycvc_ariadne, CvcCliTest.TraceInfoAndVerifyReplayASession
and state_exec_async_test_slice256, 20/20.
transfix added a commit that referenced this pull request Nov 14, 2026
#1203 (no singletons) moved the URI registry, the HTTP client and options provider, the HTTP
cache's in-flight table, the net and OIDC hosts, the WebSocket table and open-url's clock onto
each app. This branch had changed the same code for threads. The merge keeps both:

- uri.h/uri.cpp: register_uri_handler and resolve take the app (#1203) and keep this branch's
  UriCancelled and UriLocalHandler; the http(s) handlers and the HTTP cache pass the request's
  cancel predicate through to the app's client.
- net_intrinsics.cpp: the providers stay by kind with each call on the calling program's host
  (ictx.host) and its finisher. The requests, fetch and WebSocket verbs take the app, the app's
  WsTable and its OpenUrlLimit (both app slots, got once at registration). open-url stays in its
  host_proxied provider, on the app's OpenUrlLimit instead of a clock of the provider's own.
- oidc_host.cpp: the refresh sends through the app's client with the asker's cancel predicate.
- ariadne.cpp: the Runtime's owner id is counted per app (#1203); has_snapshot asks the app's
  widget registry.
- allowlist.txt: master's (76 lines); the one line this branch removed is gone there too.

This branch's tests move onto the per-app APIs: the removed NetIntrinsicsGuard, L4Guard and
NetHostGuard go, set_http_client and send take the app, live_groups takes the app by reference,
and the worker pump counts come from the pool's stats (pool_stats::worker_pumps) where the
process-wide exec_pool_worker_pumps_total() was, in the tests, mt.ariadne_docs and the docs.
Also fixed: #1180's three rich-text tests called load_string without the app #1203 added.
transfix added a commit that referenced this pull request Nov 14, 2026
cmd_trace (#1168) still had the old command signature and called cvc_app(), which #1203
removed, so cvc-cli did not build on master. It now takes the app like the other commands
and replays the trace in it. The same change as #1225's, so either can land first.
transfix added a commit that referenced this pull request Nov 14, 2026
… app (#1225)

#1203 gives every cvc command its app as an argument, removes cvc_app() and
makes cvc::ariadne::load_string take the app. It merged after #1168 and #1180,
whose new code still used the old forms, so master does not build:
- src/cvc-cli/main.cpp: cmd_trace (#1168) takes cvc::app & like the other
  commands and replays on it, not cvc_app().
- src/cvc/tests/ariadne_runtime_test.cpp: #1180's three AriadneRichText
  tests pass their app to load_string; each already makes one.
transfix added a commit to CVC-Lab/GRL-SNAM that referenced this pull request Nov 15, 2026
… exactly (Phase 5b, R49) (#184)

On libcvc's input trace (cvc.input_trace/v1, transfix/libcvc#1168).

- grl_snam/ariadne/_trace.py: Recorder (the app's world_clock at 0.01 s, the navigator every 5
  quanta; the header describes the first arm's world with the arms, seed, start, goal, plant
  and frame in its meta; writes to nav/nav_plant/run/world recorded as they land, sim_world's
  own telemetry skipped; a Retarget is nav's own nav.retarget; the state's hash each frame) and
  Player (the clock in replay mode, the sets at their ticks, nav's events to every arm's world,
  every hash compared). The hash is the arm's own for one arm, so libcvc's headless replay
  (cvc trace verify) replays a one-arm trace; over every arm's world for several.
- live: --record-trace (without --arms: one arm, the trained policy) and --replay-trace
  (the recorded arms, or --arms: other policies on the same inputs). run_arms keeps its worlds
  in a holder that a seek back rebuilds (sim_world has no restore: from tick 0 again). Headless
  replay runs to the end and exits 1 when the recorded policies depart; a window has a Trace
  window with a Position slider and Restart. v1: the kinematic plant.
- tests/test_lab_acceptance.py: the Laboratory's §9 tests 5 and 6: one retarget for every arm
  with distinct Stats rows; exact replay (byte-identical poses, the same final hash); a one-arm
  trace in libcvc's own replay; seeking back; two policy builds matching until the first tick
  their coefficients differ. The trace tests skip on a pycvc without input traces (3.7.13).
transfix added a commit that referenced this pull request Nov 15, 2026
…ion mid-request loses none (#1243)

On Windows, `pycvc_ariadne_server` (`bindings/pycvc/test_pycvc_ariadne_server.py`) hung until its timeout on every run from #1168 on. Each run printed `Task was destroyed but it is pending!` for its `client()` task. Windows, Winsock, asyncio's proactor and the GIL had nothing to do with it. The garbage collector freed a task that the test never kept.

## Cause

The test started its HTTP client with a bare `host.loop.create_task(client())` and kept no reference to the task.

- asyncio's loop holds tasks only weakly.
- A client of `asyncio.open_connection` waits on its `StreamReader`, and its protocol holds that reader only weakly too.

So while `client()` waits on `await reader.read()`, the only references to the task are a cycle of its own:

```
task -> coroutine frame -> reader -> reader._waiter (future) -> callback task.__wakeup -> task
```

The first full (generation-2) collection that runs during that wait frees the task. `host.stop(7)` never runs, and `host.run()` waits forever.

Whether a full collection lands in that wait depends on how many objects were allocated before it. That is why the hang moved with unrelated changes.

| Run | Live objects after `import pycvc` | Full collections during the run | Result |
|---|---|---|---|
| a286873 build | 30,664 | 1, 31 ms into the client's wait (collected 11, the task among them) | hangs |
| 8857fe8 build (#1168's parent) | 30,264 | none before the test ends (`gens run: [95, 8, 0]`) | passes, 2/2 |
| a286873, unchanged test, N extra live objects allocated before `import pycvc` | | | N ≤ 1000 hangs; N ≥ 1500 passes |
| a286873, `gc.disable()` at the top | | | passes |
| a286873, the task kept in a variable | | | passes |

The other clues from the report fit the same way. `runpy.run_path`, and a sitecustomize without the `importlib` imports, each allocate a different number of objects before the test runs.

## Bisect

- 62d1ff0 + #1216 (37c5ca9): passes.
- 8857fe8 (master just before #1168): passes, 2/2.
- a286873 (#1168): hangs, 2/2. The test file is the same in both.

**#1168 is the commit that turns it on, but it is not the bug.** Its input-trace wrappers (`pycvc_trace.i`) leave about 400 more objects at `import pycvc`, and that moves the run's first full collection into the client's wait.

The bug was there before #1168:

- A `gc.collect()` while `client()` waits hangs the 8857fe8 build the same way.
- A minimal asyncio program with no pycvc and no uvicorn (`start_server`, a client task nothing holds, one `gc.collect()` in the handler) loses its client the same way on Linux's `_UnixSelectorEventLoop` (Python 3.10, WSL) and on Windows' `ProactorEventLoop` (3.12). Keeping a reference fixes it on both.

Linux CI passes only because its allocation counts happen not to put a full collection in that wait.

## Fix

- **`test_pycvc_ariadne_server.py`**: keeps `client_task`. Its `/ping` handler now runs `gc.collect()`, so a full collection always falls inside the request. The test now checks that every task on the loop survives one, the host's tasks and its own. On every platform, the old test with that line added hangs.
- **The arisrv ctest programs**, which used the same unheld idiom:
  - `http_listen.py`'s selftest waits on a stream exactly as `client()` did. It now keeps its task, and its `/ping` runs `gc.collect()` too, so `arisrvx_http_listen` checks arisrvx's own path under a full collection.
  - `service.py` (`arisrvx_serve`): its selftest and its in-flight `/slow` request are kept in `tasks`.
  - `program.py` (`arisrvx_program`, and the arisrvx package's smoke test in publish-cvcpkg.yml) waits on `asyncio.sleep`, whose timer keeps its task alive, so it could not hang this way. It keeps its task anyway, because it is the example people copy.
- **Docs**: the `pycvc.ariadne` module docstring and ARIADNE.md's script-thread bullet now say to keep the task `host.loop.create_task()` returns until it is done.

arisrvx's own serving path was already safe: `_Program.spawn`, `_Served.task` and uvicorn's per-connection tasks are all held. A packaged arisrvx serving HTTP does not hang this way. A service's own code would, on any platform, if it starts a task without keeping it and that task waits on a stream of its own, which is what the docs now warn about.

## Verification

Windows 11, MSVC 14.44, static Release (pycvc core on, pycvc_gl off), Python 3.12.10. Built at this branch (master 4239741 + this commit):

| Run | Result |
|---|---|
| ctest `pycvc_ariadne_server`, this branch's test | passed 3/3 (2.4–3.1 s) |
| master's test unchanged, same build | hangs 2/2 (timeout, `Task was destroyed but it is pending!`) |
| master's test plus only the `/ping` `gc.collect()` (task not kept) | hangs 2/2, deterministically |
| `arisrvx --python http_listen.py --http-listen …`, this branch's program | passed (1 s) |
| the same program with its task not kept | hangs 2/2 (`Task was destroyed`, no selftest line) |
| ctest `-R '^(arisrvx_\|pycvc_ariadne)'` | 25/25 passed |

Linux has not been run here beyond the minimal asyncio repro. pycvc-linux and the arisrvx lanes on this PR are the check there.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant