Skip to content

Implementation of different decoupling approaches - #26

Draft
WoWaster wants to merge 44 commits into
wowaster/mass-refactorfrom
wowaster/design-tries
Draft

WoWaster wants to merge 44 commits into
wowaster/mass-refactorfrom
wowaster/design-tries

Conversation

@WoWaster

Copy link
Copy Markdown
Member

Claude and I implemented three approaches to decoupling algorithms from concrete matrix representations in a functional style. Please mind that decoupling is purely mechanic and is made with a simple prompt, I know that we very probably don't want to decouple semiring operations from algorithms, only matrix operations.

This PR is MVP and probably will be closed in some time.

Please take a look and decide on approach. IMO approach A2 look the best as it is requires only one argument (unlike A1), but can support matrix representation with poor interface (unlike A3).

The HashSet cases measured the wrong operation after the first invocation. HashSet.UnionWith, IntersectWith and ExceptWith mutate the receiver in place, while AVLSet and F# Set are persistent and return a new set. BenchmarkDotNet runs GlobalSetup once per benchmark case but invokes the benchmark method many times, so by the second iteration:

- UnionWith had nothing left to insert, because HashSetA already contained B;
- IntersectWith had already shrunk HashSetA to A ∩ B;
- ExceptWith had already removed every element of B from HashSetA.

The reported timings therefore reflected near no-op or much cheaper operations on an already-mutated set, and were not comparable with the immutable implementations, which always perform the full operation.

Clone HashSetA before each mutating operation and return the copy, so every invocation starts from the same input. The clone cost is included in the measurement, matching the allocation that AVLSet and F# Set perform to produce a persistent result.

Remove HashSetBenchmark: its Union, Intersection and Difference cases duplicate the HashSet cases in FSSetsBenchmark. Once those cases clone correctly, the separate class only doubles benchmark runtime without adding information.

Also remove the unused threads parameter, which belonged to the deleted parallel benchmark, and the ThreadingDiagnoser attribute, since no benchmark performs parallel work anymore.
At leaf level update called op to compute the stored value and again to
derive deltaNNZ, keeping only the second result for the tree. Call it
once and use that result for both, so an impure or expensive op cannot
produce a value that disagrees with the recorded change in nvals.
Vector.init re-checked pointer >= length inside the size = 1 branch,
which the preceding guard already excluded, so that arm could not be
taken.

Boruvka's mst.inner threaded an iteration counter that was incremented
on every recursive call but never read, and fixPoint carried a similar
counter plus a redundant res binding. Remove both.
WoWaster and others added 14 commits November 10, 2026 21:56
Matrix.toCoordinateList joined the four recursive results with list
append, Vector.toCoordinateList appended its leaf block to the running
accumulator, and mergeSort.extract joined the two subtrees the same
way. Each append re-walks a prefix that was already accumulated, making
the walks quadratic in the number of nodes rather than in the number of
values.

Thread the accumulator through the traversal instead and reverse once
at the end, which keeps the original left-to-right order. The order
matters because toCoordinateList output is consumed by
fromCoordinateList, where duplicate coordinates resolve as "last wins".

Vector.foldValues built List.replicate (int size) v only to fold over
it, allocating a list whose length is the leaf's size and narrowing a
uint64 to int. Fold a counter instead so the leaf costs no allocation.
Record replacing the hand-rolled tuple-of-Result matching in the
recursive kernels with the and! operator that Result.MergeSources
already provides, in Matrix.map2, vxm, vxmi_values and mxm, and decide
the fate of the unused Result.For/Result.While members.
Both functions carried an identical increaseStorage closure to grow the
vector's storage tree to the matrix storage size, and both ended with
the same SparseVector construction for the result.

Extract padStorageTo and mkResultVector so each call site is two lines.
map2i repeated the same offset computation and four-way recursion in
three arms, differing only in which operand was a node and which a
leaf, and mapi repeated it in two more. The leaf result and its nvals
were also spelled out three times.

Add quadrants, which returns a node's four subtrees or repeats a leaf
four times, so the node and leaf cases share one recursion path, and
rebuildQuadrants, which computes the offsets, recurses through a visit
callback and rebuilds the node. mkLeafResult holds the value/nvals
pairing shared by all leaf arms.
bfs_level and bfs_parent were the last snake_case public functions in
the library; every other binding uses camelCase.

Rename them to bfsLevel and bfsParent and update the test and benchmark
call sites.
The module's only public function was the last snake_case binding in
the Graph project.
Both Vector.Error and Matrix.Error rendered the message as "Must be not
greater then", which is both ungrammatical and misspelled. It now reads
"Must not be greater than".
mkNode forces the visited subtrees to be qtrees, so the 'result type
parameter in the visit callback was always constrained to qtree<'value>.
FS0064 reported the mismatch on a clean build.
The "Double check this code" comment left the quadrant product mapping
unstated. The eight sub-products are assembled as the standard quadtree
product:

  C_nw = A_nw*B_nw + A_ne*B_sw    C_ne = A_nw*B_ne + A_ne*B_se
  C_sw = A_sw*B_nw + A_se*B_sw    C_se = A_sw*B_ne + A_se*B_se

This matches rnw/rne/rsw/rse, and the Simple/Sparse/Shrinking/Expanding
mxm tests cover it, including the shrink path.
Rename the remaining snake_case locals to camelCase: new_size (now
halfSize, matching the same quantity in getQuadrantCoords and
rebuildQuadrants), data_length, vector_storage, m1_tree/m2_tree,
new_t1..4, the six quadrant new/removed pairs, nvals_removed,
parent_i/parent_j, p_i/p_j, new_frontier, iter_num,
data_for_update_parent and initial_parent_update.

Also rename the underscore-prefixed helpers: _do becomes combine in
Matrix.map2, vxm and vxmi_values, and _max/_min become op_max/op_min in
Maggs_Plotkin_MST so they follow the semiring naming convention.

The mxm quadrant product names (nw1_x_nw2, tnw1_x_nw2, ...) keep their
underscores: the _x_ marks the operand pair and camelCasing them would
obscure the algebra.
It was the only module name using underscores. Rename the module and its
file to MaggsPlotkinMST, keeping the compile position in Graph.fsproj
unchanged since Boruvka must still precede it.
Tick the consistency/dead-code TODO item and update the resultM entry to
the renamed combine closures.

Document in AGENTS.md the conventions the cleanup settled on: camelCase
bindings with the op_* semiring parameters and mxm _x_ product names as
deliberate exceptions, per-module Error unions that wrap inner ones, and
the ToString() override that keeps user-facing error messages readable.
Add one runnable project per approach from docs/decoupling-proposals.md:
- Decoupling.A1: small records per capability (plus section 7 bundles)
- Decoupling.A2: one record per algorithm
- Decoupling.A3: one combined record

Each implements BFS, SSSP and TriangleCount against records of
functions, provides quad-tree instances and Graph-shaped entry points,
and has a Program.fs with usage examples. Decoupling.Common holds
shared sample graphs and printing helpers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add Decoupling.Benchmark with BFS, SSSP and TriangleCount benchmarks
comparing Graph.* (baseline) with the A1, A1 bundled, A2 and A3
quad-tree entry points on the matrices used by Graph.Benchmark.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@WoWaster
WoWaster force-pushed the wowaster/mass-refactor branch from 1d38155 to 1959e34 Compare November 13, 2026 18:05
@gsvgit
gsvgit force-pushed the wowaster/mass-refactor branch from 1959e34 to 48cca6b Compare November 16, 2026 09:49
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