Skip to content

On-demand tick capture — record N ticks on operator demand in Attach mode #805

Closed

Description

@nockawa

Design doc: claude/design/Profiler/12-on-demand-tick-capture.md
Parent: #577

Problem

Attach mode records everything the engine emits for as long as the Workbench is connected. There is no way to say "I only care about these 100 ticks".

What this adds

An armed capture window. The operator picks cherry-pick mode when attaching, clicks Record, names a tick count, and only those ticks are kept in full detail. Everything else is reduced to a per-tick skeleton — enough for an accurate, continuous tick timeline and gauge strip, and nothing more.

The filter lives entirely in the Workbench, in AttachSessionRuntime.HandleBlock, immediately before IncrementalCacheBuilder.FeedRawRecords(...). No engine change. No wire-format change. No new protocol.

Scope discipline

An engine-side producer gate would additionally save the 25–50 ns/span on the application's worker threads and remove the ring/spillover pressure that makes high-rate workloads hit SpilloverExhaustedDrops. It was rejected on blast radius: it needs TyphonEvent + the source generator (204 event kinds) + DagScheduler, a bidirectional TCP control channel with a receive thread, and a security review of a port bound to IPAddress.Any — roughly 4 days and real regression risk for every engine user, versus ~1 day and zero for this.

This design is ~80 % reusable toward it (UI, endpoint, arming state all survive; only the filter is deleted), so the cheap path does not foreclose it. §7 of the doc turns the filter into free per-kind byte instrumentation, which is what would justify building it.

Decisions

# Question Decision
Q1 Where does the gate live? Workbench-side filter — not the engine producer, not the exporter
Q2 What survives the filter? Every kind emitted ≤1×/tick that feeds TickSummary or viewer structure: TickStart(0), TickEnd(1), ThreadInfo(77), SchedulerMetronomeWait(241), SchedulerOverloadDetector(242)
Q3 Filter the gauges? No — never filter PerTickSnapshot(76)
Q4 Arm by ticks or duration? Tick count. Nothing else.
Q5 Recording on attach? User chooses at attach time: capture everything vs cherry-pick
Q6 Re-arm: append or replace? Append
Q7 App re-run in one session? No — a restart ends the session
Q8 Save before the session dies? Auto-save in cherry-pick mode (if anything was recorded); prompt in capture-everything mode
Q9 True tick numbers? Offset at the server DTO boundary, learned from the gauge record

Three findings that shaped it

Tick numbers are not on the wire. The 12-byte common header is size / kind / threadSlot / timestamp; TickStartEvent has no payload at all. Both TraceEventDecoder.DecodeBlock and IncrementalCacheBuilder derive the tick number by counting TickStart markers — drop one and every subsequent tick is silently renumbered. Hence the mandatory spine.

SchedulerMetronomeWait is a duration input by side effect. The builder computes DurationUs from _currentTickLastTs, which TickEnd assigns and 241 is then permitted to nudge forward before sealing. Filter 241 and every idle tick's bar is systematically shorter than every armed tick's — a visible step at both window edges that reads as "the profiler slowed my app down when I hit Record".

Capacity gauges are first-snapshot-only. PageCacheTotalPages, WalCommitBufferCapacityBytes, WalStagingPoolCapacity are emitted once per session and cached by the viewer. Cherry-pick mode starts idle, so filtering that first snapshot would permanently break every gauge percentage. PerTickSnapshot is also the only record carrying an absolute u32 TickNumber (offset 12) — which is both how Q9 works and a free oracle to assert no TickStart was ever dropped.

Phases

  • P1 — FilterRecords + exempt set + _remainingTicks, tested against a fake engine in Typhon.Workbench.Tests
  • P2 — Tick offset (Q9) + the dropped-TickStart assertion
  • P3 — POST /profiler/capture, captureStateChanged SSE delta, attach-mode flag
  • P4 — UI: attach-dialog mode choice, Record/Stop + tick-count field, "recording 37/100" badge
  • P5 — Restart → new session + conditional auto-save

Acceptance criteria

  • Idle ⇒ only exempt kinds reach the builder; every other kind is dropped.
  • Idle ⇒ each TickSummary has correct TickNumber, StartUs, DurationUs, OverloadLevel, TickMultiplier, MetronomeWaitUs; EventCount is 0.
  • Duration parity: idle and armed ticks show no systematic duration offset (guards the 241 trap).
  • Arm(N) ⇒ exactly N consecutive ticks carry detail; tick N+1 does not.
  • Arming mid-tick leaves the current tick untouched; the window opens at the next TickStart.
  • Two windows in one session ⇒ both present, tick numbers monotonic and true across the idle gap.
  • A block straddling the arm boundary is split per record, not dropped or passed wholesale.
  • Attach mid-run ⇒ reported tick numbers match scheduler.CurrentTickNumber, not 1.
  • Gauges disabled ⇒ relative numbering, flagged in the UI, no crash.
  • Injected dropped TickStart ⇒ the oracle assertion fires.
  • Restart in cherry-pick mode with a recorded window ⇒ valid .typhon-replay exists and opens; with no recorded window ⇒ no file.
  • Save ordering: the last partial chunk is present in the saved replay.

Adjacent gaps found — not fixed here

Each deserves its own issue; neither should block this one.

  • TcpExporter binds new TcpListener(IPAddress.Any, _port) — unauthenticated telemetry stream on a routable interface.
  • LiveCacheTempFile has no size cap; the 2 GB / 4 h cap specified in 08-profiler-live-replay-unification.md Phase 2 was never built.

Prerequisite: #613

feature/613-workbench-db-companion adds RetentionPolicy + ProfileCatalog over <db>.typhon/profilings/. #805 does not inherit it: that path is OpenSession-only (ProfilesController rejects the rest — "Trace and Attach sessions already are a capture") and AttachSession.FilePath is the host:port endpoint, so an Attach session has no database from which to resolve a profilings/ directory. ResolveDefaultCapturePath() is byte-identical on that branch: %LOCALAPPDATA%/Typhon/Workbench/captures/, unmanaged.

Resolved by reuse rather than by filing another gap: RetentionPolicy is a public sealed record keyed on a directory (its retention.json lives inside it), and its own contract is "whoever writes a capture prunes first, from this file, with no tooling required." P5's auto-save points it at the captures directory and prunes before writing — the same pattern ProfileCatalog already follows. P5 therefore depends on #613 having merged.

Activity

  1. self-assigned this
    on Aug 14, 2026
  2. added theissue type on Aug 14, 2026
  3. updated Area Observability, Priority P2-Medium, Product Engine and Estimate L on Aug 14, 2026
  4. moved this to Todo in Typhonon Aug 14, 2026
  5. changed
    Estimate
    toon Aug 14, 2026
  6. nockawa commented on Aug 15, 2026

    @nockawa
    CollaboratorAuthor

    Accepted implementation plan — whole issue

    Scope: all five phases. Rebased onto main at 59641959 (which includes #613 / PR #810, so RetentionPolicy and ProfileCatalog are available — P5's prerequisite is satisfied).

    Acceptance criteria

    AC-0 — scriptable mock engine (test foundation). MockTcpProfilerServer today emits only a TickStart+TickEnd pair on a timer. Extend it to emit arbitrary record kinds per tick (spans, SchedulerChunk, SchedulerMetronomeWait 241, SchedulerOverloadDetector 242, PerTickSnapshot 76 carrying a true engine tick number, ThreadInfo 77), to control the reported tick origin, to emit blocks that straddle tick boundaries, and to push on demand rather than only on a timer. Backwards compatible with existing callers. Proven by its own tests.

    Filter core

    • AC-1 — idle ⇒ only exempt kinds (0, 1, 76, 77, 241, 242) reach the builder; every other kind is dropped.
    • AC-2 — idle tick's TickSummary carries correct TickNumber, StartUs, DurationUs, OverloadLevel, TickMultiplier, MetronomeWaitUs; EventCount == 0.
    • AC-3 — duration parity: idle and armed ticks show no systematic duration offset (guards the 241 nudge trap).

    Arming

    • AC-4 — Arm(N) ⇒ exactly N consecutive ticks carry detail; tick N+1 does not.
    • AC-5 — arming mid-tick leaves the current tick untouched; the window opens at the next TickStart.
    • AC-6 — a Block straddling the arm boundary is filtered per record, never dropped or passed wholesale.
    • AC-7 — two windows in one session both present, tick numbers monotonic and true across the idle gap.

    Numbering

    • AC-8 — attach mid-run ⇒ reported tick numbers equal the engine's scheduler tick, not 1. Offset learned from PerTickSnapshot's tick number (wire offset 12), applied when projecting TickSummaryDto.TickNumber and ChunkManifestEntryDto.FromTick/ToTick.
    • AC-9 — gauges disabled ⇒ relative numbering, flagged in metadata, no crash.
    • AC-10 — an injected dropped TickStart makes the oracle assertion fire rather than silently renumbering.

    Surface

    • AC-11 — POST /api/sessions/{id}/profiler/capture {tickCount} arms and returns state; auth-gated like siblings; 409 on non-Attach sessions.
    • AC-12 — captureStateChanged SSE delta observed on arm, on progress, and on window close.
    • AC-13 — attach request carries the mode; cherry-pick starts idle, capture-everything preserves today's behaviour exactly.
    • AC-14 — Attach dialog offers the two modes explicitly.
    • AC-15 — Record/Stop + tick-count field + "recording 37/100" badge driven by the SSE delta.
    • AC-16 — vitest coverage for the store/hook plus a Playwright canary; verified in a real browser, not only in tests.

    Restart / durability

    • AC-17 — engine restart ends the session (no silent renumbering continuation) and surfaces a reconnect offer.
    • AC-18 — cherry-pick auto-saves iff ≥1 window was recorded; no window ⇒ no file.
    • AC-19 — save ordering FlushCurrentChunk → FlushTrailingTick → SaveSessionAsync → dispose, proven by the last partial chunk being present in the saved replay.
    • AC-20 — RetentionPolicy applied to the captures directory before writing.

    Gate

    Deviations from the design doc

    None planned. Any that arise will be called out explicitly here before being implemented.

  7. moved this from Todo to In Progress in Typhonon Aug 15, 2026
  8. nockawa commented on Aug 15, 2026

    @nockawa
    CollaboratorAuthor

    Implementation complete — all phases

    Zero engine files touched. git status --porcelain src/ is empty: the whole feature lives in tools/Typhon.Workbench + fixtures + tests, exactly as the design's blast-radius constraint required.

    Evidence per AC

    AC Evidence
    AC-0 scriptable fixture MockRecordFactory (new) + scripted/restart modes on MockTcpProfilerServer; MockRecordFactoryTests, MockTcpProfilerServerTests
    AC-1 exempt set CaptureFilterTests.Idle_DropsDetailRecords_ButKeepsTheTickSpine, ExemptSet_IsExactlyTheSixPerTickKinds
    AC-2 summary fidelity Idle_TickSummary_RetainsEveryFieldExceptDetailDerivedOnes — criterion amended, see below
    AC-3 duration parity IdleAndArmedTicks_ReportIdenticalDurations
    AC-4/5/6/7 arming CaptureArmingTests (exactly-N, mid-tick, straddling block, two windows)
    AC-8/9/10 numbering CaptureTickNumberingTests (attach at engine tick 216 000 reports 216 000; manifest coherence; no-gauges fallback; dropped-TickStart oracle)
    AC-11/12/13 API CaptureApiTests (arm, 400, 409 on mode mismatch, 401, SSE on-connect + on-arm)
    AC-14/15/16 UI AttachTab.test.tsx, CaptureControl.test.tsx, useProfilerSessionStore.capture.test.ts
    AC-17/18/19/20 restart CaptureRestartTests, CaptureStorageRetentionTests
    AC-21 gate Workbench 696 passed / 0 failed; client 1939 passed; eslint + tsc clean; pre-push.sh --policy passed

    48 new tests (34 NUnit + 14 vitest).

    Two facts the design asserted and implementation proved

    The 241 duration nudge is real. MetronomeWait_ExtendsTickDuration_BeyondTickEnd drives the production IncrementalCacheBuilder with two identical ticks: 50 µs without SchedulerMetronomeWait, 90 µs with it. Filtering 241 would have made every idle bar shorter than every armed bar — the "profiler slowed my app down when I hit Record" artifact. This was theory in the design; it is now measured.

    PerTickSnapshot carries a usable absolute tick number. Round-trips 216 000 through the production decoder at wire offset 12, which is what makes AC-8 possible at all.

    Amendments to the plan

    1. AC-2 — EventCount == 0 was wrong and unachievable. The builder counts every record it is fed, and the exempt skeleton genuinely is in the chunk; an idle tick reports 5 (one per exempt record). Corrected criterion: EventCount equals exactly the exempt count, and the detail-derived fields (MaxSystemDurationUs, ActiveSystemsBitmask) are empty. ActiveSystemsBitmask is the honest armed/idle discriminator — only a SchedulerChunk can set it.

    2. Restart detection needed a mechanism the design did not specify. "A restart ends the session" is too blunt: the engine sends Init on every new connection, so a transient TCP blip is indistinguishable from a relaunch by signature alone — and killing a capture over a network hiccup is worse than the bug being fixed. CreatedUtcTicks separates them exactly (it is in the Init header and ComputeInitSignature deliberately excludes it). Same value ⇒ resume; different ⇒ end with reason engine_restarted. Both halves pinned by tests.

    3. TraceRetention.Prune is not reusable, despite InternalsVisibleTo("Typhon.Workbench"): it enumerates *.typhon-trace + sidecars, so pointed at the captures directory it scans files it does not recognise and deletes nothing. The RetentionPolicy record is reused instead (same retention.json, same semantics) over *.typhon-replay via CaptureStorage.

    4. Arming a capture-everything session is now 409, not a silent mode switch — it would have left the session reporting a bounded window while mode still said "Everything".

    Review findings fixed before completion

    • Cross-thread flags (_tickOffsetKnown, _tickNumberingSuspect, _tickNumberOffset) moved to Volatile per the engine's arm64 memory-ordering discipline; offset published before the flag.
    • BytesReceived / BytesRetained published as a pair at the end of HandleBlock, so an observer can never see counters that disagree or work advertised before it happened.
    • CaptureStorage gained a TYPHON_WORKBENCH_CAPTURES_DIR override — retention deletes, and the tests would otherwise have pruned the developer's real capture archive.

    Not done — needs a human

    • Browser verification. Automated coverage exercises the real Kestrel pipeline end-to-end (HTTP + SSE), but the React control has not been driven in a real browser. Manual steps in the handoff.
    • openapi.json needs a proper regen against a running server: cherryPick was added by hand so codegen would compile, but /profiler/capture is not in the committed spec. The UI calls it via the existing raw-fetch + applyWorkbenchAuthHeaders pattern, so nothing is broken — the spec is just incomplete.
    • Suite flakes observed and proven unrelated: engine suite ran 2 → 1 → 0 failures across three runs with src/ byte-identical to main; TopologyBridgeTests.WhileTheAttachedCaptureIsStillBuilding_NotReadyIs202_Not409 fails only under parallel load and passes in isolation and on three consecutive scoped runs.
  9. added a commit that references this issue on Aug 15, 2026
  10. nockawa commented on Aug 15, 2026

    @nockawa
    CollaboratorAuthor

    Implemented — #820 (code) and Typhon-Claude#87 (docs). Both open; merge together. Status stays In Progress until they land.

    All five phases are done. Four things ended up different from this issue's text, listed because each contradicts something written above.

    One acceptance criterion was wrong, not the code. "Idle ⇒ EventCount is 0" cannot hold: the builder counts every record it is fed, and the exempt skeleton is genuinely present in the chunk. Measured at exactly 5 per idle tick with gauges and the metronome seal enabled. Amended to "EventCount equals exactly the exempt count; detail-derived fields empty", with ActiveSystemsBitmask == 0 as the armed/idle discriminator — which is also what the timeline now filters on.

    There is an engine change, contrary to "No engine change. No wire-format change." No wire format moved, but three engine files did: DatabaseLockFile carries a ProfilerEndpoint (omitted when null, absent ⇒ null on read), PagedMMF writes it from the configured live port, and ProfilerBootstrap's capture-destination guard is now correct — see below. That came from the live-attach work sharing this branch.

    Q8's destination now depends on the session. A session with a database saves the recorded window into that database's own profilings/, where the Profiles list already looks; only an endpoint-only Attach session keeps the %LOCALAPPDATA% fallback this issue assumed. The "Prerequisite: #613" section reasoned correctly that an Attach session cannot resolve a profilings/ directory — but a paused Open session watching its holder can, and that is the mode that now exists. ProfileCatalog also lists .typhon-replay files, so a recorded window is findable and attachable exactly like an engine-written capture.

    Auto-save also fires on every teardown route now — engine shutdown, engine restart, stopping the watch, closing the session — not only on restart. Whichever route ends the session, the operator recorded those ticks deliberately.

    A defect was introduced and reverted inside this branch, and it defeated this feature. A change made a configured live port force the engine's default file destination. The engine then wrote a complete capture of the entire run beside the database regardless of what was armed: 25.84 MB against a 1.04 MB recorded window on a 2,000-entity shard. Cherry-picking reduced nothing that reached the disk, which is the opposite of this issue's premise. Live and Trace are independent output channels; a live port never implies a file. Both the retraction and the circular argument that had rested on it are recorded in the design docs.

    The two adjacent gaps listed above are now filed separately, as this issue asked: they are untouched here.

  11. nockawa commented on Aug 15, 2026

    @nockawa
    CollaboratorAuthor

    Merged — #820 as 550f96b, docs Typhon-Claude#87 as 4390bec. Closing.

    Shipped: an armed capture window in the Workbench, keeping only the ticks the operator asks for and a per-tick skeleton in between — 1.04 MB retained against 25.84 MB received on a 2,000-entity shard. The recorded window is saved on every teardown route and lands in the database's own profilings/, listed by the Profiles view beside engine-written captures. The timeline draws only recorded ticks, with a hatched band where the tick axis jumps, so bars either side of a gap are never read as adjacent.

    Beyond this issue's scope, from the same branch: live attach became a capability of a paused Open session rather than a third entry mode, and typhon telemetry live makes the port settable by the tool that writes the config.

    Two adjacent gaps this issue listed are now filed and untouched here: #821 (TcpExporter binds IPAddress.Any) and #822 (LiveCacheTempFile has no size cap).

    One verification gap worth stating rather than leaving implied: the full engine suite was never run in place on this branch. A Workbench dev server held Typhon.Generators.dll for the entire session, so it was built to a relocated output directory, where four tests fail for reasons of that relocation — one resolves src/Typhon.Engine/Storage by walking up from the binary, three require the database not to be under %TEMP%. The storage identifier gate's own check was run by hand over the diff (no forbidden Wal|Lsn|Fpi identifiers), but the suite itself deserves one clean local run.

  12. moved this from In Progress to Done in Typhonon Aug 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Fields

Priority

P2-Medium

Estimate

M

Area

Observability

Start date

None yet

Target date

None yet

Product

Engine

Projects

  • Status
    Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions