Repository navigation
Conversation
Adding CLAUDE.md with task information for AI processing. This file will be removed when the task is complete. Issue: #78
This implementation addresses issue #78 by providing: - Lock-free insertions: Multiple insertions (N) can be performed concurrently using ReaderWriterLockSlim read locks - Delayed balancing: Balancing operations are delayed until a configurable threshold of insertions is reached - Thread-safe operations: Uses atomic operations (Interlocked) for tracking insertion counts - Exclusive locking for balancing: Tree balancing only locks when necessary using write locks Key features: - PartiallyLockFreeSizeBalancedTreeMethods<TElement>: Abstract base class extending SizeBalancedTreeMethods - Configurable balancing threshold (default: 10 insertions) - Manual balancing trigger via ForceBalancing() method - Thread-safe insertion counter with atomic operations - Custom delayed balancing logic that mirrors original maintain operations - Comprehensive test suite including concurrent insertion tests 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
|
Double check it actually support any multiple operations on such tree, and it does not break under stress. Also we need to check all latest experience in the internet and so on, so we can reimplement all best possible algorithms, which support concurrent operations on trees, if they actually exist, work, and are stable, or even totally lock free, that may allow us to have much more performant trees. And make access to them fully concurrent. If now such solution exists, but we are feeling lucky, we can try implement one from scratch, but if we prove it does not work, we record it as failed attempt. |
|
🤖 AI Work Session Started Started at 2026-12-04T00:01:41.718Z. Please wait for it to finish before giving feedback. Runtime: solve |
…mpt breaks under concurrent inserts 6 threads x 5000 concurrent Attach calls corrupt subtree sizes in 9 of 10 rounds (non-atomic IncrementSize and non-atomic child-slot writes under a shared read lock).
…attaches with delayed balancing - Attach links nodes with compare-and-swap on empty child slots and atomic size increments, concurrent attaches and reads never block each other. - Balancing (every N attaches) and Detach take an exclusive gate; balancing restores the size balanced tree property along the paths of pending nodes with a general Maintain. - Attach of an already attached node no longer corrupts the tree. - Add concurrent stress tests for attach, detach and contains. - Make the failed attempt #1 experiment reproducible against commit bb183b7.
The benchmark shows that eager atomic size increments on every attach make the partially lock-free tree slower than a size balanced tree under a global lock.
…ounded pending slots Attaches no longer increment the sizes of all ancestors (contended atomic operations on the top nodes); the balancing recomputes sizes along the paths of pending nodes. Shared mode uses per-processor padded counters instead of a single counter. Pending slots are reserved inside the shared mode and attaches wait when all of them are taken, so overflow handling is not needed. Adds deterministic tests for the waiting paths, duplicate keys and the maximum threshold recursion depth, and fixes nullability warnings. Also makes setup-node version comments exact: the v7 tag has moved to v7.2.0, so zizmor reported the v7.1.0 pin as mismatched.
…sults - Balancing counts the pending nodes of every subtree instead of reading the child off the path, and checks only the grandchildren of a grown side (general Maintain stays the fallback and handles duplicate keys). - Waiting attaches and reads spin read-only on the gate. - Stress tests run on dedicated threads behind a barrier with a timeout, and catch only the expected exceptions (CodeQL). - docs/concurrent-trees.md: survey of concurrent and lock-free trees, design, guarantees, verification, failed attempts and benchmarks; linted in CI. - Benchmark: v2/v3 results and a split of attach vs balancing time. - Mutation check rerun: all five synchronization mutations are detected. - Version 1.1.0 with release notes; README lists the new tree.
A pending node without pending descendants is a leaf, but the balancing still computed the sizes of its children and read GetSize(0), which a storage without element 0 cannot serve. Such a leaf needs no maintenance. BalancingNeverReadsSizeOfNullNodeTest fails without the fix.
docfx builds the README into the documentation site, where a relative link to docs/ is invalid and fails the --warningsAsErrors build.
Main now checks that every tree credits the original authors of its algorithms; the partially lock-free tree builds on Chen's size balanced tree and on the relaxed balancing of Kung and Lehman (1980) and Nurmi and Soisalon-Soininen (1996).
Working session summaryI've added How it works
Your review comment
Performance (1,000,000 nodes, 6 cores, million operations per second):
Bug found during review: balancing read the size of the empty node (node 0) when it reached a newly added leaf. It's fixed, and a regression test fails before the fix and passes after. Other changes
Six CodeQL warnings were raised on earlier commits, and CodeQL now marks each of them as fixed. No other review bots have commented. This summary was automatically extracted from the AI working session output. |
🤖 Solution Draft LogThis log file contains the complete execution trace of the AI solution draft process. 💰 Cost estimation:
📊 Context and tokens usage:Claude Opus 5.5: (6 sub-sessions)
Total: (13.2K new + 579.2K cache writes + 20.3M cache reads) input tokens, 259.0K output tokens, $13.747981 cost Claude Haiku 5.5:
Total: 577.6K input tokens, 40.9K output tokens, $0.308222 cost 🤖 Models used:
📎 Log file uploaded as Gist (9554KB)This AI session has ended. Monitoring of this pull request continues. Feel free to review and add feedback while checks are running. |
🔄 Auto-restart 1/5Reason: CI failures detected Evidence:
Starting a new session to address it. |
- The balancing thresholds are static properties and the constructors are overloads instead of public constants and optional parameters (S2339, S2360). - Balance(ref root) and Contains(node, ref root) suppress S3874 in their own file: Codacy compiles each file alone and does not see GlobalSuppressions.cs, and the root must be read and replaced in place under the exclusive gate. - The fallback lock of AtomicElement lives in a non-generic class, so it is one lock for all element types (S2743). - PaddedCounter and the element structs are record structs, which implement IEquatable<T> (S3898). - The test tree exposes Root by reference from a readonly one-element array and its hooks as properties, as the other test trees do (S1104, S2357). - The experiments brace every statement and throw InvalidOperationException (S121, S112).
Codacy reported lines over 80 columns (MD013) and table separators without spaces (MD060) in the experiment notes and recorded benchmark results. The benchmark now prints its header on two lines and spaced separators, the recorded results match that output, and the stress note is wrapped at 80 columns. The Markdown job also lints experiments/**/*.md, so these findings fail in CI before Codacy reports them.
…ructor With threshold 4096 sorted attaches form an 8192 node chain, and the first balancing recursed along it in unoptimized tier 0 code, which overflowed a 1 MB stack (and a 1.5 MB one). The full test suite hid this because other tests made the JIT optimize MaintainPaths first; run alone, or under coverage instrumentation, the stack test crashed the test host. MaintainPaths is now marked AggressiveOptimization, a test checks the flag, and experiments/tier0-stack-overflow reproduces the crash. The test tree's one argument constructor now uses the parameterless base constructor, so the library stays fully covered.
On the 4 vCPU CI runner ConcurrentAttachDetachAndContainsStressTest(256) failed at Assert.True(checkedCount > 0): its 6 threads outnumber the cores, so the attachers finished before the reader was scheduled and the reader's while loop never ran. The tree itself was valid. Now the reader marks that it has started and checks at least once, and the attachers wait for that mark before they finish.
# Conflicts: # csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj
…r a block body for Doxygen
# Conflicts: # csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj
…he size balanced property and reject pending nodes
Working session summaryPR #109 is up to date with What changed this round:
Local checks before pushing:
No new comments or reviews have appeared on the PR or on issue #78 since the previous round. No human action is needed for any check, and the PR description still contains This summary was automatically extracted from the AI working session output. |
🔄 Auto-restart-until-mergeable Log 1/5This log file contains the complete execution trace of the AI solution draft process. 💰 Cost estimation:
📊 Context and tokens usage:Claude Opus 5.5: (4 sub-sessions)
Total: (7.4K new + 320.4K cache writes + 12.5M cache reads) input tokens, 127.0K output tokens, $7.635125 cost 🤖 Models used:
📎 Log file uploaded as Gist (15489KB)This AI session has ended. Monitoring of this pull request continues. Feel free to review and add feedback while checks are running. |
✅ Ready to mergeThis pull request is now ready to be merged:
|
Summary
Adds
PartiallyLockFreeSizeBalancedTreeMethods<TElement>, a size balanced tree that is "locked only for balancing", where "each N inserts can be done without any locking or balancing" (#78). Attaches and searches from many threads run without locks, and the tree is balanced once every N attaches (N =balancingThreshold, 1..4096).The PR review asked for three things: a check that concurrent operations survive stress, a survey of published concurrent and lock-free trees with the best fitting design reimplemented, and a record of attempts that fail. All three are in
docs/concurrent-trees.md.Design
Attachis lock-free with respect to other attaches andContains:Sizes are lazy: an attach writes no field of an existing node, so threads never contend on the root.
Balanceruns when the N-th attach finishes, when called explicitly, and before eachDetach:After
BalanceorDetachthe tree is size balanced and every size is exact.Other changes:
AttachandDetachofSizedBinaryTreeMethodsBasebecomevirtual, and the version is bumped to 1.1.0.docs/**/*.mdandexperiments/**/*.mdare now linted by markdownlint in CI.DefaultBalancingThresholdandMaximumBalancingThresholdare static properties.DefaultBalancingThreshold.AtomicElementfallback lock lives in a non-generic class, so all element types share one lock.PaddedCounterand the element structs arerecord structs.Rootby reference, as the other test trees do.Balance(ref root)andContains(node, ref root)suppress S3874 in their own file. Codacy compiles each file alone and does not seeGlobalSuppressions.cs, and the root has to be read and replaced in place under the exclusive gate.check-credits.mjs.AtomicElement,PaddedCounter, the test tree and the tests) is bilingual, English then Russian, in<para>paragraphs, as thecheck-xml-docs.mjscheck from Document every public C# and C++ element in English and Russian, and generate the C++ API documentation #111 requires. TheCS1591suppression in the tree methods is removed. The Doxygen coverage check also passes: the private comparer of pending nodes is documented, and the test tree constructor that callsbase(...)has a block body, because Doxygen could not parse the expression body and moved the next member's docs.main(including Document every public C# and C++ element in English and Russian, and generate the C++ API documentation #111 and Validate sizes, order, balance and threads of all trees like GLib's g_tree_node_check #112) is merged into the branch. The version conflict is resolved as 1.1.0, and the release notes keep the notes frommain.ValidateTree: it checks sizes and order and then the size balanced property. Sizes are exact only after balancing, so it throwsInvalidOperationExceptionwhile attached nodes wait for balancing. TheENABLE_TREE_AUTO_DEBUG_AND_VALIDATIONchecks afterBalanceandDetachnow callValidateTree.Research
The survey covers EFRB, Natarajan–Mittal, Howley–Jones, Ramachandran–Mittal/CASTLE, Bronson et al., logical ordering, LLX/SCX chromatic trees, CA trees, optimistic lock coupling, OCC (a,b)-trees, lock-free augmented trees (Fatourou–Ruppert 2024, CBAT 2026), wait-free augmented trees (Kokorin et al. 2024) and relaxed balancing.
Every lock-free tree that keeps subtree sizes is external and allocates descriptor or version objects. None of them fits this library: its nodes are fixed storage indices with plain numeric fields, and the trees are internal and augmented with sizes. What fits is relaxed balancing (update first, rebalance later) with a CAS-based attach path. A concurrent
Detachwould need a version word per node (optimistic lock coupling), which changes the storage format, so detach stays exclusive. This is listed as future work.Failed attempts (recorded)
bb183b7: plain writes guarded by a counter.experiments/old-partially-lock-free-stressbreaks the tree in 9/10 and 10/10 rounds.b523130: CAS publication with atomic size increments of every ancestor. It is correct, but every thread contends on the root size, and it was slower than alock(0.16 vs 0.41 M inserts/s on 6 threads).2fc5e50: lazy sizes recomputed from both children. Reads scaled, but balancing cost more than the inserts it replaced.Verification
PartiallyLockFreeSizeBalancedTreeTestshas 20 tests:uint,ulongand theushortlock fallback, plus concurrent attach, detach andContainswith thresholds 1/16/256. Threads start behind a barrier, each run has a timeout, and the tree is fully validated afterwards: links, order, sizes, the SBT property and that every node is found.Containsstress test, the attachers wait until the reader has started. A CI run on a runner with fewer cores than threads failedcheckedCount > 0: the attachers finished before the reader thread was first scheduled, so it checked nothing.ValidateTreeRequiresBalancedTreeTest:ValidateTreerejects a tree with pending nodes and accepts it when empty, afterBalanceand after eachDetach.BalancingNeverReadsSizeOfNullNodeTest: storage that throws on reading the size of node 0. Before3a954bbthe balancing of a pending leaf read it.BalancingRecursionIsCompiledOptimizedTest:MaintainPathsis markedAggressiveOptimization. Run alone, the 1 MB stack test crashed the test host with a stack overflow: the first balancing recursed 8192 deep in unoptimized tier 0 code. In the full suite, other tests had already made the JIT optimize the method, which hid the crash.experiments/tier0-stack-overflow/run.shreproduces it.-warnaserrorand coverage collection (131 tests), and the library is 100% line covered (1157 of 1157 lines).node .github/scripts/check-xml-docs.mjspasses for all 76 files, and the Doxygen coverage check passes with Doxygen 1.18.0.-p:TreeValidation=trueit also passes (128 passed, 1 skipped).experiments/mutation-check/run.shremoves each synchronization step in turn. The tests catch all five mutations (result).Benchmarks
experiments/concurrent-tree-benchmark, 1Muintnodes, millions of operations per second. The host is a shared 6-CPU machine, so multi-thread numbers vary by about 20%.lockContains): SBT +lockReaderWriterLockSlimlock.lockon 2+ threads but do not grow with the thread count. Thesplitmode shows why: the serial balancing costs about as much per node as the lock-free descent (1.2–1.4 µs vs 1.1–1.4 µs), so by Amdahl's law inserts can at most double.Limitations
DetachandBalanceare exclusive.PendingBalancingCountreports how many.IsLockFreeis false for 8- and 16-bit elements, which fall back to a lock for the atomic operations.Fixes #78