Repository navigation
Keep size balanced trees within the AVL height bound - #116
Conversation
Restore Chen's size balanced tree algorithm: Maintain after every attach (removing the skip-every-second-attach threshold) and after every detach. The recursionless variant is the same algorithm with explicit stacks, so both build trees of identical shape. Trees built by older versions are rebuilt once with Day-Stout-Warren when an operation passes more nodes than any size balanced tree of that size can have. Refs #115, linksplatform/Data.Doublets#577
Run Maintain after every detach in SizeBalancedTreeMethods and replace the RecursionlessSizeBalancedTreeMethods heuristic with Chen's algorithm using explicit stacks, matching the C# implementation. Add balance tests that check the height bound and the size balanced property. Refs #115, linksplatform/Data.Doublets#577
Replace the weight-balanced repair with a copy of the fixed RecursionlessSizeBalancedTreeMethods from linksplatform/Collections.Methods#116: Maintain runs on every attach and detach, and an index whose path is longer than the AVL height bound (written by an older version) is rebuilt once. The tests now check Chen's size balanced property and the AVL height bound for all index tree types.
Brace single-statement loops and conditions in TreeBalanceTests, fold the vine with a while loop, and return the new root from RebuildComplete instead of taking it by reference.
|
Double check we have original Size Balanced Tree maintain in a recursive mode for recursive tree implementation, double check we have 100% tests coverage, so nothing breaks what was working, and we also check for perfect balance and minimum rotations. RecursionlessSizeBalancedTreeMethods idea was to implement similar algorithm, but with no actual recursion so it should be even cheaper on method calls and so on. So we should have fully recursive and fully recursion less implementation and all of them must be perfectly correct. When we use recursion less implementation we should use knowledge on where we actually going while putting a node in the tree, so we can keep tree balanced/maintained probably with less computational expenses. Double check everything, make sure everything works perfectly in unit tests - they should say it impossible to get way to unbalanced tree, and also in benchmarks, we should make CI/CD in such a way, that we have manual benchmarks execution, yet we also have CI/CD executing unit tests on any pull request and default branch. We also must use all the best fresh best practices from https://github.com/link-foundation/csharp-ai-driven-development-pipeline-template, and prepare our repository for trusted publishing will be the first priority, and all other obsolete methods as a fallback. https://github.com/link-assistant/hive-mind/blob/main/docs/BEST-PRACTICES.md - also use all these. So as this is a critical piece of our infrastructure all our algorithms must be perfectly correct and be as performant as possible, yet as simple as possible. We need to ensure all changes are correct, consistent, validated, tested, documented, logged and fully meet each and all discussed requirements in deepest and widest possible sense (check issue description and all comments in issue and in pull request, make sure each and every requirement listed before actually checking if they were addressed). Nothing should be defered or delayed. The scope is the entire repository, every change in one place should also be applied in all places in the codebase and docs. Ensure all CI/CD checks pass. Please plan and execute everything in this single pull request, you have unlimited time and context, as context auto-compacts and you can continue indefinitely, until each and every requirement fully addressed, and everything is totally done. |
|
🤖 AI Work Session Started Started at 2026-11-29T09:21:56.795Z. Please wait for it to finish before giving feedback. Runtime: solve |
The recursionless size balanced tree remembers which way the attach went at every node, so on the way back up it compares only the grandchild that grew until a rotation changes the children. This gives the same rotations as Chen's Maintain with half of the size comparisons. Rotations are virtual so tests can count them, and the debug validation code compiles and checks the right sizes.
Mirrors the C# change: direction aware attach maintenance, Maintain steps on an explicit stack, size checks that accept empty children, and debug validation that compiles (ValidateSizes, FixSizes and ValidateSize are now available).
Every Maintain call in the recursive tree targets a node on the path of the operation or a child that a rotation has just moved up, so the subtree is never empty. The recursionless maintenance stack now starts with 8 steps and grows on demand.
A duplicate attach or a detach of a missing node threw after the sizes on the search path were already changed, which left the tree invalid. Both the C# and the C++ AVL trees now restore the sizes before throwing.
- Rotations happen exactly when the size balanced properties require them, and the recursive and the recursionless trees rotate identically. - Every order of up to eight nodes keeps the properties. - Failed operations, size validation, printing, neighbours, rebuild and the maximum balanced height are covered for every tree. - Doubly linked lists are checked against a reference model.
Port the rotation, edge case and doubly linked list tests to C++, instrument the test trees to count rotations and size reads, and report the missing node in the detach error message as the C# trees do.
The C# benchmarks use BenchmarkDotNet, the C++ benchmarks use google benchmark. Both attach and detach 1000 and 100000 nodes in ascending, descending and random order. CMake now registers the tests with CTest, requires GTest and benchmark only for the targets that use them, and fetches the Platform.Interfaces headers (cpp_0.3.41) when conan does not provide them.
…ge provides them Add options for sanitizers, gcov coverage and tree self-validation so CI builds every configuration from the same CMakeLists.txt.
…ling a consumer The nuspec now depends on Platform.Interfaces.TemplateLibrary 0.3.41, whose Polymorph.h the headers include. The icon and MSBuild targets come from the last published package (0.3.0).
|
I think inspectable tree must be done as inheritor or decorator, so the default tree implementation must not pay (memory or computation) for inspection. So we can support both features, but when inspection is not needed (we are in production code, not in development/debug or testing), we can just not pay for it. So we should allow to pay only for what we get, and if something is optional we don't force all users to pay for it. |
…equest Detach in ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION mode no longer checks for a missing node itself, so it throws the same exception as without validation (C++ and C#). dotnet test -p:TreeValidation=true defines the symbol for C#. The library builds with -warnaserror (nullable fixes, Source Link 8.0.0) and the package carries the README, the icon and embedded symbols.
…overage cpp/build-and-test.sh builds the tests and runs them through CTest. cpp-test.yml runs it on pull requests and main for GCC, Clang, AppleClang and MSVC, once with AddressSanitizer, UBSan and self-validating trees, and requires 100% line coverage of the headers with gcovr. deploy-cpp.yml publishes only the tested package, with NuGet trusted publishing first and NUGET_TOKEN as a fallback, after a release preflight.
csharp.yml now runs on pull requests and main without the shared linksplatform/Workflows jobs: it tests and packs the library, requires 100% line coverage (check-csharp-coverage.mjs), reruns the tests with -p:TreeValidation=true, builds the docfx site and PDF, and publishes to nuget.org with trusted publishing first and NUGET_TOKEN as a fallback. pipelineStatus fails if any required job failed or was skipped.
Benchmarks are noisy on shared runners, so benchmarks.yml runs only from workflow_dispatch and stores the results in the run summary and artifacts. The test workflows keep the benchmarks compiling.
workflows.yml runs actionlint, zizmor and the workflow policy tests; secrets.yml scans for committed secrets; codeql.yml analyzes Actions, C++ and C# and reviews dependency changes; readme-badges.yml checks that the badges point at existing workflows. Dependabot also updates the actions, with a cooldown, and AutoMerge.yml enables auto-merge with gh instead of the removed @dependabot merge comments. The README documents the balance guarantees, tests, benchmarks and the trusted publishing setup.
|
You are seeing this message because GitHub Code Scanning has recently been set up for this repository, or this pull request contains the workflow file for the Code Scanning tool. What Enabling Code Scanning Means:
For more information about GitHub Code Scanning, check out the documentation. |
LeftRotate and RightRotate are non-virtual again, as on main. The test trees, which inherit from the library trees, now count rotations in the SetLeft and SetRight accessors they implement anyway: a rotation is the only change of links that makes a node the child of its former child. A cross-check run (experiments/detect_rotations_in_setters.py --cross-check) confirmed that the setters detect exactly the rotations the overrides saw. A C# test fails if a rotation becomes virtual, and C++ static_asserts keep the library trees free of virtual functions; the C++ test trees shadow the rotations through CRTP, which resolves them at compile time.
The csharp test job and the C++ pack job failed with "Permission denied" (exit code 126) because six scripts were committed without the executable bit. A workflow policy test now requires it for every tracked shell script. install-local-conan-dependencies.sh gets a shebang and strict mode.
cpp/include-non-header flags the unity builds of the C++ tests and benchmarks, the linksplatform layout. cpp/unused-static-variable misreads a benchmark function template as a variable, because the buildless extraction does not have the fetched Google Benchmark headers.
|
I think inspectable tree must be done as inheritor or decorator, so the default tree implementation must not pay (memory or computation) for inspection. So we can support both features, but when inspection is not needed (we are in production code, not in development/debug or testing), we can just not pay for it. So we should allow to pay only for what we get, and if something is optional we don't force all users to pay for it. Double check #116 (comment) is fully addressed, as well as #115 We need to have perfect possible solution, extensible, configurable and so on. Use all the best https://github.com/link-foundation/code-architecture-principles, and apply it to entire codebase, for all similar algorithms like trees we benchmark relative+absolute performance and also memory usage, and limitations (like maximum possible supported items and so on). We also need to make sure results of benchmarks are clearly visible in our README.md where relevant and applicable, also in all packages we release, so user can see benefits and can compare implementations before selecting which best fits his needs. Double check for maximum perfection of every detail in this repository. We need to ensure all changes are correct, consistent, validated, tested, documented, logged and fully meet each and all discussed requirements in deepest and widest possible sense (check issue description and all comments in issue and in pull request, make sure each and every requirement listed before actually checking if they were addressed). Nothing should be defered or delayed. The scope is the entire repository, every change in one place should also be applied in all places in the codebase and docs. Ensure all CI/CD checks pass. Please plan and execute everything in this single pull request, you have unlimited time and context, as context auto-compacts and you can continue indefinitely, until each and every requirement fully addressed, and everything is totally done. |
|
🤖 AI Work Session Started Started at 2026-11-29T16:04:41.406Z. Please wait for it to finish before giving feedback. Runtime: solve |
…s path buffer The tree methods keep their helpers protected instead of private, so an inheritor can observe them without the plain tree paying anything for it. The C# AVL tree allocated a new path array on every attach and detach; it now reuses one buffer per tree, which TreeAllocationTests proves by measuring zero allocated bytes for every tree.
SizeBalancedTree, RecursionlessSizeBalancedTree and SizedAndThreadedAVLBalancedTree of the tests are now plain storage, as a user of the library would write them. Rotation and size read counting, the rotation log and the inspection helpers live only in the Inspectable* inheritors (C#) and in the InspectableTree CRTP decorator (C++), which the balance, rotation and edge case tests use. Static asserts check that the plain C++ tree is exactly its nodes plus root and count, so nothing is paid for inspection.
…locations The C++ benchmarks are registered under the same group, structure and parameter names as their C# counterparts, so one renderer can compare them, and report the bytes allocated per iteration through a counting global operator new. The same counter backs new TreeAllocationTests, which check that the plain trees allocate nothing per attach and detach once warmed up, as the C# TreeAllocationTests do.
…nd bound the AVL path Byte trees of all three kinds now hold the nodes 1..255 in both languages. The C++ AVL tree keeps its path in a std::array and writes it with at(), so a tree deeper than any AVL tree, which only other code can link, throws std::out_of_range instead of writing past the stack array (GCC warned about that for byte trees). C# already threw IndexOutOfRangeException; tests now prove both. The dead USEARRAYPOOL branches are gone.
The Benchmarks workflow normalizes the BenchmarkDotNet and Google Benchmark JSON into benchmarks/results.json and renders it into README between markers, shows the tables in the run summary and, with commit-results, commits both. The README check workflow tests the renderer and fails when README does not show the committed results. README now compares the structures, describes their memory per node and besides the nodes, and lists their limits.
The C++ package now carries README.md like the C# package, and both package checks fail when README.md lacks the benchmark section. Both descriptions say what README.md compares.
…nd delete GoogleTest sorts the tests with std::stable_sort, which allocates its buffer with the nothrow operator new and frees it with operator delete. The test executable replaced operator delete with free but left the nothrow operator new to the standard library, so the sanitizer job aborted with alloc-dealloc-mismatch before the first test.
…y them The Benchmarks workflow run 46286800162 measured C# and C++ on the same runner. AVL attaches and detaches in 0.4-0.75 of the size balanced tree's time but searches 1.06-2.1 times as long; the recursive size balanced tree is faster than the recursionless one. The guide now follows these numbers instead of preferring the recursionless tree.
Reverts the temporary push trigger of 47bd4ee now that README holds the measured results.
Addresses the CodeQL note about the implicit filter without adding LINQ delegates to the measured loop.
Self-documented names with full words, as code-architecture-principles asks; the parameter is only renamed, so positional callers are unaffected.
The renderer wraps the generated benchmark prose, uses level 3 headings under the section and * bullets, and .markdownlint.json states the line length the README keeps, so Codacy's markdownlint reports nothing.
A mutable struct kept in a readonly field would be copied on every call; the inspectable trees now keep one detector instance.
The benchmark helpers no longer take the root by reference. The library keeps ref roots on purpose: the inheritor owns the storage of the root and the trees update it in place, so SonarC# S3874 is suppressed with that justification.
Inheritors implement the node accessors and may use the rotations, RebuildComplete and GetMaximumBalancedHeight; the Maintain steps and the reused path buffers are implementation details that no inheritor needs, so they are private again in C# and C++. This also removes the 13 SonarC# S3874 issues Codacy reported on the new ref-taking helpers.
dotnet build experiments/sonar reports S3874 and the other SonarC# rules locally, so Codacy findings can be reproduced before pushing.
Working session summaryPR #116 is updated and marked ready for review: #116. All 27 checks pass on the final commit Codacy fixes (59 issues → 0):
Verification:
The PR description still says "Fixes #115". It now has the current test and coverage numbers, the measured benchmark results, the new README sections on memory and limits, the README shipped in both NuGet packages, and a section on the code-architecture changes. The branch is clean, pushed and up to date with One thing left out of scope: the description lists three items not ported from the template repo — the bilingual XML docs check, a clang-format check, and the rust submodule. Each would mean reformatting or translating existing code outside this issue. Since the review comment asked that nothing be deferred, you may want to decide whether that's acceptable. 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: (7 sub-sessions)
Total: (121.9K new + 676.1K cache writes + 23.2M cache reads) input tokens, 262.1K output tokens, $15.736449 cost 🤖 Models used:
📎 Log file uploaded as Gist (12621KB)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:
|
Fixes #115
Summary
All four size balanced trees now keep Chen's size balanced property after every attach and every detach: C# and C++, recursive and recursionless. Such a tree can never be taller than an AVL tree with the same number of nodes. Balancing still uses only the subtree sizes; no field is added to the nodes.
Maintainon every attach and every detach.main. Benchmarks run on request, and CI follows the current linksplatform and hive-mind practices.Found in linksplatform/Data.Doublets#577: the source index of the united links store had grown to 1,992 levels for 4,097 links, where the bound is 16.
What a size balanced tree must guarantee
Chen (2007): for every node
tThe smallest tree of height
hthat keeps this property hasm(h) = m(h-1) + m(h-2) + 1nodes, exactly like the smallest AVL tree:So 7 nodes may need 4 levels but never 5, 4,097 nodes never more than 16 levels, 8,192 nodes never more than 18. The new tests check exactly this bound (
GetMaximumBalancedHeight) and the property itself after every operation.Chen's
Maintain(t, leftMayBeHeavy)restores the property after a single attach or detach. After each rotation it repairs, in this order, the left child, the right child, and thentin both directions (Maintain(left, false); Maintain(right, true); Maintain(t, true); Maintain(t, false)). Each call is amortised O(1), so attach and detach stay O(log n).What was wrong
SizeBalancedTreeMethodsattachCount/maintainThreashold(added for #103) skipsMaintainon every second attach.DetachCorenever runsMaintain.RecursionlessSizeBalancedTreeMethodsSizeBalancedTreeMethodsLeftthenRightinstead of Chen's).DetachCorenever runsMaintain.RecursionlessSizeBalancedTreeMethodsExample 1: the skipped
Maintain(C# recursive tree)In Data.Doublets every new link is attached to two indexes. When many links share one source, their keys are adjacent ("hot") and are attached alternately with unrelated ("cold") keys. With the threshold,
Maintainruns only on every second attach, so every hot attach lands on the turn withoutMaintain. Keys1, 5, 2, 6, 3, 7, 4, 8(hot1..4, cold5..8):(Drawn by
experiments/sbt-heal/sbt_model.py, a model of the C# code; the C# experimentHotColdHeights.csmeasures the same heights on the real classes.)With 2,048 hot and 2,048 cold keys the old C# tree has height 2,049 — the hot half is a plain linked list — while Chen's tree has height 13 (bound 16). This is the shape Data.Doublets#577 found in real data.
Example 2: detach without
Maintain(C++ recursive tree)Attach
1..4096(a perfectly fine tree) and then detach every node except those on the path from the root to key 1. WithoutMaintainon detach nothing shortens that path: the old tree is left with 12 nodes and height 12 (bound 5). With this PR it has height 4, the same as the AVL tree.Example 3: the one-pass heuristic (recursionless trees)
The same hot/cold workload gives the old C# recursionless tree height 17 for 4,096 nodes (bound 16) and the old C++ recursionless tree height 19 for 8,192 nodes (bound 18). Detaching
1..4032of1..4096leaves the old C++ recursionless tree with 64 nodes and height 8, at the bound, where the AVL tree has 7. With this PR the recursionless trees build exactly the same shapes as the recursive ones (14 and 7).Measured with the experiment programs in linksplatform/Data.Doublets#592 (
experiments/sbt-heal):The fix
Shared base,
SizedBinaryTreeMethodsBase(C# and C++)GetMaximumBalancedHeight(size)returns the height bound from the table above.RebuildComplete(root)is Day–Stout–Warren: it rotates the subtree into a vine and folds the vine into a complete tree. It takes O(n) time and O(1) memory, and the rotations keep the sizes correct. A complete tree is size balanced.Recursive tree,
SizeBalancedTreeMethods(C# and C++)Maintainon every level of the path.Recursionless tree,
RecursionlessSizeBalancedTreeMethods(C# and C++)It is the same algorithm with an explicit path of steps (parent and side, so a step stays valid when a rotation replaces the node) and a small
Maintainstack.MaintainAttachPathuses the direction an attach took. Before the attach the tree was balanced, and the attach enlarged only the grandchild on the path. So until a rotation changes the children,Maintaincan only rotate because of that grandchild, and the tree compares only its size.After a rotation,
MaintainRotatedruns the fourMaintaincalls of the paper from the stack, in the paper's order. The result:RecursiveAndRecursionlessTreesMakeTheSameRotations);RecursionlessAttachReadsFewerSizes);Trees stored by older versions
Trees in memory-mapped files (Data.Doublets) may already be degenerate, and
Maintainonly repairs the path of the current operation. So both trees count the levels an attach or detach passes. When that count exceedsGetMaximumBalancedHeight(size), the tree cannot have been built by this algorithm, and it is rebuilt once withRebuildComplete. A tree built by this code never triggers the rebuild, because the bound is a theorem.Paying only for what you use
Requested in #116 (comment).
GetSize, and rotations inSetLeftandSetRight, accessors every tree implements anyway. A rotation is the only change of links that puts a node below its former child.LeftRotateandRightRotatestay non-virtual, as onmain.RotationsAreNotVirtualguards that.static_assert(!std::is_polymorphic_v<...>)keeps the library trees free of vtables.ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION) is compile-time only. Its exceptions are kept, and C# can be built with it through-p:TreeValidation=true.Tests
check-csharp-coverage.mjs)--fail-under-line 100)-p:TreeValidation=truejoblinux-gcc-sanitizers-validationjob (ASan + UBSan, Debug)The tests cover:
Before this PR, 16 of 24 C# balance tests and 10 of 20 C++ balance tests failed.
Benchmarks, memory and limits
Requested in #116 (comment). Every tree and every list is benchmarked in C# (BenchmarkDotNet) and C++ (Google Benchmark), on the same storages as the tests:
TreeBenchmarks: attach and detach of N = 1,000 and 100,000 nodes, in ascending, descending and random order.TreeSearchBenchmarks: search of every node.ListBenchmarks: attach and detach in all four doubly linked lists.StorageBenchmarks: the memory of the storage of N nodes.Each table shows the mean time, the ratio to the first structure, and the allocated bytes.
render-benchmarks.mjsnormalizes both outputs intobenchmarks/results.jsonand renders it into README.md between markers.--checkfails CI when the README and the JSON differ. README.md is the readme of both NuGet packages:PackageReadmeFilefor C# and<readme>in the nuspec for C++. Package validation checks that the README is in each package.README.md now also has:
bytetrees with all 255 nodes and bound the AVL path.Measured results (Benchmarks run 46286800162, committed into README.md):
uintnode, the SBT 12 B.Openlists take about 0.8× the time of theCircularones.The benchmarks run on request (Actions → Benchmarks → Run workflow). With
commit-resultsthe workflow commits new results to README.md andbenchmarks/results.json.Architecture
Applied https://github.com/link-foundation/code-architecture-principles across the codebase:
Inspectable*inheritors. The plain trees are what the benchmarks measure.InspectableTreeis a CRTP mixin.RebuildCompleteandGetMaximumBalancedHeight. TheMaintainsteps and the reused path buffers stay private in C# and C++. Rotations stay non-virtual.Maintainstack.operator new/deleteform. This includes thenothrowforms GoogleTest uses, which the AddressSanitizer job needs to see matchingnewanddelete.sbis renamed tostringBuilder.RotationDetectoris a class, so its state is never copied.ref.Attach(ref root, node)andDetach(ref root, node): the inheritor owns the storage of the root, and the trees update it in place.GlobalSuppressions.csdocuments this for SonarC# S3874.experiments/sonarruns SonarC# locally, as Codacy does.benchmarks/results.json. The README is generated from it and checked against it.CI/CD
csharp.ymlmain-warnaserror, tests, 100% coverage gate, TreeValidation tests, NuGet package validation, docfx API site and PDF of the code. Onmainalso: release preflight, trusted-publishing push, GitHub release, docs.cpp-test.ymlmaindeploy-cpp.ymlmain(nuspec version bump)benchmarks.ymlworkflow_dispatch)commit-resultscommitted into README.mdcodeql.ymlmain, weeklyworkflows.ymlmainsecrets.yml,readme-badges.yml,AutoMerge.ymlmainrender-benchmarks.mjs readme --check; Dependabot auto-mergeThe practices follow csharp-ai-driven-development-pipeline-template, hive-mind BEST-PRACTICES.md and CI-CD-BEST-PRACTICES.md, and linksplatform/Interfaces:
persist-credentials: false, least-privilegepermissions,timeout-minuteson every job.concurrencynever cancels runs onmain.tj-actions/changed-files, which was compromised, is replaced bygit diff. This closes the two open Dependabot alerts.node --test .github/scripts/*.test.mjs).Trusted publishing comes first.
NuGet/login(OIDC) needs nuget.org policies forcsharp.ymlanddeploy-cpp.ymland the repository variableNUGET_USER. Without them the workflows fall back to theNUGET_TOKENAPI key, and a preflight explains what is missing. The steps are in the README, under "Releasing".Not ported
Each of these would mean reformatting or translating the whole existing codebase, outside this issue.
CodeQL:
.github/codeql/codeql-config.ymlexcludes onlycpp/include-non-headerandcpp/unused-static-variable:Codacy: the pull request adds no new issue (SonarC#, cppcheck, markdownlint, pydocstyle).
.markdownlint.jsonsets the 80-column line length that the README and the generated benchmark section follow.Documentation: DocFX builds the README as the home page with
--warningsAsErrors.validate-csharp-docs.shchecks on every pull request that the namespace and tree pages and the API documentation PDF exist, and that the README links them.Release
VersionPrefix0.8.0.NUGET_TOKEN).