Skip to content

Runtime-gated correctness checks ("strict mode") for the Release NuGet #422

Description

@nockawa

Summary

Ship Typhon's DEBUG-only correctness checks in the Release NuGet by converting the user-valuable ones into runtime-gated checks (the profiler-gate pattern), so users can enable a "strict mode" for diagnosis without needing a separate Debug build. Developer-only internal tripwires stay Debug-only.

Design doc (settled): claude/research/Observability/debug-checks-runtime-gating.md

Background

The Release NuGet strips every Debug.Assert / #if DEBUG / [Conditional("DEBUG")] check (~177 across the engine). Shipping a Debug-built assembly via NuGet was rejected — NuGet has no build-configuration axis (layout is keyed on TFM/RID only). Instead, split the checks by who benefits into three tiers.

Three-tier design

Tier 0 — always-on guards (ungated, free). The predicate already runs in Release; only the reaction was stripped, so promoting costs nothing yet closes a silent-failure hole.

  • ManagedPagedMMF.cs:583/635/658 duplicate segment-root → throw (allocator corruption)
  • AccessControl.cs:385/485 wrong-thread exclusive release/demote → throw (lock-protocol corruption)
  • SpatialRTree.Query.cs DFS depth>256 ×7 → Record (counter + log, latch-safe; no silent incomplete results)

Tier 1 — opt-in strict mode (~50 user-facing checks). New CheckConfig class mirroring TelemetryConfig (static readonly bool → JIT dead-code-eliminated when off). Off by default; enabled via typhon.telemetry.json (Typhon:Checks:Enabled) or the TYPHON__CHECKS__ENABLED env var. A DeclaredAccessActive sub-flag gates the one costly check (SystemAccessValidator.AssertWrite<T>). Covers EntityRef misuse (write-on-readonly, disabled component, wrong-archetype handle), thread-affinity, MVCC Versioned-bypass, spawn/destroy/registration guards, on-reopen store-corruption/schema-drift, PackedDateTime range, etc.

Tier 2 — keep-as-is (~95 dev-facing). Internal invariants stay Debug.Assert/#if DEBUG; Typhon developers use a local clone + Debug build. (~20 more dropped as noise.)

Acceptance criteria

  • Tier 0: the 3 corruption swallowers throw a corruption exception via ThrowHelper; the R-tree overflow ×7 records a counter + [LoggerMessage] warning; all always-on, no gate.
  • CheckConfig class with Enabled + DeclaredAccessActive, loaded once at class init from env / typhon.telemetry.json (config-time, JIT-foldable — no runtime setter).
  • Require (throw, lazy message) + Record (latch-safe, never throws) primitives, reusing ThrowHelper.
  • EntityAccessor._debugOwningThreadId promoted out of #if DEBUG (3 sites) so the affinity check compiles always-on.
  • ~50 user-facing checks converted behind CheckConfig.Enabled, with lazy messages (no per-call allocation when the check passes).
  • Zero measurable hot-path cost when strict mode is off (BDN spot-check on the EntityRef read/write path).
  • Tests: strict mode on → misuse throws; off → no-op. Tier 0 corruption/record paths covered.
  • Research doc promoted to design/Observability/; user-facing docs updated.

Notes

  • Order: land Tier 0 first — it's free and independent of CheckConfig.
  • Constraint: any check reachable while holding an OLC latch must Record, never throw (an exception under a latch leaks it → deadlock).
  • Reuse existing ThrowHelper + SystemAccessValidator's InvalidAccessException pattern — no new plumbing.

Activity

  1. self-assigned this
    on Jul 1, 2026
  2. added theissue type on Jul 1, 2026
  3. moved this to Todo in Typhonon Jul 1, 2026
  4. moved this from Todo to In Progress in Typhonon Jul 2, 2026
  5. nockawa commented on Jul 2, 2026

    @nockawa
    CollaboratorAuthor

    Implementation plan (approved 2026-07-02) — /implement-feature

    Branch: feature/422-strict-mode-checks. Scope: whole issue, Tier 0 → Tier 1 (Tier 2 = no work).

    Verified deviations from the design doc (grounded in current code):

    1. PackedDateTime (3 checks) deferred — it lives in Typhon.Schema.Definition, a leaf assembly Engine depends on (one-way); it cannot reference CheckConfig (Engine) without a cycle. Kept as Debug.Assert. Net convert set ≈ 47, not 50.
    2. R-tree DFS-overflow Record is self-contained (Part 0 must not depend on CheckConfig) — static Interlocked counter + a new minimal [LoggerMessage] partial on SpatialRTree (precedent SpatialMaintainer.cs), emitted latch-safely (never under the OLC latch).
    3. Strict mode enabled suite-wide in tests (test/.../typhon.telemetry.json → Checks:Enabled=true); DeclaredAccess stays off globally (needs a system context) and is proven via dedicated primitive-level tests.

    Increments:

    • A — Tier 0 (free, independent): 3× ManagedPagedMMF + 2× AccessControl Debug.Fail/Assert(false) → ThrowHelper.ThrowCorruption (existing CorruptionException); 7× SpatialRTree.Query DFS-overflow → always-on Record (counter + [LoggerMessage]).
    • B — CheckConfig: new Observability/public/CheckConfig.cs mirroring TelemetryConfig (static readonly bool Enabled + DeclaredAccessActive, reuses TelemetryConfig.Configuration); Require/Record primitives (lazy interpolated-string message, reuse ThrowHelper); wired in the ProfilerBootstrap [ModuleInitializer]; gate-shape reflection test.
    • C — ~47 conversions across EntityRef, ClusterRef, ComponentValue, EntityId, EcsQuery, PointInTimeAccessor, EntityAccessor (affinity promotion out of #if DEBUG), Transaction(.ECS), SystemAccessValidator+DagScheduler (AssertWrite behind DeclaredAccessActive), PagedMMF/BootstrapDictionary/PagedHashMapBase.
    • D — Tests: primitives, per-area misuse-throws, Tier 0 corruption/record, BDN off-path spot-check (zero hot-path cost).
    • E — Docs: promote research doc → design/Observability/; update 09-observability.md.
    • F — Code-review gate (mandatory before done).

    Acceptance criteria tracked 1:1 with the issue checklist.

  6. nockawa commented on Jul 2, 2026

    @nockawa
    CollaboratorAuthor

    Implemented (2026-07-02) — ready for review + commit

    Branch feature/422-strict-mode-checks. All 8 acceptance criteria met (one scoped deviation on #5, below).

    AC Status Evidence
    1. Tier-0 always-on (3 throws + R-tree ×7 record) ✅ ManagedPagedMMF.cs ×3 + AccessControl.cs ×2 → ThrowHelper.ThrowCorruption; SpatialRTree.Query.cs ×7 → SpatialRTreeDiagnostics.RecordDfsStackOverflow (counter + [LoggerMessage]). Covered by Tier0GuardsTests (3).
    2. CheckConfig (Enabled+DeclaredAccessActive) ✅ New Observability/public/CheckConfig.cs, reuses TelemetryConfig.Configuration, EnsureInitialized wired in ProfilerBootstrap module-init. Gate-shape reflection test.
    3. Require + Record primitives (lazy msg, reuse ThrowHelper) ✅ Interpolated-string-handler (CheckMessageHandler) skips arg-eval on the passing path — proven by the Probe() side-effect test in CheckConfigTests.
    4. Affinity field promoted out of #if DEBUG ✅ _debugOwningThreadId→_owningThreadId (field+seed+clear+Transaction seed); AssertThreadAffinity un-[Conditional]'d, inline-guarded.
    5. ~50 user-facing checks converted, lazy ✅* ~47 converted (EntityRef 12, ClusterRef 4, ComponentValue 3, EntityId 2, EcsQuery 5, PointInTimeAccessor 8, Transaction(.ECS), SystemAccessValidator behind DeclaredAccessActive, PagedMMF/BootstrapDictionary/PagedHashMapBase). Deviation: PackedDateTime (3) deferred — it lives in Typhon.Schema.Definition, a leaf assembly Engine depends on, so it can't reference CheckConfig without a cycle. Kept as Debug.Assert.
    6. Zero hot-path cost when off (BDN) ✅ Real-JIT micro-benchmark: Require off-path ≈ 0.24 ns/call, zero alloc. StrictModeOffPathBenchmarks committed. (Note: BDN external run is blocked in this env by an unrelated stray .claude/worktrees/437 benchmark project — use the external toolchain, not InProcess.)
    7. Tests (on→throws, off→no-op, Tier-0) ✅ CheckConfigTests (primitives + canary), StrictModeMisuseTests (write-readonly / destroy-null / cross-thread), Tier0GuardsTests. Strict mode enabled suite-wide in the test typhon.telemetry.json.
    8. Doc promoted + user docs ✅ research/Observability/… → design/Observability/debug-checks-runtime-gating.md (status Implemented + deviations); strict-mode subsection added to overview/09-observability.md.

    Code review: 3-agent parallel review (infra+Tier-0 / ECS conversions / runtime+storage+tests). No critical/high bugs. Addressed all actionable findings: AssertWrite/Enter/Leave + AssertThreadAffinity fast-slow inline split (removes residual off-path call on EntityRef.Write), single-Spawn EntityMap check → inline-guard (array-index condition can't be DCE'd), Record hardened with try/catch, CheckMessageHandler format/alignment overloads, config-regression canary test, [NonParallelizable], unused-using + 160-col cleanups.

    Verification: engine + tests build clean (0 warn/err); the 24 #422 tests pass (0 skipped — strict mode active); full suite green apart from pre-existing parallel-flaky tests (ExceptionPathLeakTests ×3, one TransactionTests read) that all pass in isolation.

    Handoff note: the working tree also carries the unrelated TraceIdEnricher.cs deletion + Typhon.Engine.csproj edit (packaging feature #427–434) that rode onto this branch from main — commit those separately.

  7. nockawa commented on Jul 2, 2026

    @nockawa
    CollaboratorAuthor

    Correction on AC #8 (user-facing docs). My completion note ticked #8 clean, but I'd only updated the claude/ knowledge base (design doc + overview/09-observability.md) — the user-facing DocFx doc/ tree was missed. Now filled:

    • New doc/feature-set/Observability/strict-mode-checks.md — full feature doc (template-matched to telemetry-config-gating.md): the two flags + key table, JSON + TYPHON__CHECKS__* precedence table, guarantees (off-by-default, resolve-once, ~0.24 ns zero-cost, what-it-catches, Tier-0 always-on guards), test links.
    • Updated doc/feature-set/Observability/README.md — Public Features table row.

    Not touched: doc/in-depth-overview/12-observability.md (the narrative deep-dive chapter) — optional follow-up if the strict-mode section is wanted there too.

  8. added a commit that references this issue on Jul 3, 2026
  9. moved this from In Progress to Done in Typhonon Jul 3, 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

None yet

Estimate

M

Area

None yet

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