Skip to content

Add PackageRefSet and SplitRefSet for reflist merging & subtraction - #1617

Draft
refi64 wants to merge 1 commit into
aptly-dev:masterfrom
refi64:wip/refi64/refsets
Draft

refi64 wants to merge 1 commit into
aptly-dev:masterfrom
refi64:wip/refi64/refsets

Conversation

@refi64

@refi64 refi64 commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Reflist merging uses a simple, linear algorithm, where both reflists are walked in tandem top-to-bottom, placing the lesser reference on the resulting list at each step and removing duplicates. Although this works well for short reflists, it scales poorly when merging many reflists, because the leftmost list is effectively re-scanned every run. This is quadratic time and causes a great deal of memory churn from all the allocations.

A more efficient mechanism appears if we step back and consider the use cases of merging:

  • For package publishing cleanup and database cleanup: we’re just trying to merge a large number of lists where refs that are 100% identical (arch, name, version, and hash) are deduplicated. Performance for large numbers of lists here is important, since it will iterate over every published reflist (for publishing cleanup) or every single reflist in the database (for database cleanup).
  • When merging snapshots, or creating them via API from multiple sources, and neither -latest nor -no-remove (or API equivalents) are set, overrideMatching=true and ignoreDuplicates=false. In this scenario, in addition to the above deduplication, linear runs of references with a given architecture and name in a later list will override refs in former lists that had the same architecture/name.
  • When merging snapshots with -no-remove, identical deduplication as in the first case is still performed, but we also want refs that are identical in all but hash (ignoreDuplicates=false) to be overridden by the refs in later lists.
    • This is also used when merging with -latest, since all versions need to be retained in order to identify the latest one via proper version comparisons.

All three of these are actually quite similar; the most significant thing that changes is the “key” used for uniqueness. In the latter two cases, in addition to deduplicating based on the full key, we deduplicate based on “key - {version, hash}” or “key - hash”, respectively.

Thus, with these observations, we can create a different approach to merging, the “RefSet”, that uses maps. Instead of creating a new reflist for every merge, a single map is created to track the “keys” (derived from the ref using a configured identity) whose corresponding ref(s) have already been added to a currently-unsorted slice of all refs. As new lists get added, any refs sharing the same key as runs of refs from prior lists are ignored. Then, at the very end, we sort the resulting refs and place them in a reflist. Although the current reflist merging is last-run-wins, the callers can just add the input lists in reverse order to compensate.

This brings several advantages:

  • Every reflist added requires iteration relative to the number of refs in only the new reflist, rather than the new one and the old one.
  • Subtracting refsets from reflists is rather cheap, since we just perform a map lookup for each ref in the source list.
  • For split reflists, we can:
    • Completely skip buckets whose digest has already been seen.
    • Defer bucket digest calculations until the very end, which cuts down on redundant sha256 operations.

The resulting trade-off is that the initial overhead can be higher, in particular when you have higher numbers of duplicates and a small number of lists. In the newly-added benchmarks, at the highest duplicate frequency, refsets start out 10x slower (though with only 2 lists, the total time is still ~1.6ms), but by 32 lists, they’re a bit better at runtime, and nearly 6x better in memory allocated. At 512 lists, refsets are nearly 4x faster (~87ms -> ~22ms) and allocate over 96x(!) less memory.

That is their worst performance in the benchmark. Fewer duplicate counts perform even better, and WithoutHash/WithoutVersion top out at over 260x faster (~1.1s -> ~4.2ms) and nearly 550x less memory usage. With split reflists, the general trend is similar; they start off around 7x slower but end up 26x faster at 512 lists, and the best improvement in WithoutHash/WithoutVersion is 82x faster.

In our own database, with ~69k published snapshots, this cuts the publish time from ~33min -> ~3min. I couldn’t even wait long enough for a full db cleanup on >200k reflists to finish, but it had made it barely 10% through loading the reflists in over 90 minutes(!). With refsets, the full process finished in under 3 minutes.

In addition to all of this, the new implementation does fix some bugs in the previous one, where certain edge cases when overrideMatching=true would result in refs from an older list being preserved. This can be seen in the first check of the new TestMergingEdgeCases, where the previous implementation would fail because abc 7 would be preserved in the final list.

@codecov

codecov Bot commented Aug 8, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.44444% with 8 lines in your changes missing coverage. Please review.
✅ Project coverage is 77.74%. Comparing base (c66ea12) to head (7d3fcf9).

Files with missing lines Patch % Lines
api/db.go 42.85% 4 Missing ⚠️
api/snapshot.go 87.50% 1 Missing and 1 partial ⚠️
deb/refset.go 97.70% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1617      +/-   ##
==========================================
- Coverage   78.00%   77.74%   -0.27%     
==========================================
  Files         165      166       +1     
  Lines       16670    16712      +42     
==========================================
- Hits        13004    12993      -11     
- Misses       2418     2474      +56     
+ Partials     1248     1245       -3     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@neolynx neolynx self-assigned this Sep 15, 2026
@neolynx
neolynx requested a review from a team September 15, 2026 09:09
@neolynx neolynx added the needs review Ready for review & merge label Sep 15, 2026
@neolynx
neolynx force-pushed the wip/refi64/refsets branch from a6fecd2 to 1c556c2 Compare November 5, 2026 12:19
@neolynx

neolynx commented Nov 5, 2026

Copy link
Copy Markdown
Member

rebased on master

@neolynx
neolynx force-pushed the wip/refi64/refsets branch from 42dfbff to e0cc741 Compare November 5, 2026 12:57
@neolynx
neolynx force-pushed the wip/refi64/refsets branch 2 times, most recently from 341890f to 8fb51dd Compare November 28, 2026 13:27
@neolynx
neolynx marked this pull request as ready for review November 28, 2026 13:53
@refi64

refi64 commented Nov 28, 2026

Copy link
Copy Markdown
Contributor Author

Sorry but converting this to draft for a short bit, recently I realized there's a useful simplification where the entire "keep only last reference" mechanism can probably be replaced by just, uhh, giving the input reflists in reverse order, which cuts the line count and complexity down a fair bit.

@refi64
refi64 marked this pull request as draft November 28, 2026 14:41
@neolynx

neolynx commented Nov 28, 2026

Copy link
Copy Markdown
Member

oh, sorry, it mentioned draf bcs depending on 1606...

fixed rebase changes (pushed to your branch), it should build now again :)

Reflist merging uses a simple, linear algorithm, where both reflists are
walked in tandem top-to-bottom, placing the lesser reference on the
resulting list at each step and removing duplicates. Although this works
well for short reflists, it scales poorly when merging *many* reflists,
because the leftmost list is effectively re-scanned every run. This is
quadratic time and causes a great deal of memory churn from all the
allocations.

A more efficient mechanism appears if we step back and consider the use
cases of merging:

- For package publishing cleanup and database cleanup: we're just trying
  to merge a large number of lists where refs that are 100% identical
  (arch, name, version, and hash) are deduplicated. Performance for
  large numbers of lists here is important, since it will iterate over
  *every* published reflist (for publishing cleanup) or *every single
  reflist in the database* (for database cleanup).
- When merging snapshots, or creating them via API from multiple
  sources, and neither `-latest` nor `-no-remove` (or API equivalents)
  are set, `overrideMatching=true` and `ignoreDuplicates=false`. In this
  scenario, in addition to the above deduplication, linear runs of
  references with a given architecture and name in a later list will
  override refs in former lists that had the same architecture/name.
- When merging snapshots with `-no-remove`, identical deduplication as
  in the first case is still performed, but we also want refs that are
  identical in all but hash (`ignoreDuplicates=false`) to be overridden
  by the refs in later lists.
  - This is also used when merging with `-latest`, since all versions
    need to be retained in order to identify the latest one via proper
    version comparisons.

All three of these are actually quite similar; the most significant
thing that changes is *the "key" used for uniqueness*. In the latter two
cases, in addition to deduplicating based on the full key, we
deduplicate based on "key - {version, hash}" or "key - hash",
respectively.

Thus, with these observations, we can create a different approach to
merging, the "RefSet", that uses *maps*. Instead of creating a new
reflist for every merge, a single map is created to track the
"keys" (derived from the ref using a configured identity) whose
corresponding ref(s) have already been added to a currently-unsorted
slice of all refs. As new lists get added, any refs sharing the same key
as runs of refs from prior lists are ignored. Then, at the very end, we
sort the resulting refs and place them in a reflist. Although the
current reflist merging is last-run-wins, the callers can just add the
input lists in reverse order to compensate.

This brings several advantages:

- Every reflist added requires iteration relative to the number of refs
  in *only* the new reflist, rather than the new one *and* the old one.
- Subtracting refsets from reflists is rather cheap, since we just
  perform a map lookup for each ref in the source list.
- For split reflists, we can:
  - Completely skip buckets whose digest has already been seen.
  - Defer bucket digest calculations until the very end, which cuts down
    on redundant sha256 operations.

The resulting trade-off is that the initial overhead can be higher, in
particular when you have higher numbers of duplicates and a small number
of lists. In the newly-added benchmarks, at the highest duplicate
frequency, refsets start out 10x slower (though with only 2 lists, the
total time is still ~1.6ms), but by 32 lists, they're a bit better at
runtime, and nearly 6x better in memory allocated. At 512 lists, refsets
are nearly 4x faster (~87ms -> ~22ms) and allocate over 96x(!) less
memory.

That is their *worst* performance in the benchmark. Fewer duplicate
counts perform even better, and WithoutHash/WithoutVersion top out at
over 260x faster (~1.1s -> ~4.2ms) and nearly 550x less memory usage.
With split reflists, the general trend is similar; they start off around
7x slower but end up 26x faster at 512 lists, and the best improvement
in WithoutHash/WithoutVersion is 82x faster.

In our own database, with ~69k published snapshots, this cuts the
publish time from ~33min -> ~3min. I couldn't even wait long enough for
a full `db cleanup` on >200k reflists to finish, but it had made it
barely 10% through loading the reflists in over 90 minutes(!). With
refsets, the full process finished in under 3 minutes.

In addition to all of this, the new implementation does *fix* some bugs
in the previous one, where certain edge cases when overrideMatching=true
would result in refs from an older list being preserved. This can be
seen in the first check of the new TestMergingEdgeCases, where the
previous implementation would *fail* because `abc 7` would be preserved
in the final list.
@refi64
refi64 force-pushed the wip/refi64/refsets branch from ec92b61 to 7d3fcf9 Compare December 3, 2026 23:30
@refi64

refi64 commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Okay, updated now! I was indeed able to gut the entire weird "tracking run of refs" thing in favor of just adding reflists in reverse, which cut down the complexity by a bit. Also hardened the tests and fixed some small issues found along the way, plus updating the benchmark numbers.

oh, sorry, it mentioned draf bcs depending on 1606...

Yeah that's my bad, I was too lazy to post an update here since I figured the odds of split reflists merging during the exact week I was working on this again weren't high 😅 evidently I should not take up gambling.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs review Ready for review & merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants