Skip to content

ChaosStressTests: 5 deterministic failures on first-ever execution, incl. a conserved-sum (atomicity) violation #696

Closed

Description

@nockawa

Summary

ChaosStressTests had a fixture-level [Ignore("Too long, should be manually executed when needed")] (test/Typhon.Engine.Tests/Data/ChaosStressTests.cs:22). NUnit applies [Ignore] unconditionally — --filter cannot override it — so "manually executed when needed" was not achievable without editing source, and these tests appear never to have run.

Changed to [Explicit] on branch epic-411 (keeps them off the default run, makes them selectable) and ran them. 5 of 23 fail deterministically — same 5 in all 3 runs. A 6th (Scale_4T_500E) fails intermittently (2 of 3). One more (CreateDeleteRecreate_RapidLifecycle) livelocks — filed separately as #695.

⚠️ These are first-execution results on tests that have never run. Some may be stale test expectations rather than engine defects — they need triage, not assumption. I have triaged the most serious one below and it does look like an engine defect. The others are reported as-found.

Results — --filter "…ChaosStressTests" excluding CreateDeleteRecreate/UltimateStress/Torture

Test Runs failed Symptom
CrossEntityTransaction_AtomicMultiUpdate 3/3 conserved sum violated — see below
AllowMultipleIndex_HighChurn 3/3 Entity expected B=200085 got 300084
IndexSplit_CascadingSplitsUnderContention 3/3 Global verify: B=50194 entity has wrong B field: 30198
RollbackStress_ConcurrentRollbacks 3/3 Entity 48: Value 1201 != expected 4801
UniqueIndexViolation_UnderLoad 3/3 Winner B=32 has wrong B field: 28
Scale_4T_500E 2/3 Entity(Key=19, Arch=1) not found in PK index for CompA @ Transaction.ECS.cs:1247

The durability-specific tests in the same fixture all PASS — DurabilityRestart_DataSurvivesReopen, Checkpoint_ConcurrentWithHeavyWrites, DurabilityModes_MixedModesUnderLoad, PageCachePressure_ManyEntitiesSmallCache. The failures cluster on concurrent value correctness and indexes, not on durability.

The one I triaged: CrossEntityTransaction_AtomicMultiUpdate

A transfer workload: 6 threads × 50 transfers, each moving 1 unit from one entity to another inside a single transaction, with a delta-rebase ConcurrencyConflictHandler. The invariant is conservation — the total is unchanged.

Final sum mismatch: 20001 != 20000 after 282 transfers, 35 conflicts, 2 bad deltas, 2 errors.
Mismatches: e4: actual=1003(d=3) expected=1000(d=0) diff=3,
            e11: actual=1004(d=4) expected=1005(d=5) diff=-1,
            e12: actual=1001(d=1) expected=1002(d=2) diff=-1

Two independent signals point at the engine rather than the test:

  1. e4 gained 3 units that no successful transfer accounts for (expected d=0). Units were created, not merely misattributed — the total is +1.
  2. 2 bad deltas — that counter is the test's own instrumentation inside the conflict handler:
    var delta = m.A - r.A;                       // committing minus read, same entity
    if (delta != 1 && delta != -1) { badDelta++; }
    Every transfer writes exactly ±1, so within one entity committing - read must be ±1. It firing means the engine handed the handler a (ReadData, CommittingData) pair that do not correspond — e.g. the wrong entity's snapshot, or a read snapshot that moved under the transaction.

That is a conflict-resolution/rebase defect in the commit path, and it violates atomicity, not durability. Plausibly the same family as the ECS-5 / ECS-6 commit-path races on the H (hygiene) track of claude/design/Durability/MinimalWal/README.md:106, which was never started.

Reproduction

git checkout epic-411
dotnet test test/Typhon.Engine.Tests/Typhon.Engine.Tests.csproj -c Debug --no-build \
  --filter "FullyQualifiedName~ChaosStressTests&FullyQualifiedName!~CreateDeleteRecreate&FullyQualifiedName!~UltimateStress&FullyQualifiedName!~Torture"

Why this went unseen — worth fixing independently of the bugs

bench/aws/shards.json shard [3] explicitly lists Typhon.Engine.Tests.ChaosStressTests in its classes array, and its filter selects it. So CI allocated a slot and a time budget to this fixture, ran 0 of its tests because of the [Ignore], and reported green.

Suggested guards:

  • [Ignore] should never be used to mean "long-running" — that is [Explicit]. Consider a test/lint that rejects fixture-level [Ignore] without an issue reference.
  • A shard that resolves to 0 tests for a class it names should fail, not pass silently.

Suggested next steps

  • Triage each of the 5 as engine-defect vs stale-expectation; open a focused issue per confirmed defect.
  • CrossEntityTransaction_AtomicMultiUpdate first — it is an atomicity violation with a reproducible, self-instrumented signal.
  • Decide where these run once green (nightly [Explicit] selection is the natural home, and shard 3 already believes it does this).

Related: #695 (livelock in the same fixture), #679 (OLC B+Tree concurrency — three of the failures above are index-related), Epic #411.

🤖 #411 reassessment — claude/research/Durability/epic-411-reassessment/.

Activity

  1. added theissue type on Aug 7, 2026
  2. updated Area Execution, Priority P1-High, Estimate M and Product Engine on Aug 7, 2026
  3. added a commit that references this issue on Aug 8, 2026
  4. moved this to Todo in Typhonon Aug 8, 2026
  5. nockawa commented on Aug 8, 2026

    @nockawa
    CollaboratorAuthor

    Three of the five are not index failures

    AllowMultipleIndex_HighChurn, IndexSplit_CascadingSplitsUnderContention and UniqueIndexViolation_UnderLoad all report in the shape B=50196 entity has wrong B field: 40156, and the issue groups them under "concurrent value correctness and indexes". The verification that produces that string does not touch an index:

    var comp = txn.Open(kvp.Value).Read(CompDArch.D);
    if (comp.B != kvp.Key) errors.Add(...)

    It opens by entity id. So the claim is that Open(id).Read() serves another entity's data — a different and worse defect than a stale index entry.

    The cheaper explanation, ruled out first

    Spawn handing the same id to two entities would produce the identical symptom via the test's own ConcurrentDictionary. PR #721 builds the reverse map and reports duplicates before the value check, so a failure now says which of the two it is.

    Measured, IndexSplit_CascadingSplitsUnderContention on main, Debug:

    (no DUPLICATE ENTITY ID lines — every id distinct)
    
    Entity(Key=1112, Arch=6)  valid=True  B=20197  read 10160
    Entity(Key=1113, Arch=6)  valid=True  B=20198  read 10161
    Entity(Key=1114, Arch=6)  valid=True  B=20199  read 10162
    Entity(Key=1147, Arch=6)  valid=True  B=50186  read 10195
    Entity(Key=1148, Arch=6)  valid=True  B=50187  read 10196
    Entity(Key=1149, Arch=6)  valid=True  B=50188  read 10197
    Entity(Key=1150, Arch=6)  valid=True  B=50189  read 10198
    Entity(Key=1151, Arch=6)  valid=True  B=50190  read 10199
    

    Contiguous entity keys resolving to contiguous wrong values, offset by a constant, from another thread's range. Not a lost update (the values are coherent, just someone else's) and not a stale index entry (no index was consulted). It is a block of surviving entities whose records resolve to slots now holding other entities' data.

    The workload that produces it is phase 2 — destroy every third entity and immediately respawn, on several threads at once.

    Direction, stated as a direction

    Slot reuse across a concurrent destroy, which is the neighbourhood of #582 face 1: ReleaseSlot frees a chunk with nothing excluding a concurrent reader or claimant. The contiguity could equally come from a swap-with-last compaction moving a survivor without updating its record. I have not traced it and am not claiming a root cause.

    What changes is the starting point. The next pass begins from "entity resolution returns another entity's data, ids are distinct, blocks are contiguous, cross-thread" rather than from three index-shaped error strings and a wrong subsystem.

    The other two (CrossEntityTransaction_AtomicMultiUpdate, RollbackStress_ConcurrentRollbacks) are untouched and still reproduce deterministically — the conserved-sum one at 19997 != 20000 with 3 bad deltas, matching the issue's own triage.

    🤖 Bug-bash round three (PR #721).

  6. added 2 commits that reference this issue on Aug 8, 2026
  7. nockawa commented on Aug 14, 2026

    @nockawa
    CollaboratorAuthor

    ChaosTest_MultiThreadedCRUD quarantined (5aa4803) — its red band is wider than this issue records

    This issue notes Scale_4T_500E failing 2 runs of 3. Running the fixture on unmodified main today, the band is wider and the victim moves:

    Run Failing ChaosTest_MultiThreadedCRUD cases
    A HeavyWrite_4T_200E_WithDelete
    B Light_2T_50E_NoDelete, Medium_4T_100E_WithDelete, Scale_4T_500E, HeavyWrite_4T_200E_WithDelete

    Between one and four of the six cases fail per run, with a different subset each time. The seven tests already quarantined against this issue fail on every run by contrast — so this is a second, nondeterministic face of the same concurrent value/index correctness family, not the same failure.

    Quarantined at the method rather than case by case, because the victim moves and per-case suppression would chase it. QUARANTINE.md row added.

    Worth noting why it went unrecorded for so long: the fixture is [Explicit], so the merge gate never selects it and these failures only appear when someone runs it by hand. Marking the category does not change what the gate runs — it makes the known-red state declared rather than rediscovered, and puts the test in the list that gets revisited when this issue closes.

    Two more reds seen on the same box, not part of this fixture

    While running the full suite repeatedly today (4 runs), two unrelated tests failed once each with different victims — consistent with the #720 flake band, but both have concrete evidence worth recording:

    Neither is caused by the fence work on feature/bug-bash (which touches only per-chunk buffer sizing). Flagging the first in particular, since it has a stack trace pointing at recently-merged code.

  8. added a commit that references this issue on Aug 15, 2026
  9. nockawa commented on Oct 5, 2026

    @nockawa
    CollaboratorAuthor

    Bug bash 2026-10-05 — Fixed on branch bug/696-chaos-stress-atomicity @ 60f0d91 (partial: 2 engine defects fixed; the rest triaged to other issues)

    Still live on main: yes. On cca609b0 (pinned 8 CPUs, 7 runs) the 7 quarantined tests fail 7/7, apart from IndexSplit at 6/7. ChaosTest_MultiThreadedCRUD fails 1–6 runs of 7 depending on the case. The fixture also hung until the 300 s timeout twice on main; the test was not identified (0 hangs in 6 --blame-hang runs on the branch).

    Repro (deterministic, single thread; fail on main, pass on the branch):

    • TransactionTests.Rollback_Updated_ThenDisposedAfterAnotherWrite_DoesNotFreeThatWritesChunk
    • TransactionTests.Rollback_Created_ThenDisposedAfterAnotherSpawn_DoesNotFreeThatSpawnsChunk
    • TransactionTests.Rollback_Updated_OfANonLastRevision_KeepsTheLaterCommit

    Four more guard the fix, each checked against a mutant: trailing-void trim, compaction before rollback, LCRI not on a void, and an expired-deadline rollback that must wait.

    Root cause 1: a rollback frees its chunks twice, so two entities end up sharing one payload. This is the "wrong B field" / "Value 902 != expected 501" family.

    • How it was found: a chain dump showed entities 14 and 33 both headed by content chunk 66. The alloc/free trace of that chunk reads ALLOC (T24 write) → FREE (T24 RollbackComponent) → ALLOC (T21 write) → FREE (T24 CleanupEcsState ← Reset ← TransactionChain.Remove) → ALLOC (T10 write).
    • First free: Dispose rolls back (EnsureCompleted), and RollbackComponent frees the copy-on-write or spawn chunk (Transaction.cs:1488-1491).
    • Second free: the pool reset frees the same chunks again for any non-Committed state, Rollbacked included (Transaction.ECS.cs:3882-3965).
    • Why it hid: FreeChunk silently ignores a clear bit (ChunkBasedSegment.cs:750-754), so a single thread never sees it. It bites whenever another write takes the chunk between the two frees.

    Root cause 2: rolling back a revision that is not the last one drops the chain's last entry.

    • ComponentRevision.VoidElement does --ItemCount, unconditionally and without the lock.
    • When a later transaction has appended and committed, that decrement removes the committed entry from the range.
    • Result, deterministic: T1 write, T2 write+commit, T1 rollback reads the value from before T2.

    Fix:

    • Single owner. RollbackComponent is the only code that frees these chunks (branch L1467):
      • it frees CC-aware, so the rollback, not a reset reading a freed chunk, releases the ComponentCollection buffers, even when the transaction is not pooled;
      • it disarms each entry after freeing, so a re-run frees nothing.
    • Reset frees nothing Versioned. CleanupEcsState no longer frees any Versioned chunk and asserts it never resets an InProgress transaction.
    • Trim only the tail. VoidElement voids the entry, then trims trailing voids, all of them. A trailing void would make cleanup free the committed sentinel.
    • LCRI skips voids. Cleanup's copy phase no longer points LCRI at a void left mid-chain (ComponentRevisionManager.cs:336).
    • Void under the lock. RollbackComponent voids under the chain's exclusive lock with an unbounded wait. This is the rollback half of A conflict without a handler, and a rollback, void a revision entry by a stale position without the chain lock #1161; its conflict-path half is untouched.
      • The entry must be isolated, carry this transaction's TSN and its chunk (IsOwnPendingEntry).
      • The chunk is freed only if that check passes.

    Effect on the fixture (8 CPUs). Columns: main (7 runs); branch (8 runs); branch plus #1158's publish fix from fix/1151-1158-1159-coherence (7 runs). The #1158 fix was applied as an experiment and not committed.

    Test main branch + #1158
    RollbackStress_ConcurrentRollbacks 7/7 0/8 (0/8 on 4 CPUs) 0/7
    UniqueIndexViolation_UnderLoad 7/7 2–4/8 (0/8 on 4 CPUs) 1/7
    IndexSplit_CascadingSplitsUnderContention 6/7 6/8 0/7
    MultiThreadedCRUD Scale / Medium / HeavyWrite 6 / 4 / 5 of 7 5 / 5 / 5 of 8 0 / 4 / 3 of 7
    CrossEntityTransaction_AtomicMultiUpdate 7/7 8/8 7/7
    AllowMultipleIndex_HighChurn 7/7 8/8 7/7
    CreateDeleteRecreate_RapidLifecycle 7/7 8/8 7/7

    The conserved-sum test: its remaining cause is #1146, not fixed here.

    Not fixed, evidence only:

    Review (/code-review, one reviewer):

    • B1 (my first version waited with the caller's deadline, so rollback could throw part-way and the Dispose re-run would double-free): fixed with the unbounded wait plus disarmed entries; test added.
    • B2 (pre-existing: the fallback search matched the committed head by chunk id, then freed it): fixed with IsOwnPendingEntry, and the chunk is freed only once the entry is found.
    • B3 (cleanup put LCRI on a mid-chain void): fixed, test added.
    • Test precondition gaps: fixed. The two double-free tests now assert that the freed chunk was reissued.
    • Reported, not fixed: an entity updated, then destroyed in the same transaction, leaks its copy-on-write collection add-ref (Transaction.ECS.cs:3519-3523, pre-existing).
    • Behaviour change: rolling back a mid-life Created component (Enabling a never-supplied Versioned component returns a DESTROYED entity's data — the recycled chunk is not cleared #845) now releases its collection buffers. Before, they leaked. No test covers it.

    Gate: pre-push.sh full green.

    Open:

  10. changed
    Bug status
    toon Oct 5, 2026
  11. added a commit that references this issue on Oct 12, 2026
  12. nockawa commented on Oct 12, 2026

    @nockawa
    CollaboratorAuthor

    Bug bash 2026-10-12 — both engine defects fixed on main; branch now only un-quarantines (bug/696-chaos-stress-atomicity @ 8eb9504)

  13. added a commit that references this issue on Oct 12, 2026
  14. moved this from In Progress to Todo in Typhonon Oct 12, 2026
  15. moved this from Todo to In Progress in Typhonon Nov 2, 2026
  16. moved this from In Progress to Done in Typhonon Nov 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Fields

    Priority

    P1-High

    Estimate

    M

    Area

    Execution

    Start date

    None yet

    Target date

    None yet

    Bug status

    Fixed

    Product

    Engine

    Projects

    • Status
      Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions