Skip to content

Onboarding "hello world" sample, and everything that stood in its way - #586

Merged
nockawa merged 18 commits into
mainfrom
ux-imp
Jul 27, 2026
Merged

nockawa merged 18 commits into
mainfrom
ux-imp

Conversation

@nockawa

@nockawa nockawa commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator

This PR is a soup. Here is why.

The whole thing started as one modest goal: make a working "hello world" that a new user can actually run. typhon new, get a project, run it, see a database do something, open the Workbench and look at it.

That turned out to be a very effective way to find bugs. Every time the sample was made to do something a real user would do, it hit something — a wrong result, a lock, a stall, an API that made the obvious thing slow. Fifteen commits later the sample is fast and honest, and a pile of engine defects that nobody had a reproducer for are fixed.

So this is not a clean single-purpose PR and there is no point pretending otherwise. It is: an onboarding sample, plus everything that stood in its way.

Reviewing tip: the commits are individually scoped and each carries its own measurements and rationale. Reading git log is a better experience than reading the diff.


1 — The actual goal: onboarding

commit what
138d9c3 #531/#532 — SWG sample re-skin: Harvester → Character, HAM pools, factions, credits. A schema that looks like a game rather than a unit test.
c8345fc #531/#532 — typhon CLI onboarding: telemetry/ui commands, Workbench host, dev script.
d245b13 Guide sample tick systems rewritten cluster-native. ~10× on the systems.
7c210f5 Ignore dotTrace snapshots, generated reports, stray sample databases.
14c297a Sample telemetry config: GC tracing + OS thread-scheduling capture.

2 — Engine bugs the sample found

Each of these was invisible until a sample tried to do something ordinary.

a71b765 — ordered query returned 0 rows after updating an AllowMultiple Versioned cluster index. A wrong result, not a slow one.

f2e696b — #566: parallel cluster dispatch bound every system to the first cluster-eligible archetype, not its own input view's. ResolveChangeFilters scanned the global ArchetypeRegistry and took the first match, never consulting the system's view. Correct by accident with exactly one cluster archetype — which is why the whole suite passed and no fixture registered two. With two, systems either walk past the end of their segment or silently skip their own tail clusters. Affects every multi-archetype schema with parallel cluster-native systems.

Two false negatives while writing that regression test, both worth knowing about: it is ordering-dependent unless you run systems on both archetypes, and chunk ids are segment-local, so "is this chunk id mine?" passes while the bug fires. The test asserts coverage (Is.EquivalentTo), not membership.

0f2a28b — #558: FieldShadowBuffer.Append took a global lock on every indexed-field write. ~8 s of blocking per sample run. Now a wait-free segmented append.

3 — Performance, all measured on the sample

d7b2101 — #559: columnar FenceBlock WAL record. The cluster SoA is columnar; the WAL record format was row-per-(entity, component), so every tick paid a transpose nobody asked for — 736 contiguous bytes became 46 sixteen-byte copies in 46 record headers.

FinalizeArchetypeFence   6 453 ms -> 252 ms   (25.6x)
records/tick              100 005 -> 435      (230x)
WAL bytes/tick            4.92 MiB -> 1.24 MiB

Also drops Versioned slots from fence emission (their cluster HEAD is rebuilt from the revision chain, so those records were written, fsynced, retained and then ignored), narrows emission to the components actually written, and fixes a WalCommitBuffer.TryClaim path that degraded to Thread.Sleep(1) — 1 to 15.6 ms on Windows against a swap completing in microseconds.

e08d2c6 + f581ad9 — resolve/OpenMut fast paths. Versioned chain walks deferred until something actually reads the component; hinted EntityMap lookup.

40600fa — #568: ClusterDurability.Checkpoint. New per-archetype knob. See below — it is the one item here that is not purely additive.

d7546a5 — zone-map recompute narrowed to components actually written. Character indexes Faction (stable) and mutates Transform/Ham — correct schema design, the sample literally says "index what's stable, scan what churns" — and the engine rescanned 435 clusters × 46 Faction values every tick to reach an identical answer. It was punishing the right decision.

Sample, end to end

before after
tick p50 3.81 ms 1.57 ms
entity-updates/sec 21.0M 50.8M
headroom @ 60 Hz 4.4× 10.6×

Measured steady-state (excluding process warm-up) it is p50 ~0.85 ms and ~20× headroom.


🔴 The one thing that needs a real decision: #568

ClusterDurability.Checkpoint lets an archetype declare that its SingleVersion values reach disk via the checkpoint rather than the tick-fence WAL. The guide sample opts in, and that is half of its speedup.

It is included here because it is what makes the sample fast, but it is entangled with an open correctness question and should not be waved through:

An ADR is required before #568 ships. It has to decide whether Checkpoint documents today's behaviour or changes it — and that depends on how #569 is resolved. Happy to split #568 out of this PR if you would rather land the rest first.


Also in here, honestly

  • 8833703, 36a78ab — a noob skill and a project field. Unrelated; they were in the branch.
  • A long tail of guide prose updates across doc/guide/.
  • ClusterRef.MarkDirty<T>(Comp<T>) — new API. Without it a cluster-native writer using GetSpan had no way to mark dirty and keep Columnar FenceBlock WAL record — cut tick-fence emission cost and volume #559's per-component narrowing; it would have had to fall back to the mask-poisoning overload.

Related issues

#531, #532 onboarding sample + CLI — the driver
#558 FieldShadowBuffer global lock — fixed
#559 columnar FenceBlock — P1–P3 done, P4 (slice FenceFinalize) still open
#566 parallel cluster dispatch binding — fixed, filed from this work
#568 ClusterDurability — P1 implemented, ADR outstanding
#569 ApplySlotToExisting recovery gap — open, filed from this work
#577, #578 Profiler capability expansion — filed from this work

Verification

  • Engine 4061 / 0 (51 skipped) · SWG samples 4 / 4 · Shell 22 / 22
  • 84 files, +4865 / −867
  • Sample runs end to end including close/reopen: Transform/Ham durable via checkpoint, Wallet via its revision chain, Intent reset by design
  • Every regression test in this PR was proven by running it against deliberately broken code, not by observing it pass

🤖 Generated with Claude Code

https://claude.ai/code/session_01Gcg4vW8vJ4QjNyj6NQabHs

nockawa and others added 16 commits July 25, 2026 11:10
…ed cluster index

ReconcileClusterIndexAndViews maintained the per-archetype cluster B+Tree with the unique-index Move/Add/Remove and had no field.AllowMultiple branch. For an AllowMultiple index the B+Tree leaf value is a VSBS buffer-root id, not the entity clusterLocation, so the unique Move overwrote the leaf with the raw clusterLocation. The ordered read then interpreted that value as a buffer id, found no valid buffer, and dropped every entity: ExecuteOrdered/OrderByFieldDescending returned 0 after any update to the indexed field, and a following Destroy misbehaved (stale element id). Only cluster-eligible archetypes with a Versioned AllowMultiple index were affected; pure-Versioned (non-cluster) archetypes take a different, correct path.

Branch on field.AllowMultiple and use MoveValue/RemoveValue with the per-entity element id read from and written back to the cluster tail slot, mirroring ReconcileFlatIndexAndViews, FinalizeSpawns, and the cluster destroy path.

Regression tests: OrderedVersionedClusterReproTests exercises the cluster path (update, ordering correctness, and destroy-after-update), plus a non-cluster companion in EcsQueryTests. Full engine suite green (4022/0/51).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017AtukcD3UDm3zh4qGbjmJo
Replaces the tick fence's row-per-(entity, component) Slot records with one columnar FenceBlock per dirty cluster. The cluster SoA is already columnar - a cluster's entity keys and each component's values are contiguous - so the old format paid a full transpose every tick, turning 736 contiguous bytes into 46 sixteen-byte copies wrapped in 46 record headers.

Measured on doc/guide/example (20 001 entities, 120 Hz, dotTrace tracing, all frames):

  FinalizeArchetypeFence    6 453 ms -> 252 ms  (25.6x)
  memcpy                    1 802 ms ->  48 ms
  Thread.Sleep                392 ms ->   0 (absent)
  WAL bytes/tick             4.92 MiB -> ~1.24 MiB
  records/tick                100 005 -> 435
  tick wall-clock (median)     34.6 ms -> ~17.6 ms
  tick wall-clock (worst)        ~29 ms -> ~18 ms

What changed:

- RecordKind.FenceBlock + FenceBlockRecordBody: one record per dirty cluster carrying a contiguous slot RANGE, the entity-key column, and each durable component column. An all-dirty cluster degenerates to one copy per column, a single dirty entity to one entity; DirtyMask records which entities in the range actually changed.
- DurabilityLog.AppendFenceBlocks: the size is a pure function of the descriptors, so the emitter measures, claims ring space, and has the codec copy columns straight into the claim. The CommitBatchArena hop is gone from the cluster fence - one copy instead of two, and no 80-byte BatchEntry per record.
- Versioned slots are no longer fence-emitted. Their cluster HEAD is a cache rebuilt from the revision chain on reopen, so those records were written, fsynced, retained and then ignored.
- Per-archetype WrittenSlotUnion narrows emission to the component slots actually written. Fail-safe: the component-less SetDirty overload poisons the union to AllSlotsWritten, so a writer that does not identify its component keeps emitting everything - a call site added later over-emits rather than under-emits. Deliberately one value per archetype, not one per cluster: the emitter only consumes the union, and a per-cluster array false-shares badly (measured +2.1 ms/tick median, ~10 ms spread).
- GetChunkAddress hoisted out of the per-entity loop, sizes/offsets precomputed. Worth ~13 us - hygiene, not a win.
- Recovery reads FenceBlock and expands it into the same per-(entity, slot) aggregation, so recovery semantics are unchanged.

WalCommitBuffer swap-completion event (not fence-specific - benefits every WAL producer): TryClaim polled _activeBufferIndex with an AdaptiveWaiter, which degrades to Thread.Sleep(1), 1 to 15.6 ms on Windows against a swap that completes in microseconds. The buffer had one event and it pointed producer->consumer only, so a producer waiting on a swap had nothing to block on. Adding _swapCompletedEvent turned 126 ms of sleeping into 39 ms of actual waiting and removed the run-to-run variance. DurabilityWalBackpressureEvent gains a Retries field.

WalRingBufferSizeBytes default 8 MB -> 64 MB, sized for tail latency rather than throughput: the median tick is flat across 8/16/32/64 MB, but the worst tick falls from ~29 ms to ~18 ms. A ring that fills makes producers block on the buffer swap, which surfaces as an occasional tick blowing several times its budget. The option is the total pinned allocation (halved at DatabaseEngine.cs:993 into two halves), so this is 64 MB, not 128.

Pre-alpha: the wire format changed outright and the old per-entity fence path is deleted rather than kept alongside.

Design doc: claude/design/Durability/wal-fence-emission.md
Tests: FenceBlockCodecTests (7), FenceBlockSlotMaskTests (8). Full suite 4037/0.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gcg4vW8vJ4QjNyj6NQabHs
A profiling session leaves ~90 MB of .dtp snapshot parts and, with an unfiltered
report pattern, report XML in the hundreds of MB. Sample runs leave <name>.typhon
directories wherever they were launched from. None of it belongs in the repo and
none of it was covered.

Deliberately pattern-based rather than directory-based for the .dtp/report rules:
test/Typhon.Benchmark/profiling/ holds tracked tooling (analyze_profile.py,
btree-pattern.xml, profile-arpg-200k.tsh) that must stay visible.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gcg4vW8vJ4QjNyj6NQabHs
…ions, credits

The Light-tier sample was named for Star Wars Galaxies but had stopped looking like it. Re-skinned around the game's own vocabulary so the schema teaches SWG's data model rather than a generic one.

Harvester -> Character. Considered Player (wrong - most characters are NPCs), NPC (excludes players) and Creature (SWG's own type is CreatureObject, but "creature" reads as animal and animals do not hold faction allegiance). Character covers players and NPCs alike, which is what the archetype models.

Components, one per storage mode so the tier split stays the lesson:
  Transform  SV         position + velocity
  Bounds     SV         [SpatialIndex] Dynamic, kept coherent after movement
  Ham        SV         Health / Action / Mind pools with their maxima - SWG's HAM
  Faction    SV         [Index(AllowMultiple)] Neutral / Rebel / Imperial / Hutt
  Wallet     Versioned  credits, the only MVCC write in the loop
  Intent     Transient  wander target, dropped on restart by design

The guide's richer chapters (2-5) now sit on the Full tier, with Light kept as the chapter-1 seed. Two pre-existing doc bugs fell out of that pass: chapter 1's program used Console without a using directive against a scaffold csproj that has no ImplicitUsings, and chapter 4 demonstrated OrderByField on an unindexed field, which throws. Both fixed, with the ordering constraints now stated.

The scaffold template rename travels with the sample by necessity: Typhon.Shell.csproj embeds the file as an EmbeddedResource, ProjectScaffolder names it on the way out, and ScaffoldTests asserts the emitted copy is byte-identical to the in-repo source. Splitting those from the file rename leaves a commit that does not build.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gcg4vW8vJ4QjNyj6NQabHs
…t, dev script

The remaining onboarding surface, separated from the sample re-skin it sits on top of.

- typhon telemetry / typhon ui: the paths a newcomer takes from a scaffolded project to a running Workbench and a readable trace, including --open-latest.
- Workbench hosting options threaded through so `typhon ui` can host in-process on loopback.
- scripts/onboarding-smoke-test.sh: walks the scaffold -> build -> run path end to end, so the onboarding story is checked rather than assumed.
- scripts/typhon-dev.ps1: registers a `typhon-dev` function that shadows the global tool with a freshly published local build. Publishes rather than builds - `typhon ui` serves its SPA from wwwroot, which only exists after `dotnet publish`, so a plain build yields a CLI whose UI 404s. That cost an hour of confusion; the script exists so it costs nobody else one.
- release.yml adjusted for the packaging path.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gcg4vW8vJ4QjNyj6NQabHs
…pend)

FieldShadowBuffer.Append took a lock on every indexed-field write, from every worker, every tick - one lock instance per indexed field, shared by all 32 workers. Measured on doc/guide/example (20 001 entities, dotTrace tracing): Total 17 309 ms against Own 107 ms. A ten-instruction body spending 99% of its wall time blocked, and the largest single cost in the engine - roughly 73x the entire tick fence.

Storage is now segmented: entries live in fixed-size blocks reached by index, a block is allocated on first use and is never moved, resized or freed. A writer reserves its slot with one Interlocked.Increment and writes into a slot no other writer can claim. Growth adds a block reference to a wider table, so a writer holding an older table still resolves valid arrays for every index it could have reserved against it.

A flat pre-sized array would NOT have worked. The gate that admits appends (DirtyBitmap.TestAndSet) grows on demand, so after a segment grows more entities can shadow than any capacity computed at construction allowed.

  Lock.TryEnterSlow          32 115 ms -> 22 ms
  FieldShadowBuffer.Append   12 388 ms -> 228 ms   (gap Total-Own: 12 299 -> 125)
  ShadowClusterIndexedFields 20 803 ms -> 978 ms
  EntityRef.Write            20 944 ms -> 4 609 ms
  Move + Regen + Wander + BoundsSync, combined: ~60 s -> ~36 s

One contract changed and is documented on the type: the reservation increments the count BEFORE the entry is written, where the lock version incremented it after. That is safe only because reads happen at the tick boundary once the scheduler's phase barrier has retired every writer - which is exactly what Count and the indexer already documented.

Part 2 of the issue (per-(entity, slot) ClusterShadowBitmap) is deliberately not done: the cost was contention, not shadowing work, so removing the lock helps regardless of how many fields get shadowed. Its remaining ceiling is ~2 s of the 36 s and it carries a semantic change on the destroy path (Transaction.ECS.cs:2299).

One file changed in src/ - no API change, no consumer edits.
Tests: FieldShadowBufferTests (6) - concurrency, growth across block boundaries, Reset capacity retention, ref-returning indexer. Full suite 4043/0.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gcg4vW8vJ4QjNyj6NQabHs
…ktree

This work sat uncommitted in .claude/worktrees/resolve-perf since 2026-07-23 - the branch had zero commits, so it existed only as a dirty working tree. Rebased onto ux-imp here (3-way, no conflicts, including EntityRef.cs where #559's per-slot SetDirty calls live).

What it does - all on the Versioned/MVCC resolve path:
- EntityRef._chainRoots: per-slot revision-chain ROOT chunk ids recorded by ResolveEntity, so the first Write can re-resolve CompRevInfo with a direct chain walk instead of a PK-index lookup.
- Deferred SingleCache insert: read-only resolves no longer populate ComponentInfo.SingleCache; it now holds only written/spawned entries.
- RevisionWalker: an optimistic single-entry fast path for the common one-revision chain, falling back to the full enumerator.
- Supporting ordering work in RawValueHashMap, AccessControlSmall and OlcLatch.

CLAUDE.md's "No Volatile.Read/Write for <=64-bit types" rule is replaced by explicit x64 AND arm64 memory-ordering discipline. That is not incidental - it is what licenses the optimistic readers above. Acquire/release compile to plain mov on x64 and ldar/stlr on arm64, so correctness under the weak arm64 model costs nothing where the hardware does not need it. Seqlock/OLC readers must either make every load in the protocol a Volatile.Read or issue an arch-conditional barrier before the validating re-read.

Two fixes were needed to make it land:

1. It did not build. RevisionEnumerator's constructor gained a required lockWc parameter and Typhon.Shell/Commands/DiagnosticCommandExecutor.cs:537 was never updated. The engine suite was green, which is presumably why nobody noticed the solution was broken - and why this never shipped. That call site now passes the standard RevisionChainLockTimeout.
2. ResolveProbe, a temporary Stopwatch instrumentation harness, was woven through RevisionWalker and Transaction.ECS (54 lines, each tagged TEMP ResolveProbe). Stripped, along with the standalone file.

PERFORMANCE IS NOT VERIFIED HERE. The original measurement was OpenMut 675 -> ~330 ns on a Versioned-heavy workload. On doc/guide/example this shows no change (ResolveEntity 21 568 -> 22 987 ms, within noise) because that sample's hot loop is SingleVersion - Transform, Ham, Intent - with a single Versioned component touched every tenth tick. There, ResolveEntity is dominated by ChunkAccessor.LoadAndGet and RawValuePagedHashMap.TryGet, neither of which this patch touches. It needs an MVCC-heavy benchmark to demonstrate itself.

Solution builds. Engine 4043/0, Shell 22/22, SWG samples 4/4.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gcg4vW8vJ4QjNyj6NQabHs
…in walks, use the hinted EntityMap lookup

Three changes to EntityAccessor.ResolveEntity and its callees, all measured on doc/guide/example (20 001 entities, 200 ticks, Release, dotTrace tracing, Typhon telemetry off). Self-time summed over every frame beneath each system body:

                baseline   after    delta
  MoveSystem      12 002    9 414   -21.6%
  RegenSystem     10 279    7 741   -24.7%
  WanderSystem    10 427    8 072   -22.6%
  BoundsSync       1 542    1 665   control, untouched

BoundsSync is the control: it iterates clusters natively, resolves no entities, and moved 1 542 / 1 592 / 1 808 / 1 665 across the four runs. That +-17% spread is the noise floor - per-system deltas under ~300 ms are not resolvable by this method.

1. Deferred (lazy) revision-chain resolution.

ResolveEntity walked EVERY Versioned slot's chain on every open, whether or not the caller ever touched that component. MoveSystem writes only Transform (SingleVersion) yet walked Wallet's chain 4 000 200 times per run for data it never reads. It now stashes the chain ROOT (SetChainRoot) and marks the slot pending; the walk happens on first read, in EntityRef.EnsureVersionedResolved, guarded at all four Versioned read sites - Read(Comp<T>), Read<T>(), TryRead, ReadRaw - and the pending bit is cleared when a COW write supersedes it, so a later read cannot re-resolve to the pre-write revision.

Deferring is MVCC-neutral: visibility is a function of the accessor's TSN, which is fixed for its lifetime, so walking later yields the same revision. Only the base EntityAccessor changed; Transaction.ResolveEntity overrides it and is untouched.

Worth -11 to -13% on its own, well above the 6% the WalkChain line predicted, because the walk was faulting CompRev pages in: ChunkAccessor.LoadAndGet 10.59M -> 7.41M calls, PagedMMF.RequestPageEpoch 6.97M -> 3.78M.

2. Skip the per-resolve epoch-scope probe.

InitLightweight enters an epoch scope it never exits, and the accessor is thread-affine, so "is this thread in an epoch scope?" is provably true for a PointInTimeAccessor worker. _ownsPersistentEpochScope records that and short-circuits EpochManager.IsCurrentThreadInScope (two [ThreadStatic] reads plus a padded-slot load) on every resolve. False on every other path, where the original check runs verbatim.

Real but small: the frame disappeared (4 000 200 calls/system) and ResolveEntity self-time fell 875 -> 725 ms, but system totals did not move. At 4M calls of a two-field property most of the measured 207 ms was the tracing instrumentation of the call itself. Kept because it is free and strictly narrower, not because it showed up.

3. Hinted EntityMap lookup on the parallel and ArchetypeAccessor paths.

RawValuePagedHashMap.TryGetWithHint - a low-key-bits -> (bucketChunkId, index) cache that collapses a lookup to one bucket-chunk visit - already existed, documented as "identical semantics/result to TryGet", self-allocating, with exactly ONE caller: Transaction.ResolveEntity. The parallel/PTA path, which performs ~12M lookups per run, kept calling plain TryGet. EntityKey is dense and monotonic, which is precisely the shape the hint cache is built for.

Worth -11.6 / -13.1 / -11.2% from a two-line change. ScanChain, GetBucketChunkId, GetHeader and Int64.Equals (the chain's linear key compares) all left the profile.

RISK, STATED PLAINLY. This one changes WHO calls something without changing the thing called, so the assumptions that made it safe were the caller's:

- A low hint hit rate is a net loss: a miss pays the hint probe, then the full lookup, then a StoreHint write. Scan-once workloads that resolve many distinct entities exactly once miss ~100%. Not measured here.
- StoreHint was written for a single-threaded caller and now has 28 workers in it. During growth each can allocate its own array and overwrite the others' - correctness holds (readers index by their local array's length), but it churns allocations on a hot path. Worth fixing independently of this commit.
- The ArchetypeAccessor.cs call site is reasoned-safe but unmeasured; nothing in this sample exercises it.

Before this is trusted beyond the sample it wants test/Typhon.Benchmark run before/after - crud-compare, storage-modes, profile-write-sv/v, aa-bench, cluster-bench, indexed-bench, versioned-cluster-bench, tickfence-bench, and especially the one-shot query benches (simd/ordered/zonemap), which are the scan-once shape most likely to regress.

Also left on the table: TryGetFullAndRefreshHint still runs 322 920 of 4 000 200 lookups (8.1%), and the count is identical across all three systems, so it is deterministic, not a race. Cause is not collisions - 20 007 dense keys into a 32 768-slot pow2 array collide zero times - but that StoreHint fires only for bucket-ROOT hits: entries living in overflow chunks can never be hinted, because overflow chunks can be freed by RemoveFromChain and a stale hint there would dereference freed memory. Arithmetic fits: 20 001 cold misses on tick 1, then ~1 522/tick = 7.6% steady-state overflow residency. Not proven - that needs a direct count of non-root entries.

Tests: 8 new in LazyVersionedResolveTests pinning the deferral contract - snapshot fidelity across a concurrent commit, memoization, and each of the four read sites. Note that a PointInTimeAccessor is a frozen TSN, not a registered reader (Create only calls AllocateTSN), so it does not hold revisions back from cleanup; the snapshot test pins the chain with a real read-only transaction, without which the deferred walk resolves a reclaimed revision to 0. Eager resolution did not hit that, but was not safer - it would have read a recycled chunk.

all-frames-pattern.xml is the dotTrace Reporter pattern these numbers were produced with. The existing btree-pattern.xml matches Typhon\. only, which silently drops every System.* frame - Memmove, Int64.Equals, lock waits - and that omission has produced wrong conclusions here before.

Suite 4051/0 (4043 before, plus the 8 new).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gcg4vW8vJ4QjNyj6NQabHs
TyphonRuntime.ResolveChangeFilters resolved every parallel QuerySystem's ArchetypeClusterState by scanning the global ArchetypeRegistry and taking the FIRST cluster-eligible archetype it found. It never consulted the system's own input view - the comment claimed it "checks if any entity already in the view belongs to a cluster-eligible archetype"; it checked no such thing.

That state feeds ctx.ClusterIds, ctx.StartClusterIndex and ctx.EndClusterIndex, plus the tier index and the checkerboard split. With more than one cluster archetype every parallel system received the SAME archetype's cluster ids. With exactly one, the first archetype is the right one - which is why the whole suite and both in-tree samples passed.

Two failure modes, and the quiet one is the dangerous one:
- bound archetype has MORE clusters -> "GetChunkLocation: Computed page index N >= segment length M" every tick, successors skip with DependencyFailed.
- bound archetype has FEWER clusters -> the system silently processes a SUBSET of its own entities. No exception, no assertion, plausible-looking output.

The two GetClusterEnumerator overloads differ in exposure: GetClusterEnumerator<TArch>(start, end) resolves from TArch itself and is unaffected; GetClusterEnumerator<TArch>(clusterIds, start, end) consumes the misresolved ctx.ClusterIds. The idiom the guide sample teaches prefers the affected one.

FIX. ViewBase gains QueriedArchetypeId (virtual, ushort.MaxValue = not bound to a single archetype), overridden in EcsView<TArchetype>. ResolveChangeFilters selects the registry entry whose ArchetypeId matches the view's instead of the first cluster-eligible one. ViewBase previously had no way to name its archetype at all, which is why the runtime resorted to a global scan.

The ActiveClusterCount > 0 guard is RETAINED deliberately and is load-bearing: binding a cluster state switches the system to cluster-RANGE dispatch, which walks ActiveClusterIds and therefore ignores view-level filtering. I removed it on the first attempt and TierDispatchTests.View_WithTier_EndToEnd_NoSystemTier and DormancyTests.NonTierFiltered_SystemWithSleepingClusters_SkipsSleeping both processed every entity twice. There is a comment naming them so it does not get removed again.

TESTS - MultiArchetypeClusterDispatchTests, two cluster archetypes with asymmetric cluster counts (11 vs 1). Verified to FAIL against pre-fix code by temporarily reinstating the global scan. Two false-negative traps were found and closed in the process:

1. Ordering dependence. A single-system test passes or fails on which ArchetypeId happens to sort first. It runs a system on BOTH archetypes instead: the buggy scan hands them the same list, so one is provably wrong either way.
2. Chunk ids are SEGMENT-LOCAL, not global. Both archetypes number clusters from 1, so a foreign id is frequently also a valid local one - an "is this cluster id mine?" assertion passes while the bug is firing. It asserts COVERAGE instead: the 11-cluster system must cover {1..11}, not {1}. Any test comparing chunk ids across archetypes has this hole.

Found by a throwaway archetype-scaling benchmark that crashed at N=16 and double-processed at N=10, and could only produce valid numbers by working around this.

Suite 4054/0.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gcg4vW8vJ4QjNyj6NQabHs
…ystems, 5.3x budget headroom

Move, Regen and Wander iterated `foreach (id in ctx.Entities) { ctx.Accessor.OpenMut(id).Write(...) }` while BoundsSync, ten lines away in the same file, already used the columnar shape. Measured on 20 001 entities over 200 ticks, the two shapes cost 105 ns/entity and 2.2 ns/entity respectively (--cluster-bench). The sample was demonstrating the engine's slowest API in the one place its numbers get made.

An entity id names an entity; it does not say where it lives. So the id loop paid, per entity per system, a hash lookup into the EntityMap, a 23-byte record memcpy, an MVCC visibility check, and one to two chunk-address resolutions - to reach data already sitting contiguous in an SoA column. Iteration was never the problem: PartitionEntityView.MoveNext was 1.4% of MoveSystem.

The three systems now take a cluster range and walk columns. Measured with dotTrace sampling, self-time summed over every frame beneath each system body, normalised against BoundsSync as an untouched control (its own run-to-run spread is +-17%, so raw per-system numbers are not comparable across runs):

  MoveSystem  4869 -> ~370 ms      ~10x
  RegenSystem 4322 -> ~370 ms
  WanderSystem 5226 -> ~370 ms

Whole tick p50 went from missing its own 16.67 ms budget (~17.6 ms median, measured earlier via tracing) to 3.0-3.3 ms - 5.3x headroom - and that number is now PRINTED. TickTelemetry.ActualDurationMs is the right instrument here because the 60 Hz limiter sleeps out the remainder, so wall clock reports 60 Hz no matter how fast the systems are. It is stable to +-3% across runs, unlike the sampling profiler.

The readout immediately earned itself: p99 is 36 ms and worst is 55-65 ms against a 16.67 ms budget. The median is comfortable and the tail is not. That was invisible before, hidden behind the limiter.

ENGINE CHANGE - ClusterRef.MarkDirty<T>(Comp<T>). The direct cluster path sets no dirty bits, so a GetSpan write to a durable component is simply lost at the fence; ch.6 asserts Transform and Ham survive the reopen. ClusterEnumerator.MarkCurrentDirty() exists but takes no component, so it forwards to the 2-arg SetDirty which poisons the archetype's written-slot union to "all slots" - and that union is what narrows the columns a FenceBlock emits (#559). Using it here would have inflated WAL volume for every entity in the archetype. The new overload names the column and forwards to the 3-arg SetDirty.

TradeSystem built a 20 000-entry HashSet plus a 20 000-entry array every tenth tick to move credits between eight characters - >=3 MB of garbage per run. It now refreshes a roster every 300 ticks and opens defensively, since a roster can name an entity destroyed since the refresh. 82 -> ~14 ms, though at 3% of the profiled total that is inside the noise; the allocation removal is the real point.

SetSpatialBarrierOnly<Character>() - the sample writes Bounds exclusively through WriteSpatial, so the fence can trust that barrier's inline cell-crossing detector and skip its fall-back scan. WriteClusterTickFence 12 -> 6 ms across the run; the workbench trace shows DetectScan 416 -> 7 us on a given tick. It does not move p50 (that scan averages ~30 us/tick) but it is a tail contributor and it removes duplicated work: WriteSpatial had already done the detection.

Typhon.Analyzers is now referenced by the sample so TYPHON009 runs on it - that analyzer flags mutable span access to a [SpatialIndex] component, which is exactly what makes the barrier assertion checkable rather than assumed. The project builds with zero. Verified the analyzer is actually live by planting a violation and confirming it fires; "no warnings" and "analyzer not loaded" look identical otherwise.

SwgGuide.csproj is added to Typhon.slnx under the /samples/ solution folder (a virtual folder - the project stays at doc/guide/example, so the Typhon.Shell EmbeddedResource path and `dotnet run --project doc/guide/example` are unchanged). Rider could not resolve its types before. Side benefit: the solution build now compiles the guide example.

Behaviour is unchanged end to end - ch.6 still reports Transform (10.2, 36.5), Ham 100/100/100, Wallet 150 durable and Intent reset.

Engine 4054/0, SWG samples 4/4.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gcg4vW8vJ4QjNyj6NQabHs
… window for SingleVersion cluster state

A cluster archetype emits WAL records for its dirty SingleVersion values at every tick fence, and RecoveryDriver then discards all of them for any entity that already existed at the last checkpoint - which in a steady-state simulation is effectively all of them. RecoveryApplier has no ApplySlotToExisting; the comment at RecoveryDriver.cs:224 says so. So the engine writes, fsyncs and retains ~1.24 MiB/tick that nothing reads back, and the durability actually delivered for that data is the checkpoint interval, not the <=1-tick window ADR-057 and overview/02-execution.md:571 promise.

Meanwhile cluster STRUCTURE has never been WAL-logged at all - no record kind exists for slot claim/release, occupancy, entity keys or growth, and Transaction.ECS.cs:1561 deliberately keeps spawn out of the dirty bitmap. The fence is protecting values whose own entities were never protected.

New enum ClusterDurability { FenceWal (default), Checkpoint }, selected per archetype:

  [Archetype(ClusterDurability = ClusterDurability.Checkpoint)]
  public sealed partial class Character : Archetype<Character> { ... }

Per-ARCHETYPE and not per-component on purpose: a cluster page interleaves every component of the archetype, so page granularity cannot express a per-component policy. It sits on the durability axis established by ADR-005/ADR-057, not the storage axis - the cluster layout is unchanged.

Measured on doc/guide/example (20 001 entities, 60 Hz, Release, median of 3):

  tick p50              3.81 ms -> 1.88 ms   (2.03x)
  entity-updates/sec    21.0M   -> 42.5M
  headroom at 60 Hz     4.4x    -> 8.9x
  WAL bytes/tick        1.24 MiB -> 0

Before writing any code, an env-gated early-return probe confirmed the premise: it predicted p50 1.85 ms, the real feature landed at 1.88 ms.

The gate sits AFTER the dormancy sweep, dirty-ring archive, PreviousTickDirtySnapshot and the ComponentTable flag propagation, not at the top of FinalizeArchetypeFence. The dirty bitmap has eleven consumers and WAL emit is one of them; gating early would silently stop change-filtered dispatch without failing any durability test. ClusterDurabilityTests pins both halves, and both were proven by running them against deliberately broken engines: removing the gate fails the emission test, moving it above the bookkeeping fails the dirty-bitmap test.

Versioned components are unaffected in either setting - their revision chain is logged at commit and is authoritative, so no ClusterDurability value can lose a Versioned write. Transaction atomicity, lifecycle records and DurabilityDiscipline.Commit are untouched.

Deviations from the design doc (claude/design/Durability/cluster-page-durability.md), all deliberate:

- PageFlush is not in the enum. The doc specifies three values; shipping one that throws is worse than not having it. Pre-alpha, so adding it in P3 is free.
- The flat ComponentTable path is not gated (doc section 4.2 suggested it). Cluster archetypes write through the cluster dirty bitmap, so their tables report zero dirty entries and emit nothing already - the gate would be dead code, and ComponentTable->archetype is not 1:1 so it could not be written correctly anyway.
- No generator change was needed. ArchetypeRegistry reads [Archetype] by reflection at finalize time.

FenceWal's XML doc states its <=1-tick window is NOMINAL and cites #569 rather than claiming a guarantee the engine does not keep. An ADR is still required before this ships - it must decide whether Checkpoint documents today's real behaviour or changes it, which depends on how #569 is resolved.

Also in this commit: a comment-only correction in TickFence.cs. The #559 written-slot narrowing was documented as a per-cluster mask; per-cluster was implemented, measured (+2.1 ms/tick median, ~10 ms spread from false sharing) and rejected in favour of a single per-archetype union. The comment described the design that lost.

Design: claude/design/Durability/cluster-page-durability.md (Ready for implementation)
Tests: ClusterDurabilityTests (4). Suites 4061/0, samples 4/4, shell 22/22.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gcg4vW8vJ4QjNyj6NQabHs
…this tick

RecomputeClusterZoneMaps walked every dirty cluster and rescanned the min/max of EVERY indexed field, with no check on whether that field's component had been written. A field nobody wrote cannot have changed its min/max, so the rescan reproduced the same two values.

On the guide sample this was ~80% of the fence's Prep phase. Character indexes Faction.Value ([Index(AllowMultiple = true)]) and mutates Transform/Ham - which is correct schema design, the sample itself says "index what's stable, scan what churns" - so 435 clusters x 46 Faction values were rescanned every tick to reach an identical answer. The engine was punishing the right decision.

The fix reuses #559's FenceWrittenSlots, snapshotted by the caller fourteen lines before the call site and until now consumed only by the WAL emitter. Skip an index slot whose component bit is not set; bail before renting an accessor when nothing was written at all.

  tick p50            1.88 ms -> 1.57 ms
  entity-updates/sec  42.5M   -> 50.8M
  headroom at 60 Hz   8.9x    -> 10.6x

Fail-safe by construction: the union is AllSlotsWritten (-1) when any writer did not identify its component, so every bit is set and an unidentified write rescans everything. The failure direction is redundant work, never a stale zone map.

Two things checked before relying on this. Migration does not depend on the pass - ExecuteMigrations widens the destination zone map directly as it moves each entity (ZoneMap?.Widen(dstChunkId, ...)). And spawn never reached this loop anyway: Transaction.ECS.cs:1561 deliberately keeps spawn out of the cluster dirty bitmap, so the narrowing cannot make that path worse.

A stale zone map does not throw - it silently prunes clusters out of an indexed range query and rows quietly disappear. The tests therefore assert the observable consequence (query results), not the map's internals, and both guards were proven by forcing the narrowing to always skip: WritingTheIndexedComponent_StillRefreshesTheZoneMap and UnindexedTick_ThenIndexedWrite_StillRefreshesTheZoneMap both fail against that mutation.

Found by dotTrace tracing after the #568 gate removed the WAL emit and left the span still costing ~560 us. Worth noting the first hypothesis was wrong: ProcessClusterShadowEntries, the adjacent call in the same block, measured 0.3 ms across the ENTIRE run.

Tests: ClusterZoneMapNarrowingTests (3). Suite 4061/0.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gcg4vW8vJ4QjNyj6NQabHs
…he trace

Two additions to doc/guide/example/typhon.telemetry.json:

- GcTracing - one flag, previously never enabled, and the sample's own run reports gen2 collections. GC pauses are exactly the shape of an occasional multi-millisecond stall, and without this they are invisible in the Workbench.
- Runtime:ThreadScheduling - EtwSchedulingPump, which opens the NT Kernel Logger and emits one ThreadContextSwitch record per on-CPU slice for every Typhon-registered thread, carrying duration, wait reason, CPU number and ready-queue latency. This is what upgrades the Call Tree's on-CPU view from a proxy to real classification: SampleClassifier degrades to SampleClass.Unknown and relabels itself "thread time" when no context-switch records exist.

The Runtime subtree is enabled with its noisy siblings explicitly switched back off (Phase, Transaction, Subscription, WriteTickFence). That parent "Enabled": true is load-bearing, not decoration - the resolver is strictly parent-implies-children ("Parent off -> all descendants off, regardless of their own keys"), so enabling only the leaf is a silent no-op: no warning, no data, and a plausible-looking trace. Enabling the whole subtree instead costs ~18 MB per trace; this narrowing gets the context-switch lanes for ~9.5 MB.

ThreadScheduling is Windows-only and needs Administrator or Performance Log Users membership. Without either it prints one stderr line and the engine continues without scheduling data.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gcg4vW8vJ4QjNyj6NQabHs
…#532)

The pack-check job failed on this PR: the smoke test's consumer Program.cs still spawned a Harvester with Position/Footprint/Cargo/Drift/Extractor, all of which were replaced in 138d9c3 by Character with Transform/Bounds/Ham/Faction/Wallet/Intent in the Typhon.Samples.Swg.Shard namespace.

The script already compiles the REAL samples/Typhon.Samples.Swg/Light/*.cs against the package rather than a hand-maintained copy, precisely so the schema cannot drift. The hand-written consumer Program.cs beside it had no such protection and did drift - it is the one part of this gate that a schema rename can silently break, and the failure surfaces only in CI after a pack.

Rewritten against the current schema. Two deliberate additions while touching it:

- Read Wallet (Versioned, revision chain) alongside Ham (SingleVersion, cluster column). The old version exercised one storage mode; a package that wired only the easy path would have passed.
- Assert Faction through the generated ReadAll, which also puts an [Index(AllowMultiple = true)] component through the consumer compilation.

The test now also exercises ClusterDurability implicitly: Character declares [Archetype(ClusterDurability = ClusterDurability.Checkpoint)], so the enum must ship in the package for the consumer to compile at all.

Verified locally end to end - dotnet pack src/Typhon.Engine + scripts/consumer-smoke-test.sh - build 0 errors, "SMOKE OK", PASS.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gcg4vW8vJ4QjNyj6NQabHs
@github-actions

Copy link
Copy Markdown
Contributor

📝 Doc-accuracy review (advisory · scoped · Layer 2)

Reviewed:

  • doc/guide/01-first-app.md (edited in PR)
  • doc/guide/02-modeling.md (edited in PR)
  • doc/guide/03-transactions.md (edited in PR)
  • doc/guide/04-querying.md (edited in PR)
  • doc/guide/05-systems.md (edited in PR)
  • doc/guide/README.md (edited in PR)
  • doc/guide/getting-started.md (edited in PR)
  • doc/guide/using-with-ai-coding-agents.md (edited in PR)
  • doc/guide/isolation-durability-cheatsheet.md
  • doc/key-concepts/wal-checkpoint.md
  • doc/in-depth-overview/01-foundation.md
  • doc/in-depth-overview/11-durability.md
  • doc/in-depth-overview/13-resources.md
  • doc/feature-set/Foundation/access-control-lock-family/access-control-small.md
  • doc/feature-set/Resources/resource-budgets-options.md
  • doc/feature-set/Hosting/engine-options-configuration/options-validation-stubs.md

Findings

The PR raised WalRingBufferSizeBytes default from 8 MB to 64 MB (2 x 32 MB halves) in src/Typhon.Engine/Resources/public/ResourceOptions.cs. Four doc locations still claim 8 MB:

  1. doc/in-depth-overview/11-durability.md:73 ↔ src/Typhon.Engine/Resources/public/ResourceOptions.cs

    "Default is 8 MB total (ResourceOptions.WalRingBufferSizeBytes = 8 * 1024 * 1024). The buffer is split into two halves of 4 MB each"

    Fix: "Default is 64 MB total (ResourceOptions.WalRingBufferSizeBytes = 64 * 1024 * 1024). The buffer is split into two halves of 32 MB each"

  2. doc/in-depth-overview/13-resources.md:259 ↔ src/Typhon.Engine/Resources/public/ResourceOptions.cs

    | WalRingBufferSizeBytes | 8 << 20 (**8 MB**, not 4 MB) | In-memory WAL stage |

    Fix: change to 64 << 20 (64 MB, not 32 MB)

  3. doc/feature-set/Resources/resource-budgets-options.md:41 ↔ src/Typhon.Engine/Resources/public/ResourceOptions.cs

    WalRingBufferSizeBytes = 8 << 20, // 8 MB

    Fix: WalRingBufferSizeBytes = 64 << 20, // 64 MB (default — 2 x 32 MB halves)

  4. doc/feature-set/Resources/resource-budgets-options.md:59 ↔ src/Typhon.Engine/Resources/public/ResourceOptions.cs

    | WalRingBufferSizeBytes | 8 MB | Commit threads block once the ring drains slower than it fills |

    Fix: change default to 64 MB and add "(2 x 32 MB halves — sized for tail-latency; lower for memory-constrained deployments)"

Also note: doc/feature-set/Hosting/engine-options-configuration/options-validation-stubs.md:40 shows WalRingBufferSizeBytes = 8 << 20, // 8 MB in a code snippet — this is a usage example, not a default claim, but the // 8 MB comment now describes a non-default override and may mislead readers.


Map maintenance:
The docs-affected report listed these UNMAPPED source areas (no doc pages mapped — consider adding to coverage/docs-affected-map.json):

src/Typhon.Shell/Commands/DiagnosticCommandExecutor.cs
src/Typhon.Shell/Commands/NewCommand.cs
src/Typhon.Shell/Commands/ProjectScaffolder.cs
src/Typhon.Shell/Commands/TelemetryCommands.cs
src/Typhon.Shell/Commands/UiCommand.cs
src/Typhon.Shell/Telemetry/TelemetryEditor.cs
src/Typhon.Shell/Typhon.Shell.csproj

Advisory & scoped to the pages the change touches — recall for cross-cutting or unmapped drift is covered by the weekly Layer 3 audit.

The doc-accuracy reviewer on PR #586 flagged four locations still documenting WalRingBufferSizeBytes as 8 MB (2 x 4 MB halves). d7b2101 raised the default to 64 MB (2 x 32 MB halves) and did not sweep the docs.

Verified against ResourceOptions.cs:66 (= 64 * 1024 * 1024) and DatabaseEngine.cs:993 (the /2 halving) before changing anything - the finding is correct on all four.

- in-depth-overview/11-durability.md - corrected, and given the RATIONALE the number now depends on: the default is sized for tail latency, not throughput. The median tick is flat across 8/16/32/64 MB; the worst tick falls ~29 ms -> ~18 ms at 64 MB, because a ring that fills makes producers block on the buffer swap. Without that, the next person to see 64 MB of pinned memory has no way to judge whether it is deliberate.
- in-depth-overview/13-resources.md - table row.
- feature-set/Resources/resource-budgets-options.md - code sample and defaults table.

Plus one the reviewer raised as advisory rather than a finding, and it was right to: feature-set/Hosting/.../options-validation-stubs.md:40 uses 8 << 20 in a snippet that is an explicit OVERRIDE, not a default claim. The value is fine; the bare "// 8 MB" comment reads as the default now that it is not. Annotated rather than changed - editing it would have broken the point of the example.

doc/_site/ carries the same stale text but is gitignored build output and regenerates from these sources.

Not addressed here: the reviewer also listed src/Typhon.Shell/Commands/* as UNMAPPED in coverage/docs-affected-map.json. That is real (the #531/#532 CLI work added those files with no mapped doc pages) but it is map maintenance for the onboarding CLI, not this fix.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gcg4vW8vJ4QjNyj6NQabHs
@github-actions

Copy link
Copy Markdown
Contributor

📝 Doc-accuracy review (advisory · scoped · Layer 2)

Reviewed:

  • doc/guide/01-first-app.md (deep — edited in PR)
  • doc/guide/02-modeling.md (deep — edited in PR)
  • doc/guide/03-transactions.md (deep diff)
  • doc/guide/04-querying.md (deep — edited in PR)
  • doc/guide/05-systems.md (deep diff)
  • doc/guide/README.md (diff)
  • doc/guide/getting-started.md (deep — edited in PR)
  • doc/guide/using-with-ai-coding-agents.md (deep — edited in PR)
  • doc/in-depth-overview/11-durability.md (deep — edited in PR)
  • doc/in-depth-overview/13-resources.md (deep — edited in PR)
  • doc/in-depth-overview/01-foundation.md (read)
  • doc/in-depth-overview/03-indexing.md (targeted read — OLC section)
  • doc/feature-set/Hosting/engine-options-configuration/options-validation-stubs.md (diff + file)
  • doc/feature-set/Resources/resource-budgets-options.md (diff + file)
  • doc/feature-set/Foundation/access-control-lock-family/access-control-small.md (read)
  • doc/feature-set/Indexing/olc-concurrency.md (read)
  • doc/key-concepts/wal-checkpoint.md (read)
  • Corpus-wide grep for stale 8 MB / 8 << 20 WAL defaults, and for old component names (Harvester drone, SwgGuide, Footprint, etc.)

Findings:

  1. doc/in-depth-overview/03-indexing.md:116 ↔ src/Typhon.Engine/Indexing/internals/OlcLatch.cs

    "On x64 (TSO), no memory barriers are needed — loads aren't reordered with other loads, and the write-lock CAS provides the acquire/release on the writer side."

    This PR adds an explicit Interlocked.MemoryBarrier() inside OlcLatch.ValidateVersion() for non-x86 targets (if (!X86Base.IsSupported)), precisely because plain loads are reordered on arm64 and the validate step can fail without the barrier. The doc's statement that barriers are "not needed" is now only half-true (correct for x64, silent about arm64).

    Suggested fix: After "On x64 (TSO), no memory barriers are needed …", add: "On arm64 (weak memory model), ValidateVersion emits an Interlocked.MemoryBarrier() before the re-read to prevent earlier plain loads from sinking past the validating acquire load — this folds to nothing on x64 because X86Base.IsSupported is a JIT-time constant."

  2. doc/guide/01-first-app.md:13 ↔ doc/guide/example/Systems.cs:24 + samples/Typhon.Samples.Swg/Light/Character.cs:5

    📦 This is the scaffold. The model below is exactly what typhon new <name> emits … and what the runnable example/ project runs.

    The code block that follows uses namespace ShardGuide / using ShardGuide;. But typhon new embeds files verbatim: Character.cs uses namespace Typhon.Samples.Swg.Shard;, while Systems.cs (also embedded) still declares namespace SwgGuide; — and Program.cs imports it as using SwgGuide;. ShardGuide appears nowhere in the scaffold. Before this PR the doc showed SwgGuide, which at least matched Systems.cs. This PR changed the inline example to ShardGuide without renaming the scaffold namespaces.

    Suggested fix: Either (a) rename namespace SwgGuide; in Systems.cs and Program.cs to ShardGuide to match the doc, or (b) revert the note's claim to "the same data model as" instead of "exactly what … emits", and note that the scaffold uses the Typhon.Samples.Swg.Shard namespace.


Map maintenance:

The following source files have no mapped doc pages and were not reviewable for doc drift (from the docs-affected report):

src/Typhon.Shell/Commands/DiagnosticCommandExecutor.cs
src/Typhon.Shell/Commands/NewCommand.cs
src/Typhon.Shell/Commands/ProjectScaffolder.cs
src/Typhon.Shell/Commands/TelemetryCommands.cs
src/Typhon.Shell/Commands/UiCommand.cs
src/Typhon.Shell/Telemetry/TelemetryEditor.cs
src/Typhon.Shell/Typhon.Shell.csproj

ProjectScaffolder.cs in particular changed substantially (new typhon new scaffolding with Character.cs); consider mapping it to doc/guide/getting-started.md in coverage/docs-affected-map.json.


Advisory & scoped to the pages the change touches — recall for cross-cutting or unmapped drift is covered by the weekly Layer 3 audit.

… claim in 01-first-app [no-doc] [no-ut]

Both findings from the Layer 2 reviewer on PR #586, verified against the code before changing anything.

1. in-depth-overview/03-indexing.md:116 said "On x64 (TSO), no memory barriers are needed" and stopped there. That reads as "OLC needs no barriers", which this PR makes false: OlcLatch.ValidateVersion now issues Interlocked.MemoryBarrier() under if (!X86Base.IsSupported). Documented WHY rather than just noting the call - the reader's plain data loads sit between ReadVersion() and the validating re-read, and an acquire load only stops LATER accesses from hoisting above it, not earlier plain loads from sinking below it on a weakly-ordered CPU. X86Base.IsSupported is a JIT-time constant, so it folds to nothing on x64 and emits dmb ish on arm64. This is the memory-ordering discipline in the root CLAUDE.md, and 03-indexing was the one place stating the opposite.

2. guide/01-first-app.md:13 claimed the model below is "exactly what typhon new <name> emits". It is not, and the reviewer is right that this PR made it worse by renaming the chapter's inline namespace to ShardGuide - a name that appears nowhere in the scaffold.

   Root cause worth recording: the scaffold embeds files VERBATIM from two different projects (Typhon.Shell.csproj:39-43). Character.cs comes from samples/Typhon.Samples.Swg/Light/ and carries namespace Typhon.Samples.Swg.Shard; Systems.cs comes from doc/guide/example/ and carries namespace SwgGuide. So `typhon new MyGame` produces a user project containing a sample assembly's namespace, and the chapter showed a third name again.

   Took the reviewer's option (b): correct the claim, keep the chapter's single-file ShardGuide illustration. Renaming SwgGuide -> ShardGuide (option (a)) would still leave Typhon.Samples.Swg.Shard in Character.cs, since that file's namespace belongs to the samples assembly - so (a) cannot actually make the claim true. The note now says "the same components and archetype", and spells out both differences (one file vs three, and the two real namespaces) instead of implying byte-identity.

   The underlying wart - a generated starter project carrying Typhon.Samples.Swg.Shard - is an onboarding defect rather than a doc defect, and is not fixed here.

[no-doc] because this commit only reconciles drift the reviewer itself flagged; re-running it on its own fix costs 5-10 min for nothing. [no-ut] because it is docs-only.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gcg4vW8vJ4QjNyj6NQabHs
@nockawa
nockawa merged commit 884b391 into main Jul 27, 2026
10 checks passed
@nockawa
nockawa deleted the ux-imp branch July 27, 2026 21:52
nockawa added a commit that referenced this pull request Jul 29, 2026
…ped, files issues [no-doc] [no-ut]

Loïc's argument, which I initially pushed back on and was wrong to:

  1. Nothing required the check and nothing blocked on it, so a PR could merge while the review was still running. The findings then landed on a closed PR nobody revisits - the per-PR TIMING bought nothing anyone could act on.
  2. Reconciling docs is a different job from writing the feature, and the author is the worst reviewer of prose they wrote ten minutes ago and believe.

My earlier objection - "post-merge it degrades into a corpus audit, which Layer 3 already does" - was only true of a WHOLE-CORPUS post-merge run. Scoped to yesterday's merges it keeps the diff-to-page association that is the only thing making Layer 2 worth more than an audit. That is the mistake; this commit fixes it.

What changed:

- doc-accuracy-review.yml is now nightly (05:00 UTC, an hour before the Monday Layer-3 audit so the weekly sweep dedups against whatever the nightly just filed). It lists the PRs merged in the last 25 h, resolves each one's affected doc pages, reviews them, and FILES [doc-drift] ISSUES rather than commenting on a merged PR. Every issue must carry "Introduced by: #N" - that attribution is precisely what a whole-corpus sweep cannot produce.
- Fork PRs are no longer a special case. The old per-PR job had to skip them (no secrets, injection surface); a scheduled job cannot receive one, so fork-introduced drift is now covered like everything else instead of being deferred to Layer 3.
- CONTRIB.md: [no-doc] is retired. It existed to break the fix -> re-review -> fix loop, which was a workaround for a cadence that was wrong to begin with. Harmless if anyone still writes it.

Two things testing found before this could ship, both real:

- Unioning the PRs' file lists resolved to 227 affected pages against a 329-file corpus - a whole-corpus sweep wearing a scoped costume, i.e. exactly what I had just argued against. Now resolved PER PR (measured on the same night: #598 -> 86 pages, #586 -> 226, #570 -> 0), which also keeps the "Introduced by" attribution honest since each page list has one PR behind it.
- One big PR can alone resolve to ~230 pages, so a ten-PR night would exhaust the turn budget and produce a shallow skim of everything instead of a real review of something. Capped at the 5 most recent, with a ::warning:: and a line in the prompt naming the overflow - a silently truncated sweep reads exactly like a clean one, which is the failure mode this layer exists to avoid. The remainder falls to Layer 3.

Also rejected, and recorded in the workflow header so it is not re-proposed: an opt-in [doc-review] token, and reviewing only when a draft PR is marked ready. Both fail UNSAFE when someone forgets - no review at all, or only commit 1 reviewed. Loïc made this argument against [doc-review] and it applies equally to the draft-based design I had already written. This one has nothing to remember.

The scope step was extracted from the YAML and executed against the live repo end to end (PR listing, per-PR diff, docs-affected resolution, output gating) - heredoc-inside-block-scalar is where this class of workflow usually breaks.

Layer 1 (scripts/check-doc-links.py, blocking, ~0.5 s) still runs on every push. Layer 3 (weekly whole-corpus) is unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gcg4vW8vJ4QjNyj6NQabHs
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