Skip to content

perf(cleanup): list managed subtrees concurrently - #11596

Merged
Xuanwo merged 1 commit into
lance-format:mainfrom
lichuang:perf-cleanup-listing-2
Nov 30, 2026
Merged

Xuanwo merged 1 commit into
lance-format:mainfrom
lichuang:perf-cleanup-listing-2

Conversation

@lichuang

Copy link
Copy Markdown
Contributor

Summary

Cleanup lists seven managed subtrees: _versions/, _transactions/, data/,
_blobs/, _indices/, _deletions/ and _fri/. It listed them serially —
stream::iter(streams).flatten() drains _versions/ before starting
_transactions/, and so on.

On object storage every listing is a round trip, so a cleanup paid the sum of
those latencies instead of their maximum. This PR polls them together and drops
a per-object allocation from the same pipeline.

Changes

1. Poll the subtree listings concurrently

rust/lance/src/dataset/cleanup.rs:

// before
let unreferenced_files = stream::iter(streams).flatten().boxed();

// after
let unreferenced_files = stream::select_all(streams).boxed();

Cleanup does not care which subtree a candidate came from until it classifies
the file, so nothing needs the subtrees ordered against each other.

select_all was chosen over flatten_unordered because it polls the inner
streams in place: no task spawn, no per-child buffer. A previous local
experiment with flatten_unordered on this pipeline was slower than the serial
version on small inputs, which is why the lighter primitive is used here.

2. Remove the per-object boxing

// before: one Box::pin per listed object, then try_flatten unpacks it
.map_ok(|obj| stream::once(future::ready(Ok(obj))).boxed())
.or_else(|e| { /* missing subtree -> empty inner stream */ })
.try_flatten()

// after: a plain map over the listing
.map(|result| match result {
    Ok(obj_meta) => Ok(Some(obj_meta)),
    Err(error) if error.is_not_found() => Ok(None),
    Err(error) => Err(error),
})
.try_filter_map(move |obj_meta| async move { ... })

A subtree that does not exist used to be reported as an empty inner stream,
which forced the or_else to reconstruct the stream type. It is now a single
None item that the try_filter_map drops, so the ordinary path stays a plain
map and a table with millions of files no longer allocates once per object
just to represent it.

Measurements

Why a new scenario was needed

A local filesystem has no listing latency, so serial and concurrent listing
cost the same there. The existing cleanup benchmark therefore cannot show
this change: it reported only a 5.5% gain on versions, which comes from the
allocation removal, not the concurrency.

This PR adds cleanup_listing_latency to rust/lance/benches/cleanup.rs. It
builds the versions shape against a SlowListWrapper that charges a fixed
delay for every list, list_with_offset and list_with_delimiter. The delay
is paid once per listing stream, before the first item, so it models a request
round trip rather than per-object cost.

Configuration, following the file's existing CLEANUP_BENCH_* convention:

  • CLEANUP_BENCH_LIST_DELAY_MS: one delay in milliseconds; runs 10, 50 and 100
    when unset.
  • CLEANUP_BENCH_LATENCY_VERSIONS: dataset versions (default 20).

Results

20 versions, 19 expired, 10 samples per cell:

injected delay this branch main speedup
10 ms 81.7 ms 167.5 ms 2.05x
50 ms 324.8 ms 656.8 ms 2.02x
100 ms 638.5 ms 1273.4 ms 1.99x

Fitting the three points to k * delay + c:

main this branch
k (serial listings) 12.33 6.11
c (fixed cost) 40.3 ms 27.0 ms

k is the number of listing round trips a cleanup serializes. It roughly
halves, and does not reach one because some listing remains order-dependent and
outside this pipeline — local_staging_roots, _refs and the MemWAL
directories are enumerated separately. Parallelizing those is separate work: I
would want to know which of those stages are safe to reorder before touching
them.

Existing scenarios

cargo bench -p lance --bench cleanup at 500 orphans / 50 versions:

case main this branch change
orphans/500 22.605 ms 23.008 ms +5.3% (p = 0.16)
versions/50 8.459 ms 7.726 ms −5.5% (p = 0.01)

versions/50 improves and is significant. orphans/500 is within noise, which
is expected: that case is dominated by the delete path, which this PR does not
touch.

Correctness

cargo test -p lance --lib dataset::cleanup::        # 320 passed

Every run in the delay experiment reports the same statistics on both sides:

old_versions=19 data_files_removed=19 transaction_files_removed=19

So the change affects listing concurrency only, not what cleanup decides to
remove.

Not included

  • The remaining order-dependent listing stages, as above.
  • Any change to the delete path. orphans is unaffected by design; the
    bulk-delete statistics (delete_requests / delete_paths) are unchanged.

Review note

The new scenario sleeps for its configured delay per listing, so it takes tens
of seconds at the default 10 samples and three delays. It is a Criterion
scenario rather than a separate harness so the numbers carry confidence
intervals and reuse the fixtures already in this file; reviewers who would
rather not grow this benchmark can run it alone with
CLEANUP_BENCH_LIST_DELAY_MS=50 and CLEANUP_BENCH_SKIP_ORPHANS=1 CLEANUP_BENCH_SKIP_VERSIONS=1.

Cleanup listed its managed subtrees serially: `stream::iter(streams).flatten()`
drained `_versions/` before starting `_transactions/`, then `data/`, `_blobs/`,
`_indices/`, `_deletions/` and `_fri/`. On object storage each listing is a
round trip, so a cleanup paid their sum rather than their maximum.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude Code Review

This pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Gate recommendation: approve.

Cleanup can overlap its independent subtree listings while retaining the completed reference snapshot and existing deletion safeguards. Local cleanup regression tests and a delayed-stream experiment support the change.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Nov 28, 2026
@Xuanwo
Xuanwo merged commit 685ecd6 into lance-format:main Nov 30, 2026
42 checks passed
Xuanwo added a commit to lichuang/lance that referenced this pull request Dec 2, 2026
Merge main to use the cleanup implementation and benchmark from lance-format#11596. Keep the overlap regression from lance-format#11167, observing only the data and transaction listings in the sweep.

Co-authored-by: codedump <[email protected]>
Xuanwo added a commit that referenced this pull request Dec 2, 2026
The concurrent listing implementation and latency benchmark landed in
#11596. This PR retains the regression test from the original
contribution. It calls `cleanup().explain()` and checks that the `data/`
and `_transactions/` listings both await their first response at the
same time. With serial listing, the same test fails at the overlap
assertion.

<details>
<summary>Original implementation and measurements before #11596
landed</summary>

## Summary

Cleanup listed its managed directories through a serial `flatten()`, so
a large
`data/` listing delayed `_indices/`, `_deletions/`, `_blobs/`,
`_transactions/`, `_versions/`, and `_fri/` even though they are
independent.
Each subtree is a single paginated LIST, so those round trips were paid
one
after another.

This PR overlaps them with `flatten_unordered`, and builds each subtree
stream
directly from `read_dir_all` instead of wrapping every listed object in
its own
boxed stream.

## About the numbers in the previous revision

The earlier description was measured on my MacBook Pro. That machine is
not a
controlled environment — desktop session, uneven thermal throttling,
varying
background load — and its run-to-run spread was on the order of the
effect
being claimed. That is very likely why serial `flatten()` after
de-boxing
looked ~10% *slower* than before, which should be impossible from
removing an
allocation.

Everything below has been re-measured on a clean Linux machine (32
cores,
59 GB, no desktop session, nothing else running) with the variants
interleaved
so drift and page-cache state hit all of them equally. **The absolute
times are
much lower here because the machine is faster, not because the code
changed.**
Only differences within a single machine are meaningful, so the old and
new
tables are not comparable with each other and should not be mixed.

## Corrected claim about allocations

The previous description credited the per-object de-boxing with a
speed-up.
That does not hold up, and the review was right to question it:

- De-boxing removes about one allocation per listed object, but
`flatten_unordered` re-inserts its next-item future into its scheduler
after
every emitted item, adding roughly the same number back. Over 700k items
the
  allocation count is **700,007 both before and after**.
- Measured on its own, de-boxing while keeping the serial merge is
  indistinguishable from the previous code.

The de-boxing is kept because it is a simplification that disappears in
the
noise, not because it pays. The gain in this PR is entirely from
overlapping
the listings.

## Benchmark

Same harness as #10511, one machine, variants interleaved (A/B/C
adjacent).

- `release-with-debug`, sample size 20, warm-up 5s, measurement 15s
- local `file-object-store`
- `CLEANUP_BENCH_ORPHANS=2000`, `CLEANUP_BENCH_VERSIONS=200`
- medians of 3 interleaved rounds

| Variant | orphans/2000 | versions/200 |
| --- | ---: | ---: |
| before (serial `flatten`) | 17.15 ms | 12.65 ms |
| de-boxed, still serial | 17.20 ms | 12.66 ms |
| **this PR** | **10.77 ms** | **5.60 ms** |
| | −37% | −56% |

The de-boxed row is the point the review raised: removing the per-object
stream
buys nothing measurable on its own, so the entire change is the
concurrency.

### Modeling object-store listing latency

A local filesystem has no LIST round trip, so the local numbers
understate what
this change is for. The benchmark now accepts
`CLEANUP_BENCH_LIST_LATENCY_MICROS`, which charges every LIST a fixed
delay
inside the timed region only (setup stays unthrottled). With 1000 µs,
roughly a
same-region object store:

| Variant | orphans/2000 | versions/200 |
| --- | ---: | ---: |
| before (serial `flatten`) | 27.40 ms | 21.63 ms |
| de-boxed, still serial | 26.35 ms | 21.71 ms |
| **this PR** | **14.70 ms** | **8.64 ms** |
| | −46% | −60% |

This is still a modeled delay, not a real remote store. It shows the
shape of
the win rather than its absolute size on S3 or GCS.

## What is unchanged

- Which files cleanup selects and deletes.
- The listing cutoffs, including the `_versions`/`_indices` rules that
scan
  without a retained-manifest cutoff.
- Delete request counts: 2000 requests for 2000 paths in the orphan
scenario
  and 597 for 597 paths in the version scenario, before and after.

The outer composition (unreferenced files, then local staging files,
then
manifests) is also unchanged.

## Tests

- New `rust/lance/src/dataset/cleanup/tests/listing.rs`: a store wrapper
holds
each listing open and records the peak number of in-flight listings. The
test
asserts more than one managed subtree is in flight at a time, and fails
on a
serial merge. It asserts overlap, not duration, so it does not depend on
  machine speed.
- `cargo test -p lance --lib dataset::cleanup`: 311 passed.
- `cargo clippy -p lance --all-targets -- -D warnings`: clean.
- `cargo fmt --all`: clean.

The full workspace test suite was not run; the change is confined to
cleanup
listing and the cleanup benchmark.

## Review follow-ups in this revision

These three are folded into the PR and do not change performance — the
numbers
above already describe the original commit:

- Dropped the comment describing the removed per-object boxing, and
moved the
  history of the previous `flatten()` into the commit message.
- Corrected the concurrency note: `read_dir_all` is a single paginated
LIST, so
the merge is at most one in-flight LIST per subtree — not something
bounded
by the store's own listing concurrency. `None` is used instead of
restating
  `streams.len()`.
- Added the concurrency regression test and the modeled LIST latency to
the
  benchmark.

## Notes

- No file-format or API changes.
- `flatten_unordered` costs roughly 83–108 ns per item in scheduler
overhead
when measured with no I/O. At cleanup's real scale (~600 files in the
version
scenario, 2000 in the orphan scenario) that is not observable end to
end, but
a zero-allocation merge is a reasonable later optimisation if it ever
is. It
  was measured at parity here, so it is not part of this PR.
hint: if you need to wait for this pull request to be reviewed, merged,
or closed before continuing, use this instead of polling:
gh event listen --resource
#11167 --event
com.github.pull_request.review.submitted.v1,com.github.pull_request.state.changed.v1
- It prints the first event as a JSON line on stdout and exits; run it
again to wait for the next one.
- Add `--timeout` to stop waiting after a while, for example `--timeout
30m`; it then exits with status 8.
  - Events carry no details; read the pull request to see what changed.
- It misses changes made before it starts, so read the pull request once
it is running.
  - See `gh event listen --help` for other event types.
- Event subscriptions are in preview and may not be enabled for your
account.

</details>

Co-authored-by: Xuanwo <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

K-approved Latest Gatekeeper recommendation permits acceptance. performance

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants