Skip to content

perf(cleanup): concurrent deletion and robustness fixes - #9414

Merged
zhangyue19921010 merged 9 commits into
lance-format:mainfrom
jackye1995:jack/fix-cleanup-deadlock
Sep 22, 2026
Merged

zhangyue19921010 merged 9 commits into
lance-format:mainfrom
jackye1995:jack/fix-cleanup-deadlock

Conversation

@jackye1995

@jackye1995 jackye1995 commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Problem

ObjectStore::remove_stream drove deletions with TryStreamExt::and_then, which awaits each delete before producing the next. Its only caller (cleanup_old_versions) drains it with try_for_each, also sequential. Cleanup therefore performed one network round trip per object, with no overlap.

Measured against a cloud store that is ~30 deletes/s. On a production bucket, cleanup could not finish tables holding large numbers of unreferenced files:

Table Unreferenced files Result
A 35.4M objects 9.7 h, removed 4.5%, never finished
B 3.2M data + deletion removed 0
C 996k data ~1.5–2 h, removed exactly 200,048

That 200,048 over ~1.5–2 h is 28–37 deletes/s — the serial round-trip rate. Tables with few unreferenced files are unaffected; 337k of them cleaned normally in the same run.

Fix 1 — delete concurrently

buffer_unordered(io_parallelism()) instead of and_then.

I first tried delegating to ObjectStore::delete_stream, which would additionally batch (S3 removes up to 1000 keys per request). It does not typecheck here: delete_stream takes a 'static stream of object_store::Result<Path>, while remove_stream takes a borrowed stream of lance_core::Result<Path> and its caller's stream borrows local state. Adopting it would mean changing this public signature, so it is noted in the doc comment as a follow-up rather than done here.

Deletion order is no longer preserved. Nothing depends on it: cleanup finds garbage by listing, not by walking old manifests ("if a data file is not referenced by any fragment in a valid manifest file then it will be deleted"), so a reordered or interrupted deletion leaves files the next run rediscovers. The one ordering constraint in delete_unreferenced_files — retiring version records only after their objects are gone — already runs after the stream is fully drained. --delete-rate-limit is applied to the input stream before remove_stream, so it still governs.

Fix 2 — an already-deleted object must not fail the sweep

Cleanup lists first and deletes after, so a concurrent writer or a second cleanup can remove a path in between. Propagating NotFound there abandons the entire sweep over one absent object. Observed on a live table with 24M unreferenced files, where a single vanished data file ended the run.

The inspection path already tolerates exactly this for manifests ("Another cleanup may remove an old manifest after this cleanup lists it"); this extends the same tolerance to deletion, which is idempotent by nature.

Fix 3 — stop issuing a HEAD per expired manifest

delete_unreferenced_files re-fetched the size of every manifest it was about to delete, purely to report bytes_removed:

let size_bytes = self.dataset.object_store.size(&path).await?;   // HEAD per manifest

The size is already known — ManifestLocation.size is populated by list_manifest_locations and passed to read_manifest during inspection, but process_manifest_file stored only (path, version) and dropped it. Carry it through, and fall back to a HEAD only when the listing did not report one. On table A that is 9.79M avoidable requests.

Fix 4 — count failed deletes instead of abandoning the sweep

A single failed DELETE aborted the whole run, discarding every object the sweep had
already identified. On a live bucket that is not hypothetical: transient GCS connection
failures killed a run 57 minutes in, after it had already freed 118 TiB, and the next
attempt had to redo the entire mark phase.

Failures are now counted in a new RemovalStats::failed_deletes and the sweep continues.
The first failure logs at warn, the rest at debug, so a failing backend cannot emit
millions of warnings.

This also required moving record_file to after the delete. Stats previously counted
what cleanup intended to remove, so anything that failed to delete was still reported as
removed — bytes_removed could not be reconciled against storage. That was pre-existing,
but "treat a failed delete as not removed" is unimplementable while stats are recorded
ahead of the outcome.

Fix 5 — a manifest that failed to delete keeps its store record

Fix 4 introduced this, and it is silent — nothing errors, the data is simply unreachable
afterwards.

delete_unreferenced_files retires store records only after the objects are gone, and
says why: "a record that outlives its manifest is retired by the next cleanup, the reverse
is a lost version."
Before this branch a failed manifest delete aborted the function, so
the retire loop never ran. Making failures non-fatal removed that accidental protection:
the sweep continued to the retire loop and called forget_version for manifests still on
disk, producing exactly the manifest-without-record state the comment warns about.

Fixed by recording the versions whose manifest delete failed and skipping them when
retiring.

Measured result

Table C, before and after, with this branch built and run against the same bucket:

Before After
Objects 920,670 7
Bytes 119,983,831,747 153,784,143
Version / rows 464,665 / 10,284 unchanged

920,663 objects and 111.6 GiB removed in 885 s — 1,040 objects/s, against ~30/s before. stats.bytes_removed matched the storage delta exactly. The speedup is below the 64× concurrency because listing and the mark phase are serial and unaffected.

Two larger tables from the same bucket, also on this branch:

Table Before After Freed
A (35.4M objects) 30.51 TiB 1,283 objects 22.01 TiB in 18,033 s
D (the 9.7 h / 4.5% case) 178.90 TiB 19.37 TiB ~159 TiB

Table D needed its manifests thinned first — it holds ~2,900 commits/hour, so the mark
phase alone had 3.99 TiB of manifests to read. That is a property of the table, not of
this change, but it is why the sweep rate matters so much: once marking is cheap, the
delete rate is the whole job.

@github-actions github-actions Bot added A-encoding Encoding, IO, file reader/writer performance A-python Python bindings labels Sep 18, 2026
`ObjectStore::remove_stream` drove deletions with `TryStreamExt::and_then`,
which awaits each delete before producing the next; its only caller drains it
with `try_for_each`, also sequential. Cleanup therefore performed one network
round trip per object with no overlap.

Measured against a cloud store that is ~30 deletes/s. On a production table
holding 3.2M unreferenced files this is ~30 hours, and on one holding 35.4M it
does not finish at all. A table observed mid-run had removed exactly 200,048
objects in ~1.5-2h, matching the serial round-trip rate.

Delegate to the store's own `delete_stream`, which is concurrent and, on
backends that support it, batched -- S3 removes up to 1000 keys per request.
`remove_dir_all` in the same file already uses it. Deletion order is not
preserved; nothing depends on it, because cleanup finds garbage by listing
rather than by walking old manifests, and the one ordering constraint
(retiring version records) already runs after the stream is fully drained.

Also stop issuing a HEAD per expired manifest. `delete_unreferenced_files`
re-fetched the size of every manifest it was about to delete purely for byte
accounting, though `ManifestLocation.size` is populated by the listing and then
discarded. Carry it through instead and fall back to a HEAD only when the
listing did not report one. On the 35.4M-object table that is 9.79M avoidable
requests.
delete_stream needs a 'static stream of object_store::Result and callers
pass a borrowed lance_core::Result stream, so delegation would change the
public signature. Use buffer_unordered(io_parallelism) instead.
Cleanup lists first and deletes after, so a concurrent writer or a second
cleanup can remove a path in between. Propagating NotFound there abandons the
entire sweep over one absent object -- observed on a live table with 24M
unreferenced files, where a single vanished data file ended the run.

The inspection path already tolerates this for manifests ("Another cleanup may
remove an old manifest after this cleanup lists it"); this extends the same
tolerance to deletion, which is idempotent by nature.
A single failed DELETE ended the whole cleanup and discarded RemovalStats.
Observed on a live table where, after removing 23.7M objects, one transient
sub-millisecond connection error ended the run and reported nothing -- the
deletions were durable, but the accounting was lost and the obvious response
is to start over.

Failures are now counted in RemovalStats::failed_deletes, the file is not
counted as removed, and the sweep continues. The next run finds the file again
by listing, which is how cleanup discovers garbage anyway.

This also makes the stats honest. record_file ran when a path was produced,
before it was deleted, so bytes_removed counted what cleanup intended to
remove. Deletion now happens with each file in scope, so the stats count what
was actually removed.

can_recover_delete_failure asserted that a blocked delete surfaced as an error.
It now asserts the file is counted and skipped and that cleanup completes. Its
own comment noted the previous behaviour depended on buffering order -- "it
seems stable to stably delete the data file even though the manifest delete
fails" -- which is no longer left to chance.

failed_deletes is exposed through the Python CleanupStats binding.
Tolerating delete failures introduced a way to reach the state the retire loop
exists to avoid. Records are retired after the objects are gone, because "a
record that outlives its manifest is retired by the next cleanup, the reverse
is a lost version". Previously a failed manifest delete aborted before that
loop ran; now the sweep continues, so the record of a manifest still on disk
was being forgotten -- a version nothing can find again.

Track the versions whose manifest delete failed and skip them when retiring.

The new test fails without the guard: records for versions 1 and 2 are retired
while their manifests remain, leaving [3] instead of [1, 2, 3].

IdentifiedStore moves to module scope so both external-store tests share it.
Per-file delete failures now log once at warn and the rest at debug; a failing
backend would otherwise emit a line per object.
@jackye1995
jackye1995 force-pushed the jack/fix-cleanup-deadlock branch from 503de36 to f0266f7 Compare September 19, 2026 00:34
…ytes

Each kind must add its size to bytes_removed, not merely increment its per-kind
counter. Index files dominate some tables, so an undercount there makes cleanup
look far less effective than it is; deletion and transaction files are small but
numerous. No existing test covered index or deletion bytes.

Verified non-vacuous: zeroing the index size fails with left 10746, right 18366;
zeroing the deletion and transaction sizes fails with left 18571, right 20051.
@jackye1995
jackye1995 force-pushed the jack/fix-cleanup-deadlock branch from f26a4ac to fc79ca5 Compare September 19, 2026 20:31
@jackye1995 jackye1995 changed the title perf(cleanup): delete objects in bulk instead of one at a time perf(cleanup): concurrent deletion and robustness fixes Sep 19, 2026
@jackye1995
jackye1995 marked this pull request as ready for review September 19, 2026 22:23
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-changes Latest Gatekeeper recommendation requests changes. label Sep 19, 2026
`calculate_duration` scaled the configured rate by a bulk-delete batch size
(1,000 on S3, 256 on Azure), which is only correct if one permit covers a whole
batch. Nothing coalesces paths into a single request: the limiter zips one tick
per file and each file is its own `delete`. A configured 100 requests/s
therefore issued up to 100,000.

The miscalibration predates this branch, but serial deletion capped throughput
low enough that the ticker never bound. Deleting concurrently removes that
accidental ceiling and leaves the limiter as the only safeguard, so it has to be
right.

The batch constants are now unused and removed, and `delete_rate_limit`'s doc no
longer claims requests may cover multiple paths.

Verified non-vacuous: reintroducing a 1,000x multiplier fails
test_calculate_duration with left 10us, right 10ms.
@lance-gatekeeper lance-gatekeeper Bot removed the K-changes Latest Gatekeeper recommendation requests changes. label Sep 19, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-changes Latest Gatekeeper recommendation requests changes. label Sep 19, 2026
Best-effort deletion made failed_deletes the only programmatic signal that
cleanup returned normally without removing everything it identified, but
cleanup_stats_to_java still invoked the six-long constructor. A Java caller
therefore saw stats indistinguishable from complete success and had no way to
trigger a retry.

Adds the field, getter and a seven-long constructor, and passes it through JNI.
The six-long constructor stays and defaults to zero, so existing callers keep
compiling.

The new Java test forces a real failure rather than asserting zero on a
successful run: asserting zero proves nothing, because the six-long constructor
defaults it to zero and a projection that dropped the field would still pass.
Removing a file needs write permission on its parent, so making _transactions
read-only fails those deletes while the manifest deletes still succeed. Root
ignores the bits, so the test probes first and skips rather than failing.

Verified non-vacuous: reverting the JNI to the six-long constructor fails it with
"expected the blocked transaction deletes to be counted, got 0".
@github-actions github-actions Bot added the A-java Java bindings + JNI label Sep 19, 2026
@lance-gatekeeper lance-gatekeeper Bot removed the K-changes Latest Gatekeeper recommendation requests changes. label Sep 19, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 19, 2026

@zhangyue19921010 zhangyue19921010 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nice Change! left two minor comments :)

Comment thread rust/lance/src/dataset/cleanup.rs Outdated
Comment on lines +783 to +789
.map(|(path, expired)| async move {
// HEAD only when the listing did not report a size. Fetching
// unconditionally costs a request per expired manifest.
let size_bytes = match expired.size_bytes {
Some(size_bytes) => size_bytes,
None => self.dataset.object_store.size(&path).await?,
};

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

If the manifest has been deleted by concurrent cleanup, size() returns NotFound, and ? will cause the entire cleanup to fail directly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch, fixed in 34750e6. This was the one place left that still turned a benign race
into a fatal error: the delete path already tolerates an already-gone object, but the size
lookup did not, so a manifest removed by a concurrent cleanup between the listing and the
HEAD would abort the whole sweep.

A vanished manifest now counts as zero bytes and the sweep continues.

I moved the resolution into expired_manifest_size so it can actually be tested — the
fixture's listings always report a size, so the fallback is unreachable from there and a
test through the fixture would have asserted nothing.

Verified non-vacuous: restoring the bare ? fails the new test with
NotFound { uri: "_versions/1.manifest" }, which is exactly the scenario you described.

pub index_files_removed: u64,
pub deletion_files_removed: u64,
/// Files that could not be deleted; not counted as removed.
pub failed_deletes: u64,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

nit: The class CleanupStats in python/python/lance/lance/__init__.pyi still has only six fields and is missing failed_deletes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 34750e6 — failed_deletes added to CleanupStats in
python/python/lance/lance/__init__.pyi.

Not really a nit: the stub is what type checkers and editors read, so without it the field
existed at runtime and was invisible to every Python caller — which defeats the point of
adding a signal callers are supposed to check.

I diffed the stub against the pyo3 struct field-by-field afterwards rather than eyeballing
it; all seven now match.

Review catch. When the listing did not report a manifest's size, cleanup fell
back to a HEAD and propagated its error. A concurrent cleanup can remove that
manifest between the listing and the HEAD, so `NotFound` there aborted the entire
sweep over a file already in the state the sweep wanted.

This is the same tolerance the delete path already has, applied to the one
remaining place that still turned a benign race into a fatal error.

The size resolution moves into `expired_manifest_size` so it can be tested
directly: the fixture's listings always report a size, so the fallback is
unreachable from there.

Verified non-vacuous: restoring the bare `?` fails the test with
NotFound { uri: "_versions/1.manifest" }, which is the reported scenario.

Also adds `failed_deletes` to the CleanupStats type stub, which still described
six fields.
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 21, 2026

@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.

The follow-up now treats a manifest that vanishes between listing and the fallback size lookup as an idempotent success while preserving other lookup failures. Python's public stub also exposes failed_deletes. The prior recommendation remains unchanged.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 21, 2026

@zhangyue19921010 zhangyue19921010 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nice work!

@zhangyue19921010
zhangyue19921010 merged commit 92968f0 into lance-format:main Sep 22, 2026
39 checks passed
jackylee-ch added a commit to jackylee-ch/lance-duckdb that referenced this pull request Oct 16, 2026
Lance 13 no longer fails cleanup on a file it cannot delete
(lance-format/lance#9414): the file is counted in failed_deletes and
left for a later run. List the VACUUM LANCE metrics, note that cleanup
is best-effort, and assert failed_deletes on the VACUUM LANCE surface.
Xuanwo added a commit to lance-format/lance-duckdb that referenced this pull request Oct 26, 2026
* chore: update lance dependency to v13.0.0

Lance 13 drops RowIdMeta::External, so build_row_id_index loads row id
sequences through load_row_id_sequence, which also reads row ids spilled
to a data-file column. Cleanup is best-effort in Lance 13, so the cleanup
metrics now report failed_deletes.

* docs(maintenance): document failed_deletes for VACUUM LANCE

Lance 13 no longer fails cleanup on a file it cannot delete
(lance-format/lance#9414): the file is counted in failed_deletes and
left for a later run. List the VACUUM LANCE metrics, note that cleanup
is best-effort, and assert failed_deletes on the VACUUM LANCE surface.

* fix(write): restate destination extension types on append

Lance checks an append against the destination and writes it under the
destination's fields; its check ignores most extensions, so Lance 12
recorded the destination's extensions whatever a batch carried. Lance
13's file writers now reject a batch whose extensions differ from those
fields (lance-format/lance#9478), which broke INSERT and COPY appends
Lance 12 accepted: DuckDB drops extensions it does not model, such as
arrow.fixed_shape_tensor, adds its own under arrow_lossless_conversion,
such as arrow.opaque on BIT, and spells geoarrow.wkb metadata its own
way. Wherever Lance would give both sides the same type, appends now
take the destination's extensions, which is what Lance 12 recorded;
JSON text takes only the metadata, keeping the arrow.json name that
makes Lance convert it. As with Lance 12, the values are not checked
against those extensions. Blob v2 fields, which Lance reads by their
extension, and the items of fixed-size lists of structs, which its check
compares whole, are left to Lance.

Writes that create or overwrite a dataset are left as they are. Lance's
schema describes the items of a fixed-size list that are not structs by
Lance type alone, so Lance 13 rejects a create or overwrite that writes
rows of such items with an extension. For UUID, HUGEINT, UHUGEINT,
TIME_TZ and BOOLEAN items under arrow_lossless_conversion, Lance 12
wrote the rows without the item type, as both versions still do when a
create writes no rows. It did the same for variable-width items with an
extension, such as GEOMETRY's, when no item held a value; otherwise its
encoder panicked, aborting DuckDB.

On appends, the items of a fixed-size list that are not structs take
the destination's extension the same way, as if they were fields, so
they can lose one such as GEOMETRY's. A COPY appending GEOMETRY[2] rows
with a non-null item to a table made by CREATE TABLE ... GEOMETRY[2],
for example, then reaches that encoder panic, as it did on Lance 12;
Lance 13 without this change rejected those rows.

* fix(maintenance): refuse delete_unverified with uncommitted Lance writes

With delete_unverified, Lance 13 lists data files without an age cutoff
(lance-format/lance#8944), so VACUUM LANCE deleted the data files of
writes a transaction had not committed yet, and its COMMIT then
published a table that could no longer be read. Refuse delete_unverified
while a transaction in this database holds Lance writes waiting for its
COMMIT, and document what the option removes, what the check cannot
see, and that the refusal aborts the transaction it runs in.

---------

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

A-encoding Encoding, IO, file reader/writer A-java Java bindings + JNI A-python Python bindings K-approved Latest Gatekeeper recommendation permits acceptance. performance

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants