Attributing PocketIC instructions to Rust source

Research and implementation status, 21 October 2026. The exact artifact/source gate and first offline source-assisted charge view are implemented. Broader profiler design and acceptance criteria below retain their original proposal status where not explicitly qualified by recorded evidence.

The canonical builder accepts --debug-artifacts, forwarded by both RRT/RRts packagers. It keeps release optimization and existing target flags, emits full DWARF, archives the raw Wasm, and uses the pinned compiler's LLVM 23 rust-objcopy to strip debug sections before ordinary SDK preparation. The transformer checks that all other bytes survive stripping and records exact raw/installed body hashes and coordinates. Debug source archives include dependencies, standard library and that Wasm build's generated Rust/graph maps. Implementation and usage notes.

Resolve a saved profile with python3 ver1/tools/wasm-symbolize.py --artifact <name>.manifest.json --trace <trace.json.gz> --output <report.json>; use --llvm-symbolizer <binary> to select the LLVM installation. The analyzer checks the installed uncompressed module hash, raw/map/output hashes and archived source contents. It resolves original block coordinates even when PocketIC omits its large operator dictionary. Static costs remain whole prepaid block charges with source boundary hints; bulk charges retain their operation location. API/page costs and unknowns remain in complete execution ledgers. This first view does not allocate static blocks across source lines or invent dynamic caller stacks.

The 21 October canonical RRts smoke artifact has installed hash fac30ed5114ff05b2f4428b8f0d285b7bdda19ecd502d454f77788142d33b31e. LLVM 19.1.7 successfully reads its LLVM 23 Wasm64 DWARF, including Rust source, columns and library inline frames. The analyzer explicitly requests DWARF short function names: LLVM 19's default linkage-name PC lookup can substitute a nearby symbol while retaining the correct file/line. Qualified physical function labels come separately from exact Wasm ElementIndex symbols and Rust demangling; their tools are recorded. Independent llvm-dwarfdump --lookup checks confirm the questioned source coordinates. Its sidecar is 55,022,984 bytes; the installed Wasm is 3,421,789 bytes. A previous ac3f0441… profile is rejected by the module guard. This establishes real symbol lookup, not execution parity or a performance claim about the new artifact. Evidence is under rrt/tmp/explain-20261021/stable-debug/. The matching populated Heavy16 prefix capture, debug-on-turn/trace.json.gz, records a 575,423-instruction timer and a 507,448,704-instruction executor turn; both ledgers reconcile with zero unexplained instructions. debug-on-turn/source-profile.json resolves 566 of 600 selected block-boundary/bulk-operation points to hashed archived sources; 34 remain unmapped. The selected points cover the 200 largest recorded static blocks and 200 largest bulk sites, not all operators. These are diagnostic windows, not complete Heavy16 performance qualification. No neighboring IC source was modified here.

Recommendation

Build an IC charge profiler, using optimized Rust DWARF as its source map. Preserve origin maps across both the SDK transformation and IC instrumentation. Count existing IC metering blocks and dynamic debits in PocketIC, aggregate them outside canister memory, then symbolize offline. Start with a table of expensive internal functions and blocks; add source heatmaps, memory-fee origins and selected call paths next.

A Rust compiler fork is unnecessary for this design. Ordinary compiler debug information supplies source locations and inline frames. Implementation is required in our artifact builder/SDK transformer, the PocketIC/IC embedder and the analyzer/viewer. Existing PocketIC memory tracing cannot recover PCs or individual stable-memory costs retrospectively.

CPU sampling remains useful for replica wall time, but answers a different question. Wasmtime's guest profiler samples execution and can miss time inside host calls; neither those samples nor Wasmtime fuel implement IC's weighted instruction and memory-fee accounting. Wasmtime profiling documentation, guest profiler accuracy.

What exists and what must be preserved

The build is wasm64 only, pinned by ver1/rust-toolchain.toml to nightly-2026-10-15. An inspected build receipt records Rust 1.101.0-nightly, LLVM 23.1.3, release optimization 3, thin LTO, one codegen unit and debuginfo=0. build-app.py already saves raw/final Wasm, compiler information, source archives, transform-tool hashes and SHA receipts; RRT/RRts packagers call it.

The live memory viewer guide exposes execution totals, entrypoint/callback labels, call context, outcome and accessed/dirty heap page sets. Its page_access_instructions is included in the execution total. Subtracting it does not yield pure compute: stable-memory costs, API charges and other work remain.

IC source findings below refer to read-only /srv/shared/ic, commit ee8086a9773725fd1058832a9400297cf0990112, branch pocketic-memory-access-tracing. This is explanatory source, not a recovered build revision of the measured PocketIC 16.1 binary, SHA-256 1fc9e6f58f7b329a0deb0c1944306a74625293fa56decf9df653ba8ec41fa45c. A profiler build needs its own frozen source/build identity and an explicit parity check against that control. Do not silently identify the two.

1. Produce exact, useful source artifacts

Add a debug-artifact option to the canonical builder, forwarded by both packagers. Keep release optimization, LTO, features, panic behavior, SIMD and memory layout unchanged. Initially emit -C debuginfo=2 -C strip=none for the Wasm build, including dependencies/build-std; archive the unstripped raw Wasm, then strip debug sections before the normal prepare transformation. This enables source profiling without a dev build. Rust documents debug information separately from optimization/debug assertions; line-tables-only is smaller, but full information is the safer first choice for testing inline recovery. Downgrade only after verifying the required frames. rustc options.

Use the unstripped raw Wasm as the initial sidecar, rather than depending on target-specific split-DWARF support. LLVM supports Wasm debug-section removal; never apply --strip-all indiscriminately to a prepared canister because it removes custom sections, including our IC metadata. Record the stripping tool and verify its output. LLVM objcopy documentation, Wasm implementation.

Prefer a single debug-bearing release build whose stripped product is deployed. To attach its symbols to an older qualified debuginfo-zero artifact, require equality of the raw function bodies and final CODE payload, plus all other execution-relevant sections and metadata. A code hash alone does not establish equal imports, data, memory configuration or persistence behavior. Require full deployed-byte equality where achievable; otherwise record the precise permitted debug-only difference. If code differs, profile the newly built artifact and qualify it separately—never attach approximate symbols to the control.

The immutable bundle, keyed by SHA-256 of the exact installed, uncompressed final Wasm, should contain:

  • Raw DWARF-bearing Wasm, stripped raw/final Wasm, SDK origin map and hashes; rustc -vV, tool binaries/versions, Cargo.lock, effective flags/features and package/build receipts.
  • Content-addressed source files with normalized logical paths. Archive the actual files referenced by DWARF: application/SDK, dependencies and pinned standard-library sources, plus generated Rust. Current source snapshots exclude target/Cargo caches, so they are not sufficient for generated-source browsing.
  • For RRT/RRts, capture OUT_DIR/<workflow>.rs, its existing .rs.map.json, JSON graph, bindings and generator identity from that build. The generator already writes both files. Preserve procedural-macro definition/invocation locations when DWARF supplies them; do not promise that macro expansion text is recoverable.

Use stable --remap-path-prefix roots with a recorded physical-to-logical manifest, including generated output directories. A source URL identifies bundle hash + source hash + line, not the current checkout. Open live editor files only when their content hash matches. Later, compose the existing generated-Rust-line→JSON-pointer map to show workflow nodes; this is optional after phase 1.

2. Preserve origins through every transformation

Rust source ← raw DWARF PC ← SDK origin map ← installed Wasm origin
                                              ↑ IC origin map
                                      instrumented Wasm / JIT PC

The SDK transformer copies existing function bodies byte-for-byte, rebuilds the code section and appends three startup functions. Existing function indices stay unchanged in this transform, but absolute offsets move; even code-relative offsets can move when the function-count LEB grows. Record each raw/final body start and hash. Identify an operator by (module hash, original function index, body-relative byte offset, operator ordinal). Define body offset as operator file offset minus FunctionBody.range().start, including local declarations, and verify this convention against parser offsets. Mark added reset/init/upgrade code as SDK-generated.

DWARF Wasm PCs are Code-section-relative; Wasmtime FrameInfo::module_offset is module-file-relative. Normalize using explicit parsed section boundaries, never a guessed constant. Retain the raw DWARF as raw DWARF: copying it unchanged into the rebuilt module does not relocate it. An external sidecar plus origin translation avoids rewriting DWARF. WebAssembly DWARF conventions, Wasmtime 48.0.1 FrameInfo.

At IC instrumentation input, assign origin IDs before adding imports/helpers, meters, memory-grow rewrites and stable-API replacements. Carry IDs beside the IR and export instrumented ranges→origin/synthetic-kind. The current grow rewrite recreates operator offsets as zero, so final offsets alone cannot recover provenance. Replaced stable operations keep the original callsite as their parent origin. Store this map with the exact IC instrumentation configuration/hash; do not confuse it with the installed-module map.

3. Count what IC actually charges

Use existing debit locations as the accounting authority. At a static metering point, increment a host-owned counter for that original block; multiply hits by the block's existing IC weight offline. Aggregate dynamic byte lengths and fee events by origin and category. Do not stream every opcode.

Cost category Required collection point and attribution
Static weighted Wasm instrumentation.rs:1221, injections/inject_metering: retain block membership and exact weights; identify the function-entry minimum charge separately.
Dynamic bulk length Same file, dynamic-meter insertion: record the consumed runtime operand at its original operation. In inspected source, emitted bulk copy/fill has static 100 plus length; optimized Rust copies need not emit those opcodes.
System API base/bytes/direct fees linker.rs:141, charge_for_system_api_call/charge_direct_fee; preserve API and originating callsite.
Stable API replacement charges system_api_replacements.rs:589: instrument its actual debit too. Nonempty stable64 read/write charges 20 + length in this source; generated copies must not be charged again as original bulk operations.
Heap/stable first access and dirtying deterministic.rs:332, actual page-debit callbacks; record memory kind, aligned region, access/dirty kind, fee and origin evidence.
Other / unknown Keep observed synthetic/runtime debits and unexplained reconciliation visible; never spread the remainder across source lines.

The reconciliation contract for each execution/attempt is:

reported instructions = static prepaid + bulk length + API/replacement fees
                      + heap access/dirty + stable access/dirty
                      + other known debits + explicit budget adjustment

Maintain raw debit totals as well as the runtime's final reported total. Capture counter refills, limit clamps and DTS events so a signed adjustment has an identified cause. An unexplained difference is a profiler failure, not a compute bucket. Fixed cycle fees are separate; the IC performance counter describes current execution work, while counter 1 spans a call context. IC performance-counter specification.

Charged blocks are not literal executed-opcode counts. IC prepays blocks at injection points. A trap, API failure or budget boundary can occur before all prepaid operators execute. Allocate a block's charge across its operators using their actual weights and DWARF ranges, retaining an explicit entry/runtime remainder. Label that source view “allocation of prepaid charges.” Do not put the entire block on its first source line or imply that every mapped line executed.

Optimization also merges, reorders and removes source operations. Preserve columns/discriminators and inline ranges where present; keep line-zero, uncovered and compiler-generated ranges unmapped rather than extending a neighboring line across them.

In the measured configuration, first access and first dirtying of an aligned 64 KiB region each cost 80,000 instructions per execution. Repeated accesses do not each pay 80,000; a later message/callback can pay again. Keep this distinct from 4 KiB OS/bytemap granules. Stable first-read handling can copy directly from PageMap when all requested 4 KiB granules are untouched, avoiding native stable-region mapping; it still copies bytes, charges the API and touches the heap destination. Overlap can choose a different path. Capture these decisions rather than infer stable fees from API counts or heap page sets. First-read selection, direct read helper.

4. Collector, call paths and memory origins

For the first implementation, add an observer-only host callback at existing metering points, after original charge weights have been calculated. Pair observation with the actual debit without moving/splitting meters or adding budget checks. It updates preallocated host counters and must not enter the system-API fee path. Its inserted code is excluded from IC metering. Never store counters in the canister heap or stable memory: their allocation/touch/dirty fees would contaminate the result. A callback per block can still be expensive; measure that overhead and use selected executions. A faster private native counter path is a later optimization, not a reason to add unaccounted guest memory now.

Store profiler state outside canister rollback, and distinguish execution ID, attempt ID, DTS slice, completion/abort and committed/discarded outcome. Preserve continuation state across a paused slice; do not reset page epochs at a slice boundary or count a resumed debit twice. Link callbacks using canister + call-context/callback identity and explicit message relationships. An asynchronous continuation is a new physical stack, linked causally to earlier work rather than pretending to retain its Rust stack.

Phase 1 needs no native PC lookup for its flat block totals. For phase 2, enable Wasmtime address maps in the diagnostic engine: the inspected configuration disables them, inherited by execution config. Keep offline DWARF symbolization; enabling address maps does not require embedding Rust types into deployed Wasm.

Capture bounded stacks at selected normal observer/API callbacks, intern them and aggregate block/fee charges by stack ID. Existing Wasmtime stack-capture APIs can establish this before designing a shadow stack. Show physical Rust/Wasm frames plus DWARF inline frames, including inlined library functions and caller locations. Preserve separate monomorphizations internally; offer optional grouping by logical function. Flat counters cannot reconstruct dynamic caller paths. Wasmtime stack capture, LLVM inline symbolization.

Memory attribution requires more than the last block ID. A block can contain a call and subsequent accesses, so a callee's last ID can remain stale after return. Extend the existing signal handler to record a native fault PC with the actual page debit into preallocated storage, then translate it after execution. Do not symbolize, allocate, lock a new general mutex or capture a generic backtrace in the signal handler. Preserve unmapped native-helper PCs. Host copies and bulk helpers may fault outside JIT code; use a scoped originating-operation tag around those paths and restore it across nested calls/returns/traps. Label block-level origins explicitly, and leave unavailable caller chains unavailable. First-touch attribution says which operation triggered a state-dependent fee; it is not an inherent constant cost of that source line.

5. Output for fast optimization

Extend the current execution/page viewer rather than create a separate tracing workflow. Filter by canister, installed-module hash, method/callback, sequence window, outcome and attempt. Default to whole-execution totals and a ranked internal-function table; drill into source, block disassembly, fee breakdown and page history. Display exclusive costs as the additive ledger; inclusive caller costs are a separate view and must not be summed into that total. Keep unmapped, SDK-generated and runtime rows visible, with mapping coverage and truncation status.

For example, all figures and locations below are synthetic, not measurements:

Selected execution: 1,000,000 instructions Prepaid Wasm Dynamic/API Heap fees Stable fees Exclusive total
collections::lookup → map.rs:120 100,000 20,000 160,000 0 280,000
stable::read → arena.rs:800 40,000 70,000 80,000 80,000 270,000
SDK/generated wrapper 150,000 20,000 160,000 0 330,000
Runtime / unmapped 100,000 20,000 0 0 120,000
Total 390,000 130,000 400,000 80,000 1,000,000

Clicking arena.rs:800 should show the archived source/inline chain, original operator/block, API byte counts and attributed region IDs, plus whether attribution is exact-callsite, block-level or unmapped. Source rows are allocations of the ledger, not extra charges.

Make aggregation the primary artifact: module dictionaries once, execution summaries, sparse block hits and aggregated (origin, category, stack) debits. Version the format; use decimal strings/u64-aware handling for counters and wasm64 addresses, not lossy JavaScript numbers. Key runs by server-generation UUID and binary hash as well as instance ID; instance IDs can repeat. Every execution carries its module hash, including upgrades.

Offer a bounded chronological event stream only for a selected execution/window, ordered by execution-local event index and charged-instruction position; round time is not intra-message timing. Export weighted stacks to Speedscope with unit none and an explicit “IC instructions” label. Its sampled format accepts stack weights; this is a visualization of charge totals, not a statistical CPU sample or invented wall-clock timeline. Speedscope format.

Set host-memory/event limits, stop or truncate profiling detail visibly when reached, and preserve authoritative execution totals. Do not silently evict data or trap the canister. Export run artifacts before a server restart: current traces live in RAM. Retain bundles while referenced by retained traces; garbage-collect unreferenced bundles by hash. A suggested initial workflow is the next 20 matching executions with a 64 MiB run budget, then a narrower expensive callback; these are proposed defaults to tune, not measured overhead bounds.

Phased delivery and acceptance

  1. Artifact gate. Implement debug sidecar/source capture and SDK origin map in the canonical build only. Verify function-body hashes, Code-relative versus file-relative conversions, inline library frames, generated workflow source and LEB-count boundary cases. Reject a wrong module/source hash. Establish executable identity before attaching symbols to qualified controls.
  2. Minimal useful profiler. Add flat block-hit and dynamic-debit aggregation to a separately identified PocketIC build; expose top internal functions/blocks through the current viewer/API. Initially use successful selected messages; collect remaining API/page debits as categorized totals without source origins. Exit when all successful execution totals reconcile exactly and profile-on/off instructions, outcomes, replies, heap/stable state and accessed/dirty sets agree. This already replaces repeated manual source timers with actionable internal hotspots.
  3. Complete fee/source view. Add exact API/replacement events, heap/stable page debit origins, offline inline-aware source allocation and targeted stack capture. Test first read/write, rereads/overlap, host-copy destination fees, zero-length and bulk operations, traps, deep/indirect/tail calls, queries, callbacks, upgrades and DTS pause/resume/abort. Test instruction limits immediately around each debit boundary; retain and explain terminal clamping/prepayment differences.
  4. Iteration qualification. Run matched profile-on/off targeted workloads, then selected Heavy16 execution windows. Measure host CPU time, peak profiler memory, compile time, native stack effects and trace size separately from charged instructions. Compare state, scheduling/slice boundaries and canister outputs, not successful counts alone. If observers change instruction totals or budget behavior, fix the instrumentation or label the run diagnostic and quantify the skew; never subtract an assumed per-event overhead and claim exactness.

The essential invariant is the same installed program and IC debit semantics, with a reconciled charge ledger and honest source resolution. Precise origin IDs make compiler changes unnecessary; optimized line attribution and complete call paths still need evidence rather than assumed one-to-one mappings.