Repository navigation
Description
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 inTyphon.Workbench.Tests - P2 — Tick offset (Q9) + the dropped-
TickStartassertion - P3 —
POST /profiler/capture,captureStateChangedSSE 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
TickSummaryhas correctTickNumber,StartUs,DurationUs,OverloadLevel,TickMultiplier,MetronomeWaitUs;EventCountis 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-replayexists 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.
TcpExporterbindsnew TcpListener(IPAddress.Any, _port)— unauthenticated telemetry stream on a routable interface.LiveCacheTempFilehas no size cap; the 2 GB / 4 h cap specified in08-profiler-live-replay-unification.mdPhase 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
nockawa commentedon Aug 15, 2026
Accepted implementation plan — whole issue
Scope: all five phases. Rebased onto
mainat59641959(which includes #613 / PR #810, soRetentionPolicyandProfileCatalogare available — P5's prerequisite is satisfied).Acceptance criteria
AC-0 — scriptable mock engine (test foundation).
MockTcpProfilerServertoday emits only aTickStart+TickEndpair on a timer. Extend it to emit arbitrary record kinds per tick (spans,SchedulerChunk,SchedulerMetronomeWait241,SchedulerOverloadDetector242,PerTickSnapshot76 carrying a true engine tick number,ThreadInfo77), 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
TickSummarycarries correctTickNumber,StartUs,DurationUs,OverloadLevel,TickMultiplier,MetronomeWaitUs;EventCount == 0.Arming
Arm(N)⇒ exactly N consecutive ticks carry detail; tick N+1 does not.TickStart.Numbering
PerTickSnapshot's tick number (wire offset 12), applied when projectingTickSummaryDto.TickNumberandChunkManifestEntryDto.FromTick/ToTick.TickStartmakes the oracle assertion fire rather than silently renumbering.Surface
POST /api/sessions/{id}/profiler/capture{tickCount}arms and returns state; auth-gated like siblings; 409 on non-Attach sessions.captureStateChangedSSE delta observed on arm, on progress, and on window close.Restart / durability
FlushCurrentChunk→FlushTrailingTick→SaveSessionAsync→ dispose, proven by the last partial chunk being present in the saved replay.RetentionPolicyapplied to the captures directory before writing.Gate
scripts/pre-push.sh(gate parity — Stress_Config back-pressure test fails deterministically on the gate runner, and the path filter has been hiding it #774 showed the Workbench suite is where bugs reach the gate), then a mandatory code review of the full diff against every AC, the design doc,.editorconfigandCLAUDE.md. Completion blocked until it passes.Deviations from the design doc
None planned. Any that arise will be called out explicitly here before being implemented.
nockawa commentedon Aug 15, 2026
Implementation complete — all phases
Zero engine files touched.
git status --porcelain src/is empty: the whole feature lives intools/Typhon.Workbench+ fixtures + tests, exactly as the design's blast-radius constraint required.Evidence per AC
MockRecordFactory(new) + scripted/restart modes onMockTcpProfilerServer;MockRecordFactoryTests,MockTcpProfilerServerTestsCaptureFilterTests.Idle_DropsDetailRecords_ButKeepsTheTickSpine,ExemptSet_IsExactlyTheSixPerTickKindsIdle_TickSummary_RetainsEveryFieldExceptDetailDerivedOnes— criterion amended, see belowIdleAndArmedTicks_ReportIdenticalDurationsCaptureArmingTests(exactly-N, mid-tick, straddling block, two windows)CaptureTickNumberingTests(attach at engine tick 216 000 reports 216 000; manifest coherence; no-gauges fallback; dropped-TickStartoracle)CaptureApiTests(arm, 400, 409 on mode mismatch, 401, SSE on-connect + on-arm)AttachTab.test.tsx,CaptureControl.test.tsx,useProfilerSessionStore.capture.test.tsCaptureRestartTests,CaptureStorageRetentionTestspre-push.sh --policypassed48 new tests (34 NUnit + 14 vitest).
Two facts the design asserted and implementation proved
The 241 duration nudge is real.
MetronomeWait_ExtendsTickDuration_BeyondTickEnddrives the productionIncrementalCacheBuilderwith two identical ticks: 50 µs withoutSchedulerMetronomeWait, 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.PerTickSnapshotcarries 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
AC-2 —
EventCount == 0was 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:EventCountequals exactly the exempt count, and the detail-derived fields (MaxSystemDurationUs,ActiveSystemsBitmask) are empty.ActiveSystemsBitmaskis the honest armed/idle discriminator — only aSchedulerChunkcan set it.Restart detection needed a mechanism the design did not specify. "A restart ends the session" is too blunt: the engine sends
Initon 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.CreatedUtcTicksseparates them exactly (it is in the Init header andComputeInitSignaturedeliberately excludes it). Same value ⇒ resume; different ⇒ end with reasonengine_restarted. Both halves pinned by tests.TraceRetention.Pruneis not reusable, despiteInternalsVisibleTo("Typhon.Workbench"): it enumerates*.typhon-trace+ sidecars, so pointed at the captures directory it scans files it does not recognise and deletes nothing. TheRetentionPolicyrecord is reused instead (sameretention.json, same semantics) over*.typhon-replayviaCaptureStorage.Arming a capture-everything session is now 409, not a silent mode switch — it would have left the session reporting a bounded window while
modestill said "Everything".Review findings fixed before completion
_tickOffsetKnown,_tickNumberingSuspect,_tickNumberOffset) moved toVolatileper the engine's arm64 memory-ordering discipline; offset published before the flag.BytesReceived/BytesRetainedpublished as a pair at the end ofHandleBlock, so an observer can never see counters that disagree or work advertised before it happened.CaptureStoragegained aTYPHON_WORKBENCH_CAPTURES_DIRoverride — retention deletes, and the tests would otherwise have pruned the developer's real capture archive.Not done — needs a human
openapi.jsonneeds a proper regen against a running server:cherryPickwas added by hand so codegen would compile, but/profiler/captureis not in the committed spec. The UI calls it via the existing raw-fetch +applyWorkbenchAuthHeaderspattern, so nothing is broken — the spec is just incomplete.src/byte-identical to main;TopologyBridgeTests.WhileTheAttachedCaptureIsStillBuilding_NotReadyIs202_Not409fails only under parallel load and passes in isolation and on three consecutive scoped runs.#805 On-demand tick capture, and live attach as a capability of a pau…
nockawa commentedon Aug 15, 2026
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 ⇒
EventCountis 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 "EventCountequals exactly the exempt count; detail-derived fields empty", withActiveSystemsBitmask == 0as 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:
DatabaseLockFilecarries aProfilerEndpoint(omitted when null, absent ⇒ null on read),PagedMMFwrites it from the configured live port, andProfilerBootstrap'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 aprofilings/directory — but a paused Open session watching its holder can, and that is the mode that now exists.ProfileCatalogalso lists.typhon-replayfiles, 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.
LiveandTraceare 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.
nockawa commentedon Aug 15, 2026
Merged — #820 as
550f96b, docs Typhon-Claude#87 as4390bec. 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 livemakes the port settable by the tool that writes the config.Two adjacent gaps this issue listed are now filed and untouched here: #821 (
TcpExporterbindsIPAddress.Any) and #822 (LiveCacheTempFilehas 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.dllfor the entire session, so it was built to a relocated output directory, where four tests fail for reasons of that relocation — one resolvessrc/Typhon.Engine/Storageby 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 forbiddenWal|Lsn|Fpiidentifiers), but the suite itself deserves one clean local run.