Skip to content

perf: accelerate Lance access with shared metadata and index caches - #86

Open
FANNG1 wants to merge 20 commits into
daft-engine:mainfrom
FANNG1:feat/share-lance-session
Open

FANNG1 wants to merge 20 commits into
daft-engine:mainfrom
FANNG1:feat/share-lance-session

Conversation

@FANNG1

@FANNG1 FANNG1 commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #92

Summary

Repeated dataset opens can repeatedly load and decode the same large Lance manifest. This is particularly expensive when write_fragments opens an existing destination for every small batch. Reads and other operations that open the same table in one process can incur the same cost.

Share one lance.Session per process across dataset opens and fragment writes, allowing Lance to reuse its metadata and index caches. Dataset handles remain independently owned; this PR does not introduce a process-wide Dataset cache.

Implementation

  • Default dataset opens and fragment writes reuse one process-local lance.Session. A small selection helper is shared by the thin open_dataset(uri, **kwargs) wrapper and maintenance's low-level constructor.
  • Explicit Sessions are preserved. If any cache-size argument is non-None (including zero), no shared Session is injected: Lance interprets the options and creates an independent Session. Calls no longer depend on which table or configuration was opened first.
  • DAFT_LANCE_SHARE_SESSION=0/false/no restores Lance's normal per-open behavior. DAFT_LANCE_INDEX_CACHE_SIZE_BYTES and DAFT_LANCE_METADATA_CACHE_SIZE_BYTES configure only the default shared Session; invalid values report the setting and cannot be mistaken for a missing table by the sink.
  • The shared Session lives for the process lifetime, with explicit reset support. Reset releases only the global reference; existing Dataset handles stay valid. There is no TTL, background cleanup thread, fixed configuration registry, or custom legacy-capacity conversion.
  • Keep the initialization lock and fork reset for Python-side process state. Dataset/network operations run outside the lock. This does not make native Lance fork-safe.
  • read_blobs uses serializable DatasetOpenContext state rather than shipping the driver's Dataset/manifest. Each deserialized UDF closure opens once successfully under a lock and reuses that handle across batches. Preserve Lance-exposed read, base-store, storage, and default scan options. Namespace inputs may supply an originating open_context to retain namespace reconstruction and credential refresh. Without it, the existing read_blobs(df, ds, column) call keeps the original Dataset closure behavior rather than failing; this fallback retains Lance's existing serialization limitations. Explicit contexts with mismatched URI/version or missing namespace addressing are rejected.
  • Preserve DatasetOpenContext for pinned worker reopens; no duplicate DatasetOpenOptions parameter model remains.

Cache reuse still depends on Lance's cache keys, loading path, and capacity. This does not eliminate latest-version resolution or add a V1-manifest workaround. A URI must consistently identify the same underlying dataset; identical URIs referring to different endpoint data require isolation.

README documents behavior and configuration. Historical measurements and version-specific process-layout observations live in docs/session-performance.md, rather than being enforced as functional test contracts.

Local append benchmark

These measurements preceded the lifecycle simplification; they were not rerun for this refactor.

Run read_lance → write_lance(mode="append") on local Ray configured with 4 CPUs, using Daft 0.7.14 and pylance 12.0.0. Each run reads and appends 10,000 rows, with Lance scan batch size 16, into a pre-existing target. Each Session setting starts from a separate target with the same initial fragment count and manifest size.

Initial target fragments Manifest size Shared Session Wall time Sampled CPU time Average CPU
10,000 1.60 MiB Off 3.48 s 3.67 s 105.4%
10,000 1.60 MiB On 2.03 s 2.04 s 100.4%
100,000 16.18 MiB Off 25.41 s 26.64 s 104.8%
100,000 16.18 MiB On 2.75 s 2.94 s 106.6%

At 100,000 fragments, sharing reduced wall time by approximately 9.2× and CPU time by 89%. CPU utilization remained around one core: the improvement was less time spent doing the work, rather than lower instantaneous utilization.

Measurement boundaries:

  • One measured run per setting at each scale, executed sequentially. These are local observations, not a statistical performance guarantee.
  • CPU is sampled over the driver and descendant process tree every 250 ms; 100% represents one CPU core. Timing excludes input/target preparation, Ray startup/warmup, and output validation.
  • Targets use synthetic fragment metadata with distinct IDs referencing one seed data file. This exercises large-manifest loading without creating 100,000 initial data files; it does not model production object-store or distinct-file access costs.
  • The source has one fragment. The measured pipeline produces 625 new fragments from the 10,000 appended rows. This also exposes small-batch write overhead; Session sharing does not solve write buffering or fragment sizing.
  • Every run verifies the final row count and all appended values, normalizing Arrow string width for comparison. The 100,000-fragment target ends with 110,000 rows and 100,625 fragments.
  • Benchmark scripts are local-only and are not included in this PR or added to integration tests. These results do not establish performance at five million fragments.

Validation

After the lifecycle and selection changes:

  • Native Lance suite: 574 passed, 16 skipped, 2 xfailed, 2 xpassed, excluding external REST E2E and pre-existing untracked tests.
  • Updated Ray Session suite: 7 passed. Maintenance workers verify Session identity within their own process and check the pinned version/fragment count. Tests no longer require one process per UDF instance, compare addresses across processes, or require a compaction cache-growth ratio.
  • Explicit-capacity tests cover all three size options, zero values, and both call orders. Tests also cover invalid shared configuration, reset with active handles, and independent maintenance opens.
  • Local checks passed for real namespace Blob contents, optional context, retained read/base-store options, serialization resetting lazy state, and one open across 32 calls from 8 threads. A fork check verified only Python reference/lock reset, without invoking native Lance in the child.
  • Ruff, formatting, mypy, and diff checks passed.

Blob compatibility follow-up: native Blob/shared-Session tests passed (46 passed, 1 skipped); Ray Session tests plus both namespace Blob paths passed (9 passed). Added committed regressions for direct Lance namespace inputs without a Daft-Lance handle, optional serialized namespace context, URI/version/namespace mismatch, read/base-store parameters reaching the real Dataset constructor, and one open per deserialized UDF instance under concurrent calls. The base-store test checks forwarding, not remote authentication.

The benchmark scripts remain local-only; no performance benchmark was added to IT.

Every `lance.dataset()` opened without a session builds its own
`Arc<Manifest>` holding the table's whole fragment list, plus its own
index and metadata cache budgets and its own object-store client. Daft
opens one per scan task, per writer flush and per maintenance instance,
so a many-fragment table pays that again for every concurrently open
dataset.

Pass one process-level `Session` to every open instead. The manifest is
a metadata-cache entry keyed by (uri, version, e_tag), so every open of
the snapshot the driver pinned hands back a clone of the same
`Arc<Manifest>`.

`read_blobs` additionally stops closing over the driver's
`LanceDataset`: `__reduce__` ships the whole re-encoded manifest per
task, which both inflates the payload and bypasses the session's
manifest cache. It now carries the uri plus the pinned open kwargs and
reopens once per worker process.

`DAFT_LANCE_SHARE_SESSION=0` restores lance's per-open sessions. It is
an escape hatch, and the only way to get pre-sharing behavior inside a
Ray worker, which is what the A/B benchmark needs: a driver-side
monkeypatch never reaches the worker.

Measured in a Ray worker on a KubeRay cluster, `read_lance` ->
`write_parquet` (a write rather than an aggregation on purpose: a task
holds its parquet buffers at the same time as its manifest, so the two
compete for one memory limit):

- 4000 fragments x 10k rows, concurrency 24, whole table: worker
  ru_maxrss grew 206.5 MB unshared against 157.4 MB shared, so 49.1 MB
  less resident. Daft's own sampled peak agrees (487.8 vs 442.1 MB).
- 100k fragments x 10k rows, concurrency 8, reading 1% in groups of
  ten: 1052.2 MB against 573.3 MB, so 479.0 MB less resident -- and the
  pipeline finished in 61.9s instead of 609.6s. At that scale the cost
  of not sharing is mostly time: each unshared task re-parsed the same
  8 MB manifest, about 5.5s of the 6.1s it spent.
- Repeated `nearest` queries on a 200k-row IVF_PQ index run 1.7-2.0x
  faster, because the index is loaded once per process instead of once
  per query.

The maintenance path is the exception and is covered so the exception
stays documented: Daft runs each `daft.cls` instance in a process of its
own, so a maintenance worker opens the table exactly once however high
the concurrency, and nothing multiplies by it. An indexed table does not
change that -- a task's open brings in the index's metadata entry only,
and the index data is read once on the driver, when the compaction
commit remaps it onto the new fragment ids.

Tests assert the mechanism rather than the megabytes: `Session.size_bytes()`
is exact, needs no large table, and is zero for any open that did not go
through the process session. `benchmarks/lance_session_memory.py`
(`make bench`) is the counterpart that puts numbers on it.
@FANNG1 FANNG1 changed the title perf: share one lance Session per process perf: accelerate Lance access with shared metadata and index caches Nov 12, 2026
@FANNG1
FANNG1 marked this pull request as ready for review November 12, 2026 23:40
@FANNG1

FANNG1 commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor Author

@rchowell @universalmind303 @ChaosJu could you please review this PR?

It shares Lance metadata and index caches through a process-local Session to reduce repeated Dataset-open costs, particularly when small-batch appends repeatedly open a destination with a large manifest. Explicit Sessions and cache-size settings retain independent behavior.

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.

Slow write_lance appends to tables with large manifests due to repeated Dataset opens

1 participant