mirror of
https://github.com/lancedb/lancedb.git
synced 2026-10-21 19:22:27 +00:00
refactor!: rename MemWAL APIs to RTE (realtime engine) (#4598)
## What Renames the user-facing MemWAL surface to **RTE** (realtime engine) across Rust, Python, TypeScript, and Java, including the REST wire format. This follows the LSM → MemWAL rename in #4075. | Before | After | |---|---| | `MemWalWriteSpec` / `MemWalStats` | `RTEWriteSpec` / `RTEStats` | | `enable_memwal` / `disable_memwal` / `get_memwal_spec` | `enable_rte` / `disable_rte` / `get_rte_spec` | | `flush_memwal` / `compact_memwal` / `checkpoint_memwal` | `flush_rte` / `compact_rte` / `checkpoint_rte` | | `get_memwal_stats` / `close_memwal_writers` | `get_rte_stats` / `close_rte_writers` | | `use_memwal` (query, merge insert) | `use_rte` | | TS/Java `enableMemWal`, `useMemWal`, ... | `enableRTE`, `useRTE`, ... (napi `js_name` set explicitly) | | Java `LanceDbTableMemWal` | `LanceDbTableRTE` | | `table/memwal_stats.rs` | `table/rte_stats.rs` | Docs and comments now say "realtime engine (RTE)". Text about Lance's underlying mechanism keeps "MemWAL" ("Lance's MemWAL", "MemWAL index"). **Left alone:** Lance-owned names (`MemWalIndexDetails`, `DatasetMemWalExt`, `InitializeMemWal*`, `mem_wal` paths), internal `Lsm*` names and modules, and the `does not support with_row_id` refusal text that the hybrid fallback matches on. ## Compatibility Breaking, for an experimental API. The wire format changes, so this must roll out together with the matching sophon change (lancedb/sophon#8870): - Routes: `/enable_memwal/` → `/enable_rte/`, `/disable_memwal/` → `/disable_rte/`, `/get_memwal_spec/` → `/get_rte_spec/`, `/get_memwal_stats/` → `/get_rte_stats/`, `/flush_memwal/` → `/flush_rte/`, `/compact_memwal/` → `/compact_rte/` - Response keys: `memwal_spec` → `rte_spec`, `memwal_stats` → `rte_stats` - Request field: `use_memwal` → `use_rte` on query and merge-insert bodies The SQL keyword becomes `ALTER TABLE ... SET RTE` server-side. The guides under `docs/web` will be updated separately. ## Validation - Rust: `cargo clippy --features remote --tests --examples` clean; `cargo test --features remote -p lancedb --lib`: 1533 passed - Java: `mvn test`: 37 passed (Spotless applied with JDK 11) - Python: `ruff format` / `ruff check` clean; targeted tests (`test_rte_spec`, `test_merge_insert_lsm`, `test_remote_db`, `test_wal_hybrid`, `test_query`, `test_permutation`, `test_table`): 708 passed - TypeScript: `pnpm build`; `table`, `query` tests: 606 passed; `biome check` clean; `docs/src/js` regenerated with `pnpm run docs` 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
1772f4ef83
commit
92825f6f13
@@ -425,16 +425,16 @@ Empty results retain the query's output schema.
|
||||
|
||||
***
|
||||
|
||||
### useMemWal()
|
||||
### useRTE()
|
||||
|
||||
```ts
|
||||
useMemWal(enable): this
|
||||
useRTE(enable): this
|
||||
```
|
||||
|
||||
Control MemWAL read routing for this query.
|
||||
Control RTE read routing for this query.
|
||||
|
||||
By default (unset), when the table carries a MemWAL write spec (see
|
||||
[Table#enableMemWal](Table.md#enablememwal)), reads are routed through the LSM scanner so
|
||||
By default (unset), when the table carries an RTE write spec (see
|
||||
[Table#enableRTE](Table.md#enablerte)), reads are routed through the LSM scanner so
|
||||
they also return data written via the `mergeInsert` LSM path that has not yet
|
||||
been compacted into the base table (the active/frozen in-memory memtables and
|
||||
the SSTables), deduplicated by primary key; a table without a spec
|
||||
@@ -444,12 +444,12 @@ reads the base table.
|
||||
|
||||
* **enable**: `boolean`
|
||||
`true` forces the LSM scanner and errors if the table has no
|
||||
MemWAL write spec. `false` bypasses the MemWAL and reads the base table only,
|
||||
RTE write spec. `false` bypasses the RTE and reads the base table only,
|
||||
even when a spec is present.
|
||||
Note: the LSM scanner does not support every query shape (e.g. reranking,
|
||||
hybrid search, `orderBy`). On a MemWAL table those shapes error unless
|
||||
`useMemWal(false)` is set, because a base-only read would silently exclude
|
||||
un-compacted MemWAL data.
|
||||
hybrid search, `orderBy`). On an RTE table those shapes error unless
|
||||
`useRTE(false)` is set, because a base-only read would silently exclude
|
||||
un-compacted RTE data.
|
||||
|
||||
#### Returns
|
||||
|
||||
@@ -457,7 +457,7 @@ reads the base table.
|
||||
|
||||
#### Inherited from
|
||||
|
||||
`StandardQueryBase.useMemWal`
|
||||
`StandardQueryBase.useRTE`
|
||||
|
||||
***
|
||||
|
||||
|
||||
@@ -76,23 +76,23 @@ the query optimizer chooses a suboptimal path.
|
||||
|
||||
***
|
||||
|
||||
### useMemWal()
|
||||
### useRTE()
|
||||
|
||||
```ts
|
||||
useMemWal(enable): MergeInsertBuilder
|
||||
useRTE(enable): MergeInsertBuilder
|
||||
```
|
||||
|
||||
Control MemWAL routing for this merge.
|
||||
Control RTE routing for this merge.
|
||||
|
||||
By default (unset), a `mergeInsert` on a table with a MemWAL write spec is
|
||||
By default (unset), a `mergeInsert` on a table with an RTE write spec is
|
||||
routed through Lance's MemWAL shard writer, and a table without one uses the
|
||||
standard path.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **enable**: `boolean`
|
||||
`true` forces MemWAL routing and errors if the table has no
|
||||
MemWAL write spec. `false` forces the standard write path even when a spec is set.
|
||||
`true` forces RTE routing and errors if the table has no
|
||||
RTE write spec. `false` forces the standard write path even when a spec is set.
|
||||
|
||||
#### Returns
|
||||
|
||||
@@ -108,12 +108,12 @@ validateSingleShard(validateSingleShard): MergeInsertBuilder
|
||||
|
||||
Controls how an LSM merge checks that its input targets a single shard.
|
||||
|
||||
When a table has a MemWAL write spec, every row in a `mergeInsert` call must
|
||||
When a table has an RTE write spec, every row in a `mergeInsert` call must
|
||||
route to the same shard. When `true` (the default), every row is inspected
|
||||
to verify this. When `false`, only the first row is inspected and the
|
||||
shard it routes to is used for the whole input — a faster path for callers
|
||||
that have already pre-sharded their input. Has no effect on tables without
|
||||
a MemWAL write spec.
|
||||
an RTE write spec.
|
||||
|
||||
#### Parameters
|
||||
|
||||
|
||||
@@ -499,16 +499,16 @@ Empty results retain the query's output schema.
|
||||
|
||||
***
|
||||
|
||||
### useMemWal()
|
||||
### useRTE()
|
||||
|
||||
```ts
|
||||
useMemWal(enable): this
|
||||
useRTE(enable): this
|
||||
```
|
||||
|
||||
Control MemWAL read routing for this query.
|
||||
Control RTE read routing for this query.
|
||||
|
||||
By default (unset), when the table carries a MemWAL write spec (see
|
||||
[Table#enableMemWal](Table.md#enablememwal)), reads are routed through the LSM scanner so
|
||||
By default (unset), when the table carries an RTE write spec (see
|
||||
[Table#enableRTE](Table.md#enablerte)), reads are routed through the LSM scanner so
|
||||
they also return data written via the `mergeInsert` LSM path that has not yet
|
||||
been compacted into the base table (the active/frozen in-memory memtables and
|
||||
the SSTables), deduplicated by primary key; a table without a spec
|
||||
@@ -518,12 +518,12 @@ reads the base table.
|
||||
|
||||
* **enable**: `boolean`
|
||||
`true` forces the LSM scanner and errors if the table has no
|
||||
MemWAL write spec. `false` bypasses the MemWAL and reads the base table only,
|
||||
RTE write spec. `false` bypasses the RTE and reads the base table only,
|
||||
even when a spec is present.
|
||||
Note: the LSM scanner does not support every query shape (e.g. reranking,
|
||||
hybrid search, `orderBy`). On a MemWAL table those shapes error unless
|
||||
`useMemWal(false)` is set, because a base-only read would silently exclude
|
||||
un-compacted MemWAL data.
|
||||
hybrid search, `orderBy`). On an RTE table those shapes error unless
|
||||
`useRTE(false)` is set, because a base-only read would silently exclude
|
||||
un-compacted RTE data.
|
||||
|
||||
#### Returns
|
||||
|
||||
@@ -531,7 +531,7 @@ reads the base table.
|
||||
|
||||
#### Inherited from
|
||||
|
||||
`StandardQueryBase.useMemWal`
|
||||
`StandardQueryBase.useRTE`
|
||||
|
||||
***
|
||||
|
||||
|
||||
@@ -228,13 +228,13 @@ version of the table.
|
||||
|
||||
***
|
||||
|
||||
### checkpointMemWal()
|
||||
### checkpointRTE()
|
||||
|
||||
```ts
|
||||
abstract checkpointMemWal(): Promise<void>
|
||||
abstract checkpointRTE(): Promise<void>
|
||||
```
|
||||
|
||||
Converge this table's MemWAL write path into its base table.
|
||||
Converge this table's RTE write path into its base table.
|
||||
|
||||
Freezes once, then triggers compaction and polls until the SSTables that existed
|
||||
at the start is gone. The target set is fixed at the start, so
|
||||
@@ -254,9 +254,9 @@ is merging. The caller owns the deadline.
|
||||
#### Example
|
||||
|
||||
```ts
|
||||
const before = await table.getMemWalStats();
|
||||
await table.checkpointMemWal();
|
||||
const after = await table.getMemWalStats();
|
||||
const before = await table.getRTEStats();
|
||||
await table.checkpointRTE();
|
||||
const after = await table.getRTEStats();
|
||||
```
|
||||
|
||||
***
|
||||
@@ -279,15 +279,15 @@ Any attempt to use the table after it is closed will result in an error.
|
||||
|
||||
***
|
||||
|
||||
### closeMemWalWriters()
|
||||
### closeRTEWriters()
|
||||
|
||||
```ts
|
||||
abstract closeMemWalWriters(): Promise<void>
|
||||
abstract closeRTEWriters(): Promise<void>
|
||||
```
|
||||
|
||||
Drain and close any cached MemWAL shard writers held for this table.
|
||||
Drain and close any cached RTE shard writers held for this table.
|
||||
|
||||
When an [MemWalWriteSpec](../interfaces/MemWalWriteSpec.md) is installed, `mergeInsert` opens MemWAL
|
||||
When an [RTEWriteSpec](../interfaces/RTEWriteSpec.md) is installed, `mergeInsert` opens RTE
|
||||
shard writers and caches them for reuse across calls. This closes them,
|
||||
flushing pending data; writers reopen lazily on the next `mergeInsert`.
|
||||
It is a no-op when no writers are cached.
|
||||
@@ -298,17 +298,17 @@ It is a no-op when no writers are cached.
|
||||
|
||||
***
|
||||
|
||||
### compactMemWal()
|
||||
### compactRTE()
|
||||
|
||||
```ts
|
||||
abstract compactMemWal(): Promise<void>
|
||||
abstract compactRTE(): Promise<void>
|
||||
```
|
||||
|
||||
Trigger a background SSTable compaction pass per table shard.
|
||||
|
||||
Returns once the passes are *dispatched*, not once they finish — watch
|
||||
[Table#getMemWalStats](Table.md#getmemwalstats) for progress, or use
|
||||
[Table#checkpointMemWal](Table.md#checkpointmemwal) to wait for convergence.
|
||||
[Table#getRTEStats](Table.md#getrtestats) for progress, or use
|
||||
[Table#checkpointRTE](Table.md#checkpointrte) to wait for convergence.
|
||||
|
||||
#### Returns
|
||||
|
||||
@@ -449,13 +449,13 @@ containing the new version number of the table
|
||||
|
||||
***
|
||||
|
||||
### disableMemWal()
|
||||
### disableRTE()
|
||||
|
||||
```ts
|
||||
abstract disableMemWal(): Promise<void>
|
||||
abstract disableRTE(): Promise<void>
|
||||
```
|
||||
|
||||
Remove the [MemWalWriteSpec](../interfaces/MemWalWriteSpec.md) from this table, reverting to the standard
|
||||
Remove the [RTEWriteSpec](../interfaces/RTEWriteSpec.md) from this table, reverting to the standard
|
||||
`mergeInsert` write path.
|
||||
|
||||
Errors if no spec is currently set.
|
||||
@@ -531,16 +531,16 @@ Drop an index from the table.
|
||||
|
||||
***
|
||||
|
||||
### enableMemWal()
|
||||
### enableRTE()
|
||||
|
||||
```ts
|
||||
abstract enableMemWal(spec): Promise<void>
|
||||
abstract enableRTE(spec): Promise<void>
|
||||
```
|
||||
|
||||
Install an [MemWalWriteSpec](../interfaces/MemWalWriteSpec.md) on this table, selecting Lance's MemWAL
|
||||
Install an [RTEWriteSpec](../interfaces/RTEWriteSpec.md) on this table, selecting Lance's MemWAL
|
||||
LSM-style write path for future `mergeInsert` calls.
|
||||
|
||||
`MemWalWriteSpec` chooses one of three sharding strategies via `specType`:
|
||||
`RTEWriteSpec` chooses one of three sharding strategies via `specType`:
|
||||
|
||||
- `"bucket"` — hash-bucket writes by the single-column unenforced primary
|
||||
key (`column` and `numBuckets` required).
|
||||
@@ -552,13 +552,13 @@ All variants require the table to have an unenforced primary key
|
||||
requires it to be the single column being bucketed.
|
||||
|
||||
Omitting `maintainedIndexes` maintains every index the table has,
|
||||
including ones created later, and skips a kind the MemWAL cannot maintain.
|
||||
including ones created later, and skips a kind the RTE cannot maintain.
|
||||
Naming them pins an exact set, and a still-building index is rejected
|
||||
rather than quietly omitted.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **spec**: [`MemWalWriteSpec`](../interfaces/MemWalWriteSpec.md)
|
||||
* **spec**: [`RTEWriteSpec`](../interfaces/RTEWriteSpec.md)
|
||||
The sharding spec to install.
|
||||
|
||||
#### Returns
|
||||
@@ -569,7 +569,7 @@ rather than quietly omitted.
|
||||
|
||||
```ts
|
||||
await table.setUnenforcedPrimaryKey("id");
|
||||
await table.enableMemWal({
|
||||
await table.enableRTE({
|
||||
specType: "bucket",
|
||||
column: "id",
|
||||
numBuckets: 16,
|
||||
@@ -647,10 +647,10 @@ memory; use [Table.fetchBlobFiles](Table.md#fetchblobfiles) for large values.
|
||||
|
||||
***
|
||||
|
||||
### flushMemWal()
|
||||
### flushRTE()
|
||||
|
||||
```ts
|
||||
abstract flushMemWal(): Promise<void>
|
||||
abstract flushRTE(): Promise<void>
|
||||
```
|
||||
|
||||
Freeze every table shard's active memtable into a new SSTable.
|
||||
@@ -699,38 +699,38 @@ const { records, truncated } = await table.functionErrors({ column: "embedding"
|
||||
|
||||
***
|
||||
|
||||
### getMemWalSpec()
|
||||
### getRTESpec()
|
||||
|
||||
```ts
|
||||
abstract getMemWalSpec(): Promise<undefined | MemWalWriteSpec>
|
||||
abstract getRTESpec(): Promise<undefined | RTEWriteSpec>
|
||||
```
|
||||
|
||||
Read the [MemWalWriteSpec](../interfaces/MemWalWriteSpec.md) currently installed on this table.
|
||||
Read the [RTEWriteSpec](../interfaces/RTEWriteSpec.md) currently installed on this table.
|
||||
|
||||
Resolves to `undefined` when the MemWAL write path is not enabled (no
|
||||
spec has been set, or it was removed with [Table#disableMemWal](Table.md#disablememwal)).
|
||||
Resolves to `undefined` when the RTE write path is not enabled (no
|
||||
spec has been set, or it was removed with [Table#disableRTE](Table.md#disablerte)).
|
||||
The spec is the one installed, including its maintained-index selection:
|
||||
an absent `maintainedIndexes` for every index the table has, an empty
|
||||
array for none.
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<`undefined` \| [`MemWalWriteSpec`](../interfaces/MemWalWriteSpec.md)>
|
||||
`Promise`<`undefined` \| [`RTEWriteSpec`](../interfaces/RTEWriteSpec.md)>
|
||||
|
||||
***
|
||||
|
||||
### getMemWalStats()
|
||||
### getRTEStats()
|
||||
|
||||
```ts
|
||||
abstract getMemWalStats(includeSstableRows?): Promise<undefined | MemWalStats>
|
||||
abstract getRTEStats(includeSstableRows?): Promise<undefined | RTEStats>
|
||||
```
|
||||
|
||||
Read live per-table-shard MemWAL state.
|
||||
Read live per-table-shard RTE state.
|
||||
|
||||
Answers "how far behind is my fresh tier", "which table shard is hot", and
|
||||
"why is my fresh-tier vector search brute-force". Mutates no table state.
|
||||
|
||||
Resolves to `undefined` only when the MemWAL write path is not enabled.
|
||||
Resolves to `undefined` only when the RTE write path is not enabled.
|
||||
|
||||
#### Parameters
|
||||
|
||||
@@ -740,7 +740,7 @@ Resolves to `undefined` only when the MemWAL write path is not enabled.
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<`undefined` \| [`MemWalStats`](../interfaces/MemWalStats.md)>
|
||||
`Promise`<`undefined` \| [`RTEStats`](../interfaces/RTEStats.md)>
|
||||
|
||||
***
|
||||
|
||||
|
||||
@@ -275,17 +275,17 @@ Empty results retain the query's output schema.
|
||||
|
||||
***
|
||||
|
||||
### useMemWal()
|
||||
### useRTE()
|
||||
|
||||
```ts
|
||||
useMemWal(enable): this
|
||||
useRTE(enable): this
|
||||
```
|
||||
|
||||
Control MemWAL read routing for this take query.
|
||||
Control RTE read routing for this take query.
|
||||
|
||||
`false` bypasses the MemWAL and reads the base table only — the escape hatch,
|
||||
`false` bypasses the RTE and reads the base table only — the escape hatch,
|
||||
since take-by-row-id/offset is not supported on the LSM scanner and, on a
|
||||
MemWAL table, auto-routes to it and errors otherwise.
|
||||
RTE table, auto-routes to it and errors otherwise.
|
||||
|
||||
#### Parameters
|
||||
|
||||
|
||||
@@ -659,7 +659,7 @@ minimum; one searches all partitions within the caller maximum. Later
|
||||
probing may continue when too few candidates are found.
|
||||
Any explicit effort, including 0.5, overrides nprobes in either call order.
|
||||
Explicit minimum and maximum bounds still apply. This is not a recall
|
||||
guarantee and does not change refinement or HNSW ef. The MemWAL LSM
|
||||
guarantee and does not change refinement or HNSW ef. The RTE LSM
|
||||
scanner does not yet support this option.
|
||||
|
||||
#### Parameters
|
||||
@@ -781,16 +781,16 @@ Empty results retain the query's output schema.
|
||||
|
||||
***
|
||||
|
||||
### useMemWal()
|
||||
### useRTE()
|
||||
|
||||
```ts
|
||||
useMemWal(enable): this
|
||||
useRTE(enable): this
|
||||
```
|
||||
|
||||
Control MemWAL read routing for this query.
|
||||
Control RTE read routing for this query.
|
||||
|
||||
By default (unset), when the table carries a MemWAL write spec (see
|
||||
[Table#enableMemWal](Table.md#enablememwal)), reads are routed through the LSM scanner so
|
||||
By default (unset), when the table carries an RTE write spec (see
|
||||
[Table#enableRTE](Table.md#enablerte)), reads are routed through the LSM scanner so
|
||||
they also return data written via the `mergeInsert` LSM path that has not yet
|
||||
been compacted into the base table (the active/frozen in-memory memtables and
|
||||
the SSTables), deduplicated by primary key; a table without a spec
|
||||
@@ -800,12 +800,12 @@ reads the base table.
|
||||
|
||||
* **enable**: `boolean`
|
||||
`true` forces the LSM scanner and errors if the table has no
|
||||
MemWAL write spec. `false` bypasses the MemWAL and reads the base table only,
|
||||
RTE write spec. `false` bypasses the RTE and reads the base table only,
|
||||
even when a spec is present.
|
||||
Note: the LSM scanner does not support every query shape (e.g. reranking,
|
||||
hybrid search, `orderBy`). On a MemWAL table those shapes error unless
|
||||
`useMemWal(false)` is set, because a base-only read would silently exclude
|
||||
un-compacted MemWAL data.
|
||||
hybrid search, `orderBy`). On an RTE table those shapes error unless
|
||||
`useRTE(false)` is set, because a base-only read would silently exclude
|
||||
un-compacted RTE data.
|
||||
|
||||
#### Returns
|
||||
|
||||
@@ -813,7 +813,7 @@ reads the base table.
|
||||
|
||||
#### Inherited from
|
||||
|
||||
`StandardQueryBase.useMemWal`
|
||||
`StandardQueryBase.useRTE`
|
||||
|
||||
***
|
||||
|
||||
|
||||
@@ -114,8 +114,6 @@
|
||||
- [ListTablesResponse](interfaces/ListTablesResponse.md)
|
||||
- [ListingOptions](interfaces/ListingOptions.md)
|
||||
- [MaterializedViewDefinition](interfaces/MaterializedViewDefinition.md)
|
||||
- [MemWalStats](interfaces/MemWalStats.md)
|
||||
- [MemWalWriteSpec](interfaces/MemWalWriteSpec.md)
|
||||
- [MemtableStats](interfaces/MemtableStats.md)
|
||||
- [MergeResult](interfaces/MergeResult.md)
|
||||
- [NativeOAuthConfig](interfaces/NativeOAuthConfig.md)
|
||||
@@ -124,6 +122,8 @@
|
||||
- [OptimizeOptions](interfaces/OptimizeOptions.md)
|
||||
- [OptimizeStats](interfaces/OptimizeStats.md)
|
||||
- [QueryExecutionOptions](interfaces/QueryExecutionOptions.md)
|
||||
- [RTEStats](interfaces/RTEStats.md)
|
||||
- [RTEWriteSpec](interfaces/RTEWriteSpec.md)
|
||||
- [RefreshColumnResult](interfaces/RefreshColumnResult.md)
|
||||
- [RefreshMaterializedViewResult](interfaces/RefreshMaterializedViewResult.md)
|
||||
- [RemovalStats](interfaces/RemovalStats.md)
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / MemWalStats
|
||||
[@lancedb/lancedb](../globals.md) / RTEStats
|
||||
|
||||
# Interface: MemWalStats
|
||||
# Interface: RTEStats
|
||||
|
||||
Live per-table-shard MemWAL state, as returned by `Table#getMemWalStats`.
|
||||
Live per-table-shard RTE state, as returned by `Table#getRTEStats`.
|
||||
|
||||
Nothing here is derived: sums and differences (total SSTable bytes, WAL lag) are
|
||||
the caller's to compute.
|
||||
@@ -2,12 +2,12 @@
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / MemWalWriteSpec
|
||||
[@lancedb/lancedb](../globals.md) / RTEWriteSpec
|
||||
|
||||
# Interface: MemWalWriteSpec
|
||||
# Interface: RTEWriteSpec
|
||||
|
||||
Specification selecting Lance's MemWAL LSM-style write path for
|
||||
`mergeInsert`.
|
||||
Specification enabling the realtime engine (RTE), which routes
|
||||
`mergeInsert` through Lance's MemWAL LSM-style write path.
|
||||
|
||||
`specType` is `"bucket"`, `"identity"`, or `"unsharded"`. For `"bucket"`,
|
||||
`column` and `numBuckets` are required; for `"identity"`, `column` is
|
||||
@@ -34,7 +34,7 @@ Bucket and identity variants: the sharding column.
|
||||
optional maintainedIndexes: string[];
|
||||
```
|
||||
|
||||
Indexes the MemWAL keeps up to date. Omit for every index the table has,
|
||||
Indexes the RTE keeps up to date. Omit for every index the table has,
|
||||
including ones created later. Pass `[]` for none.
|
||||
|
||||
***
|
||||
@@ -297,7 +297,7 @@ listing a storage directory.
|
||||
|
||||
::: lancedb.table.Branches
|
||||
|
||||
::: lancedb.MemWalWriteSpec
|
||||
::: lancedb.RTEWriteSpec
|
||||
|
||||
## Functions and Jobs
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<projectDescription>
|
||||
<name>lancedb-parent</name>
|
||||
<comment></comment>
|
||||
<projects>
|
||||
</projects>
|
||||
<buildSpec>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.m2e.core.maven2Builder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
</buildSpec>
|
||||
<natures>
|
||||
<nature>org.eclipse.m2e.core.maven2Nature</nature>
|
||||
</natures>
|
||||
<filteredResources>
|
||||
<filter>
|
||||
<id>1786980408448</id>
|
||||
<name></name>
|
||||
<type>30</type>
|
||||
<matcher>
|
||||
<id>org.eclipse.core.resources.regexFilterMatcher</id>
|
||||
<arguments>node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
|
||||
</matcher>
|
||||
</filter>
|
||||
</filteredResources>
|
||||
</projectDescription>
|
||||
@@ -0,0 +1,2 @@
|
||||
eclipse.preferences.version=1
|
||||
encoding/<project>=UTF-8
|
||||
@@ -0,0 +1,4 @@
|
||||
activeProfiles=
|
||||
eclipse.preferences.version=1
|
||||
resolveWorkspaceProjects=true
|
||||
version=1
|
||||
+9
-9
@@ -29,34 +29,34 @@ LanceNamespace namespaceClient = LanceDbNamespaceClientBuilder.newBuilder()
|
||||
.build();
|
||||
```
|
||||
|
||||
## MemWAL write path
|
||||
## RTE write path
|
||||
|
||||
Most table operations reach LanceDB through the `LanceNamespace` above, which is
|
||||
generated from the Lance Namespace specification. The MemWAL LSM routes are not part
|
||||
generated from the Lance Namespace specification. The RTE LSM routes are not part
|
||||
of that specification, so they are issued through a separate client:
|
||||
|
||||
```java
|
||||
import com.lancedb.LanceDbRestClient;
|
||||
import com.lancedb.LanceDbTableMemWal;
|
||||
import com.lancedb.MemWalWriteSpec;
|
||||
import com.lancedb.LanceDbTableRTE;
|
||||
import com.lancedb.RTEWriteSpec;
|
||||
|
||||
LanceDbRestClient client = LanceDbNamespaceClientBuilder.newBuilder()
|
||||
.apiKey("your_lancedb_cloud_api_key")
|
||||
.database("your_database_name")
|
||||
.buildRestClient();
|
||||
|
||||
LanceDbTableMemWal memWal = new LanceDbTableMemWal(client, "my_table");
|
||||
LanceDbTableRTE rte = new LanceDbTableRTE(client, "my_table");
|
||||
|
||||
// Route future merge_insert upserts through the MemWAL, hash-bucketed by `id`.
|
||||
memWal.enableMemWal(MemWalWriteSpec.bucket("id", 16));
|
||||
// Route future merge_insert upserts through the RTE, hash-bucketed by `id`.
|
||||
rte.enableRTE(RTEWriteSpec.bucket("id", 16));
|
||||
|
||||
// ... merge_insert traffic ...
|
||||
|
||||
// Converge the fresh tier into the base table.
|
||||
memWal.checkpointMemWal();
|
||||
rte.checkpointRTE();
|
||||
|
||||
// Inspect live per-table-shard state.
|
||||
memWal.getMemWalStats().ifPresent(stats -> stats.tableShards().forEach(tableShard ->
|
||||
rte.getRTEStats().ifPresent(stats -> stats.tableShards().forEach(tableShard ->
|
||||
System.out.println(tableShard.shardId() + ": " + tableShard.sstables().size() + " SSTables")));
|
||||
|
||||
client.close();
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<classpath>
|
||||
<classpathentry kind="src" output="target/classes" path="src/main/java">
|
||||
<attributes>
|
||||
<attribute name="optional" value="true"/>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
<attribute name="optional" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
|
||||
<attributes>
|
||||
<attribute name="optional" value="true"/>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
<attribute name="test" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
<attribute name="test" value="true"/>
|
||||
<attribute name="optional" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-11">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="src" path="target/generated-sources/annotations">
|
||||
<attributes>
|
||||
<attribute name="optional" value="true"/>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
<attribute name="ignore_optional_problems" value="true"/>
|
||||
<attribute name="m2e-apt" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="src" output="target/test-classes" path="target/generated-test-sources/test-annotations">
|
||||
<attributes>
|
||||
<attribute name="optional" value="true"/>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
<attribute name="ignore_optional_problems" value="true"/>
|
||||
<attribute name="m2e-apt" value="true"/>
|
||||
<attribute name="test" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="output" path="target/classes"/>
|
||||
</classpath>
|
||||
@@ -0,0 +1,34 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<projectDescription>
|
||||
<name>lancedb-core</name>
|
||||
<comment></comment>
|
||||
<projects>
|
||||
</projects>
|
||||
<buildSpec>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.jdt.core.javabuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.m2e.core.maven2Builder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
</buildSpec>
|
||||
<natures>
|
||||
<nature>org.eclipse.jdt.core.javanature</nature>
|
||||
<nature>org.eclipse.m2e.core.maven2Nature</nature>
|
||||
</natures>
|
||||
<filteredResources>
|
||||
<filter>
|
||||
<id>1786980408445</id>
|
||||
<name></name>
|
||||
<type>30</type>
|
||||
<matcher>
|
||||
<id>org.eclipse.core.resources.regexFilterMatcher</id>
|
||||
<arguments>node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
|
||||
</matcher>
|
||||
</filter>
|
||||
</filteredResources>
|
||||
</projectDescription>
|
||||
@@ -0,0 +1,5 @@
|
||||
eclipse.preferences.version=1
|
||||
encoding//src/main/java=UTF-8
|
||||
encoding//src/test/java=UTF-8
|
||||
encoding//src/test/resources=UTF-8
|
||||
encoding/<project>=UTF-8
|
||||
@@ -0,0 +1,2 @@
|
||||
eclipse.preferences.version=1
|
||||
org.eclipse.jdt.apt.aptEnabled=false
|
||||
@@ -0,0 +1,9 @@
|
||||
eclipse.preferences.version=1
|
||||
org.eclipse.jdt.core.compiler.codegen.targetPlatform=11
|
||||
org.eclipse.jdt.core.compiler.compliance=11
|
||||
org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
|
||||
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore
|
||||
org.eclipse.jdt.core.compiler.processAnnotations=disabled
|
||||
org.eclipse.jdt.core.compiler.release=disabled
|
||||
org.eclipse.jdt.core.compiler.source=11
|
||||
@@ -0,0 +1,4 @@
|
||||
activeProfiles=
|
||||
eclipse.preferences.version=1
|
||||
resolveWorkspaceProjects=true
|
||||
version=1
|
||||
@@ -20,11 +20,11 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
*
|
||||
* <p>Every reader fails closed: a missing, null, or wrong-typed field throws rather than
|
||||
* defaulting. That mirrors the serde decoding the Rust client applies to the same payloads in
|
||||
* {@code rust/lancedb/src/table/memwal_stats.rs}, where a required field has no default and a
|
||||
* {@code rust/lancedb/src/table/rte_stats.rs}, where a required field has no default and a
|
||||
* malformed response is an error rather than a zero.
|
||||
*
|
||||
* <p>The alternative — Jackson's {@code path()}, which yields a missing node that reads as an empty
|
||||
* array or a zero — is unsafe here because {@link LanceDbTableMemWal#checkpointMemWal()} decides
|
||||
* array or a zero — is unsafe here because {@link LanceDbTableRTE#checkpointRTE()} decides
|
||||
* convergence from these numbers. A defaulted {@code sstables} array is indistinguishable from a
|
||||
* drained one, so a malformed response would report a checkpoint that never happened.
|
||||
*/
|
||||
|
||||
@@ -151,8 +151,8 @@ public class LanceDbNamespaceClientBuilder {
|
||||
* Build a {@link LanceDbRestClient} for the same endpoint.
|
||||
*
|
||||
* <p>Needed only for LanceDB routes that the Lance Namespace specification does not cover — the
|
||||
* MemWAL write path, reached through {@link LanceDbTableMemWal}. Every other table
|
||||
* operation belongs on the {@link LanceNamespace} from {@link #build()}.
|
||||
* RTE write path, reached through {@link LanceDbTableRTE}. Every other table operation belongs on
|
||||
* the {@link LanceNamespace} from {@link #build()}.
|
||||
*
|
||||
* <p>The returned client owns an HTTP connection pool; close it when you are done with it.
|
||||
*
|
||||
|
||||
@@ -31,9 +31,9 @@ import java.io.UncheckedIOException;
|
||||
* specification does not cover.
|
||||
*
|
||||
* <p>Most table operations reach LanceDB through {@link org.lance.namespace.LanceNamespace}, which
|
||||
* is generated from the namespace spec. A handful of routes — the MemWAL write path in
|
||||
* particular — are served by the same endpoint but are not part of that spec, so they are issued
|
||||
* directly here. See {@link LanceDbTableMemWal}.
|
||||
* is generated from the namespace spec. A handful of routes — the RTE write path in particular —
|
||||
* are served by the same endpoint but are not part of that spec, so they are issued directly here.
|
||||
* See {@link LanceDbTableRTE}.
|
||||
*
|
||||
* <p>Obtain one from {@link LanceDbNamespaceClientBuilder#buildRestClient()}.
|
||||
*/
|
||||
@@ -50,8 +50,8 @@ public class LanceDbRestClient implements Closeable {
|
||||
this.apiKey = apiKey;
|
||||
this.database = database;
|
||||
// Automatic retries off, deliberately. The default strategy retries 429 and 503 —
|
||||
// exactly the two statuses LanceDbTableMemWal.checkpointMemWal() acts on — which would
|
||||
// silently double its explicit retry budget and would also retry compact_memwal in
|
||||
// exactly the two statuses LanceDbTableRTE.checkpointRTE() acts on — which would
|
||||
// silently double its explicit retry budget and would also retry compact_rte in
|
||||
// place, where the loop is designed to fall through to a fresh stats poll instead.
|
||||
// The checkpoint loop owns the 421/429/503 transitions; the transport must not.
|
||||
this.http = HttpClients.custom().disableAutomaticRetries().build();
|
||||
@@ -98,9 +98,8 @@ public class LanceDbRestClient implements Closeable {
|
||||
/**
|
||||
* A non-2xx response.
|
||||
*
|
||||
* <p>The status is exposed because callers act on it: {@link
|
||||
* LanceDbTableMemWal#checkpointMemWal()} treats 429 and 503 as retryable and 421 as a lost node
|
||||
* claim.
|
||||
* <p>The status is exposed because callers act on it: {@link LanceDbTableRTE#checkpointRTE()}
|
||||
* treats 429 and 503 as retryable and 421 as a lost node claim.
|
||||
*/
|
||||
public static class HttpException extends RuntimeException {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
+58
-58
@@ -22,11 +22,11 @@ import java.util.Optional;
|
||||
import java.util.OptionalLong;
|
||||
|
||||
/**
|
||||
* The MemWAL write path for one LanceDB Cloud or Enterprise table.
|
||||
* The RTE write path for one LanceDB Cloud or Enterprise table.
|
||||
*
|
||||
* <p>Installing an {@link MemWalWriteSpec} routes {@code mergeInsert} upserts through Lance's
|
||||
* MemWAL — an LSM-style append — instead of the standard merge path. Rows land in an in-memory
|
||||
* memtable, freeze into SSTables, and are merged into the base table by compaction.
|
||||
* <p>Installing an {@link RTEWriteSpec} routes {@code mergeInsert} upserts through Lance's RTE — an
|
||||
* LSM-style append — instead of the standard merge path. Rows land in an in-memory memtable, freeze
|
||||
* into SSTables, and are merged into the base table by compaction.
|
||||
*
|
||||
* <p>These routes are not part of the Lance Namespace specification, so they are issued directly
|
||||
* rather than through {@link org.lance.namespace.LanceNamespace}.
|
||||
@@ -37,23 +37,23 @@ import java.util.OptionalLong;
|
||||
* .database("your_database_name")
|
||||
* .buildRestClient();
|
||||
*
|
||||
* LanceDbTableMemWal memWal = new LanceDbTableMemWal(client, "my_table");
|
||||
* memWal.enableMemWal(MemWalWriteSpec.bucket("id", 16));
|
||||
* LanceDbTableRTE rte = new LanceDbTableRTE(client, "my_table");
|
||||
* rte.enableRTE(RTEWriteSpec.bucket("id", 16));
|
||||
* // ... merge_insert traffic ...
|
||||
* memWal.checkpointMemWal();
|
||||
* rte.checkpointRTE();
|
||||
* }</pre>
|
||||
*/
|
||||
public class LanceDbTableMemWal {
|
||||
public class LanceDbTableRTE {
|
||||
|
||||
/**
|
||||
* Interval between {@code get_memwal_stats} polls during a checkpoint. One interval is roughly
|
||||
* one compaction pass, the granularity at which the answer can change.
|
||||
* Interval between {@code get_rte_stats} polls during a checkpoint. One interval is roughly one
|
||||
* compaction pass, the granularity at which the answer can change.
|
||||
*/
|
||||
private static final long POLL_INTERVAL_MS = 5_000L;
|
||||
|
||||
/**
|
||||
* Cap on re-issues from {@code flushMemWal} after a 421, so a crash-looping node cannot turn
|
||||
* flush → compact → 421 → flush into a spin.
|
||||
* Cap on re-issues from {@code flushRTE} after a 421, so a crash-looping node cannot turn flush →
|
||||
* compact → 421 → flush into a spin.
|
||||
*
|
||||
* <p>Deliberately not shared with {@link #MAX_RETRIES}: a claim that keeps evaporating is a
|
||||
* broken node, while contention is routine and wants a real budget.
|
||||
@@ -79,7 +79,7 @@ public class LanceDbTableMemWal {
|
||||
* @param tableIdentifier The table's full identifier, {@code $}-delimited when it sits inside a
|
||||
* namespace, such as {@code analytics$events}.
|
||||
*/
|
||||
public LanceDbTableMemWal(LanceDbRestClient client, String tableIdentifier) {
|
||||
public LanceDbTableRTE(LanceDbRestClient client, String tableIdentifier) {
|
||||
if (client == null) {
|
||||
throw new IllegalArgumentException("Client cannot be null");
|
||||
}
|
||||
@@ -91,46 +91,46 @@ public class LanceDbTableMemWal {
|
||||
}
|
||||
|
||||
/**
|
||||
* Install an {@link MemWalWriteSpec} on this table, selecting the MemWAL write path for
|
||||
* future {@code mergeInsert} calls.
|
||||
* Install an {@link RTEWriteSpec} on this table, selecting the RTE write path for future {@code
|
||||
* mergeInsert} calls.
|
||||
*
|
||||
* <p>All variants require the table to have an unenforced primary key; bucket sharding
|
||||
* additionally requires it to be the single column being bucketed.
|
||||
*/
|
||||
public void enableMemWal(MemWalWriteSpec spec) {
|
||||
public void enableRTE(RTEWriteSpec spec) {
|
||||
if (spec == null) {
|
||||
throw new IllegalArgumentException("Spec cannot be null");
|
||||
}
|
||||
client.post(route("enable_memwal"), spec.toRequestBody());
|
||||
client.post(route("enable_rte"), spec.toRequestBody());
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the {@link MemWalWriteSpec} from this table, reverting to the standard {@code
|
||||
* mergeInsert} write path.
|
||||
* Remove the {@link RTEWriteSpec} from this table, reverting to the standard {@code mergeInsert}
|
||||
* write path.
|
||||
*
|
||||
* <p>Errors if no spec is currently set.
|
||||
*/
|
||||
public void disableMemWal() {
|
||||
client.post(route("disable_memwal"), null);
|
||||
public void disableRTE() {
|
||||
client.post(route("disable_rte"), null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the {@link MemWalWriteSpec} currently installed on this table.
|
||||
* Read the {@link RTEWriteSpec} currently installed on this table.
|
||||
*
|
||||
* <p>Empty when the MemWAL write path is not enabled at all — no spec has been set, or one was
|
||||
* removed with {@link #disableMemWal()}. That is a different answer from a present spec whose
|
||||
* {@link MemWalWriteSpec#maintainedIndexes()} is null, which selects indexes automatically.
|
||||
* <p>Empty when the RTE write path is not enabled at all — no spec has been set, or one was
|
||||
* removed with {@link #disableRTE()}. That is a different answer from a present spec whose {@link
|
||||
* RTEWriteSpec#maintainedIndexes()} is null, which selects indexes automatically.
|
||||
*
|
||||
* <p>The spec read back is the one that was installed, selection included: null maintains every
|
||||
* supported index the table has now or gains later, an empty list maintains none, and a non-empty
|
||||
* list maintains exactly those. All three round-trip.
|
||||
*/
|
||||
public Optional<MemWalWriteSpec> getMemWalSpec() {
|
||||
JsonNode response = client.post(route("get_memwal_spec"), null);
|
||||
if (response == null || !response.hasNonNull("memwal_spec")) {
|
||||
public Optional<RTEWriteSpec> getRTESpec() {
|
||||
JsonNode response = client.post(route("get_rte_spec"), null);
|
||||
if (response == null || !response.hasNonNull("rte_spec")) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(MemWalWriteSpec.fromJson(response.get("memwal_spec")));
|
||||
return Optional.of(RTEWriteSpec.fromJson(response.get("rte_spec")));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -139,56 +139,56 @@ public class LanceDbTableMemWal {
|
||||
* <p>Returns once the freeze is committed. Freezing an empty memtable is a no-op, so this is safe
|
||||
* to call repeatedly.
|
||||
*/
|
||||
public void flushMemWal() {
|
||||
client.post(route("flush_memwal"), null);
|
||||
public void flushRTE() {
|
||||
client.post(route("flush_rte"), null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger a background SSTable compaction pass per table shard.
|
||||
*
|
||||
* <p>Returns once the passes are <em>dispatched</em>, not once they finish — watch {@link
|
||||
* #getMemWalStats}, or use {@link #checkpointMemWal} to wait for convergence.
|
||||
* #getRTEStats}, or use {@link #checkpointRTE} to wait for convergence.
|
||||
*/
|
||||
public void compactMemWal() {
|
||||
client.post(route("compact_memwal"), null);
|
||||
public void compactRTE() {
|
||||
client.post(route("compact_rte"), null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read live per-table-shard MemWAL state.
|
||||
* Read live per-table-shard RTE state.
|
||||
*
|
||||
* <p>Answers "how far behind is my fresh tier", "which table shard is hot", and "why is my
|
||||
* fresh-tier vector search brute-force". Mutates no table state.
|
||||
*
|
||||
* <p>Empty only when the MemWAL write path is not enabled — that is, when the server sends an
|
||||
* absent or null {@code memwal_stats}. A stats object that is present is decoded strictly, and a
|
||||
* malformed one throws rather than decoding to something empty, because {@link #checkpointMemWal}
|
||||
* reads convergence out of these numbers and cannot tell a defaulted array from a drained one.
|
||||
* <p>Empty only when the RTE write path is not enabled — that is, when the server sends an absent
|
||||
* or null {@code rte_stats}. A stats object that is present is decoded strictly, and a malformed
|
||||
* one throws rather than decoding to something empty, because {@link #checkpointRTE} reads
|
||||
* convergence out of these numbers and cannot tell a defaulted array from a drained one.
|
||||
*
|
||||
* @param includeSstableRows Also count rows per SSTable. Off by default because each count opens
|
||||
* an uncached Lance dataset.
|
||||
* @throws IllegalStateException if the response is absent or does not decode.
|
||||
*/
|
||||
public Optional<MemWalStats> getMemWalStats(boolean includeSstableRows) {
|
||||
public Optional<RTEStats> getRTEStats(boolean includeSstableRows) {
|
||||
Map<String, Object> body = new LinkedHashMap<String, Object>();
|
||||
body.put("include_sstable_rows", includeSstableRows);
|
||||
JsonNode response = client.post(route("get_memwal_stats"), body);
|
||||
JsonNode response = client.post(route("get_rte_stats"), body);
|
||||
if (response == null) {
|
||||
throw new IllegalStateException("get_memwal_stats returned an empty response body");
|
||||
throw new IllegalStateException("get_rte_stats returned an empty response body");
|
||||
}
|
||||
JsonNode stats = response.get("memwal_stats");
|
||||
JsonNode stats = response.get("rte_stats");
|
||||
if (stats == null || stats.isNull()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(MemWalStats.fromJson(stats));
|
||||
return Optional.of(RTEStats.fromJson(stats));
|
||||
}
|
||||
|
||||
/** Equivalent to {@code getMemWalStats(false)}. */
|
||||
public Optional<MemWalStats> getMemWalStats() {
|
||||
return getMemWalStats(false);
|
||||
/** Equivalent to {@code getRTEStats(false)}. */
|
||||
public Optional<RTEStats> getRTEStats() {
|
||||
return getRTEStats(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converge this table's MemWAL write path into its base table.
|
||||
* Converge this table's RTE write path into its base table.
|
||||
*
|
||||
* <p>Freezes once, fixes a target watermark from the resulting SSTables, then triggers compaction
|
||||
* and polls until those SSTables are gone. The target set is fixed at the start, so sstables
|
||||
@@ -196,31 +196,31 @@ public class LanceDbTableMemWal {
|
||||
* load, and what makes it best-effort: it converges the fresh tier as of some instant.
|
||||
* Idempotent, abandonable at any point, safe on a cadence.
|
||||
*
|
||||
* <p>The loop runs here, not on the server: {@link #compactMemWal} dispatches a pass and returns,
|
||||
* so nothing holds a socket and a client can vanish mid-operation with nothing to reconcile.
|
||||
* <p>The loop runs here, not on the server: {@link #compactRTE} dispatches a pass and returns, so
|
||||
* nothing holds a socket and a client can vanish mid-operation with nothing to reconcile.
|
||||
* Completion is read from generation numbers in the shard manifest — durable state, unlike a
|
||||
* count in a compact response, which a concurrent write invalidates.
|
||||
*
|
||||
* <p>No liveness bound — the caller owns the deadline. The compactor pool is shared across
|
||||
* tables, so a checkpoint queued behind unrelated work looks exactly like one that is merging.
|
||||
*/
|
||||
public void checkpointMemWal() {
|
||||
public void checkpointRTE() {
|
||||
for (int reissue = 0; reissue <= MAX_REISSUES; reissue++) {
|
||||
// The freeze turns everything written before this call into an SSTable, so the
|
||||
// watermark has to be read after it. Idempotent: freezing an empty memtable is a
|
||||
// no-op, so a re-issue does not churn empty sstables.
|
||||
if (issueVoid(this::flushMemWal)) {
|
||||
if (issueVoid(this::flushRTE)) {
|
||||
backoff(reissue);
|
||||
continue;
|
||||
}
|
||||
|
||||
Attempt<Optional<MemWalStats>> stats = issue(() -> getMemWalStats(false));
|
||||
Attempt<Optional<RTEStats>> stats = issue(() -> getRTEStats(false));
|
||||
if (stats.lostClaim) {
|
||||
backoff(reissue);
|
||||
continue;
|
||||
}
|
||||
if (!stats.value.isPresent()) {
|
||||
// Not WAL-backed; flushMemWal would have errored first but for a race.
|
||||
// Not WAL-backed; flushRTE would have errored first but for a race.
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -235,7 +235,7 @@ public class LanceDbTableMemWal {
|
||||
backoff(reissue);
|
||||
}
|
||||
throw new IllegalStateException(
|
||||
"checkpointMemWal: the owning node kept losing its claim; re-issued from flush the maximum "
|
||||
"checkpointRTE: the owning node kept losing its claim; re-issued from flush the maximum "
|
||||
+ "number of times");
|
||||
}
|
||||
|
||||
@@ -246,7 +246,7 @@ public class LanceDbTableMemWal {
|
||||
*/
|
||||
private boolean drainToTargets(Map<String, Long> targets) {
|
||||
while (true) {
|
||||
Attempt<Optional<MemWalStats>> stats = issue(() -> getMemWalStats(false));
|
||||
Attempt<Optional<RTEStats>> stats = issue(() -> getRTEStats(false));
|
||||
if (stats.lostClaim) {
|
||||
return false;
|
||||
}
|
||||
@@ -277,7 +277,7 @@ public class LanceDbTableMemWal {
|
||||
|
||||
if (!allCompacting) {
|
||||
try {
|
||||
compactMemWal();
|
||||
compactRTE();
|
||||
} catch (LanceDbRestClient.HttpException e) {
|
||||
if (isLostClaim(e)) {
|
||||
return false;
|
||||
@@ -296,7 +296,7 @@ public class LanceDbTableMemWal {
|
||||
}
|
||||
|
||||
/** The newest SSTable generation held by each table shard, skipping table shards holding none. */
|
||||
private static Map<String, Long> newestSstableGenerations(MemWalStats stats) {
|
||||
private static Map<String, Long> newestSstableGenerations(RTEStats stats) {
|
||||
Map<String, Long> targets = new HashMap<String, Long>();
|
||||
for (TableShardStats tableShard : stats.tableShards()) {
|
||||
OptionalLong newest = tableShard.newestSstableGeneration();
|
||||
+7
-7
@@ -20,18 +20,18 @@ import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Live per-table-shard MemWAL state, as returned by {@link LanceDbTableMemWal#getMemWalStats()}.
|
||||
* Live per-table-shard RTE state, as returned by {@link LanceDbTableRTE#getRTEStats()}.
|
||||
*
|
||||
* <p>Nothing here is derived: sums and differences (total SSTable bytes, WAL lag) are the caller's
|
||||
* to compute. There is no "LSM is off" shape — that case is an empty {@link java.util.Optional},
|
||||
* because a stats object of zeros would read as measurements.
|
||||
*/
|
||||
public class MemWalStats {
|
||||
private static final String CONTEXT = "memwal stats";
|
||||
public class RTEStats {
|
||||
private static final String CONTEXT = "rte stats";
|
||||
|
||||
private final List<TableShardStats> tableShards;
|
||||
|
||||
MemWalStats(List<TableShardStats> tableShards) {
|
||||
RTEStats(List<TableShardStats> tableShards) {
|
||||
this.tableShards = Collections.unmodifiableList(tableShards);
|
||||
}
|
||||
|
||||
@@ -40,17 +40,17 @@ public class MemWalStats {
|
||||
return tableShards;
|
||||
}
|
||||
|
||||
static MemWalStats fromJson(JsonNode node) {
|
||||
static RTEStats fromJson(JsonNode node) {
|
||||
JsonFields.requiredObject(node, CONTEXT);
|
||||
List<TableShardStats> tableShards = new ArrayList<TableShardStats>();
|
||||
for (JsonNode tableShard : JsonFields.requiredArray(node, "table_shards", CONTEXT)) {
|
||||
tableShards.add(TableShardStats.fromJson(tableShard));
|
||||
}
|
||||
return new MemWalStats(tableShards);
|
||||
return new RTEStats(tableShards);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MemWalStats{tableShards=" + tableShards + "}";
|
||||
return "RTEStats{tableShards=" + tableShards + "}";
|
||||
}
|
||||
}
|
||||
+26
-26
@@ -23,22 +23,23 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Specification selecting Lance's MemWAL LSM-style write path for {@code mergeInsert}.
|
||||
* Specification enabling the realtime engine (RTE), which routes {@code mergeInsert} through
|
||||
* Lance's MemWAL LSM-style write path.
|
||||
*
|
||||
* <p>Construct via {@link #bucket}, {@link #identity}, or {@link #unsharded}, then optionally chain
|
||||
* {@link #withMaintainedIndexes} and {@link #withWriterConfigDefaults}. Install it with {@link
|
||||
* LanceDbTableMemWal#enableMemWal} and remove it with {@link LanceDbTableMemWal#disableMemWal}.
|
||||
* LanceDbTableRTE#enableRTE} and remove it with {@link LanceDbTableRTE#disableRTE}.
|
||||
*
|
||||
* <p>This is deliberately not {@code org.lance.memwal.InitializeMemWalParams}. That type is Lance's
|
||||
* own, and its maintained-index default is the opposite of this one: it defaults to maintaining
|
||||
* <em>nothing</em>, while a fresh spec here maintains <em>every</em> index. It also cannot express
|
||||
* the null that asks the server to resolve the set.
|
||||
*/
|
||||
public class MemWalWriteSpec {
|
||||
public class RTEWriteSpec {
|
||||
|
||||
private static final String CONTEXT = "get_memwal_spec response";
|
||||
private static final String CONTEXT = "get_rte_spec response";
|
||||
|
||||
/** How writes are routed to MemWAL shards. */
|
||||
/** How writes are routed to RTE shards. */
|
||||
public enum Sharding {
|
||||
/** Hash-bucket writes by a scalar column. */
|
||||
BUCKET("bucket"),
|
||||
@@ -73,7 +74,7 @@ public class MemWalWriteSpec {
|
||||
private final List<String> maintainedIndexes;
|
||||
private final Map<String, String> writerConfigDefaults;
|
||||
|
||||
private MemWalWriteSpec(
|
||||
private RTEWriteSpec(
|
||||
Sharding sharding,
|
||||
String column,
|
||||
Integer numBuckets,
|
||||
@@ -95,11 +96,11 @@ public class MemWalWriteSpec {
|
||||
* @param column A non-nested column with a supported scalar type.
|
||||
* @param numBuckets The number of buckets, in {@code [1, 1024]}.
|
||||
*/
|
||||
public static MemWalWriteSpec bucket(String column, int numBuckets) {
|
||||
public static RTEWriteSpec bucket(String column, int numBuckets) {
|
||||
if (column == null || column.trim().isEmpty()) {
|
||||
throw new IllegalArgumentException("Column cannot be null or empty");
|
||||
}
|
||||
return new MemWalWriteSpec(
|
||||
return new RTEWriteSpec(
|
||||
Sharding.BUCKET, column, numBuckets, null, new HashMap<String, String>());
|
||||
}
|
||||
|
||||
@@ -111,29 +112,28 @@ public class MemWalWriteSpec {
|
||||
* with a given primary key must always produce the same {@code column} value, or upserts of that
|
||||
* key can land in different shards and a stale version can win.
|
||||
*/
|
||||
public static MemWalWriteSpec identity(String column) {
|
||||
public static RTEWriteSpec identity(String column) {
|
||||
if (column == null || column.trim().isEmpty()) {
|
||||
throw new IllegalArgumentException("Column cannot be null or empty");
|
||||
}
|
||||
return new MemWalWriteSpec(
|
||||
Sharding.IDENTITY, column, null, null, new HashMap<String, String>());
|
||||
return new RTEWriteSpec(Sharding.IDENTITY, column, null, null, new HashMap<String, String>());
|
||||
}
|
||||
|
||||
/** No sharding — every write goes to a single MemWAL shard — maintaining every index. */
|
||||
public static MemWalWriteSpec unsharded() {
|
||||
return new MemWalWriteSpec(Sharding.UNSHARDED, null, null, null, new HashMap<String, String>());
|
||||
/** No sharding — every write goes to a single RTE shard — maintaining every index. */
|
||||
public static RTEWriteSpec unsharded() {
|
||||
return new RTEWriteSpec(Sharding.UNSHARDED, null, null, null, new HashMap<String, String>());
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the indexes the MemWAL keeps up to date as rows are appended.
|
||||
* Set the indexes the RTE keeps up to date as rows are appended.
|
||||
*
|
||||
* <p>Pass {@code null} — the default for a fresh spec — to maintain every index the table has,
|
||||
* including ones created later. Pass an empty list to maintain none.
|
||||
*
|
||||
* <p>Note that {@code null} and the empty list mean opposite things here.
|
||||
*/
|
||||
public MemWalWriteSpec withMaintainedIndexes(List<String> maintainedIndexes) {
|
||||
return new MemWalWriteSpec(
|
||||
public RTEWriteSpec withMaintainedIndexes(List<String> maintainedIndexes) {
|
||||
return new RTEWriteSpec(
|
||||
sharding,
|
||||
column,
|
||||
numBuckets,
|
||||
@@ -150,11 +150,11 @@ public class MemWalWriteSpec {
|
||||
* max_unflushed_memtable_bytes}, and {@code enable_memtable}. Duration knobs carry an {@code _ms}
|
||||
* suffix, such as {@code max_wal_flush_interval_ms}.
|
||||
*/
|
||||
public MemWalWriteSpec withWriterConfigDefaults(Map<String, String> writerConfigDefaults) {
|
||||
public RTEWriteSpec withWriterConfigDefaults(Map<String, String> writerConfigDefaults) {
|
||||
if (writerConfigDefaults == null) {
|
||||
throw new IllegalArgumentException("writerConfigDefaults cannot be null");
|
||||
}
|
||||
return new MemWalWriteSpec(
|
||||
return new RTEWriteSpec(
|
||||
sharding,
|
||||
column,
|
||||
numBuckets,
|
||||
@@ -178,7 +178,7 @@ public class MemWalWriteSpec {
|
||||
}
|
||||
|
||||
/**
|
||||
* Which indexes the MemWAL maintains.
|
||||
* Which indexes the RTE maintains.
|
||||
*
|
||||
* <p>Null selects automatically: every supported index the table has now or gains later. An empty
|
||||
* list maintains none. A non-empty list maintains exactly those.
|
||||
@@ -192,7 +192,7 @@ public class MemWalWriteSpec {
|
||||
return Collections.unmodifiableMap(writerConfigDefaults);
|
||||
}
|
||||
|
||||
/** Render this spec as the {@code enable_memwal} request body. */
|
||||
/** Render this spec as the {@code enable_rte} request body. */
|
||||
Map<String, Object> toRequestBody() {
|
||||
Map<String, Object> shardingBody = new LinkedHashMap<String, Object>();
|
||||
shardingBody.put("mode", sharding.wireName());
|
||||
@@ -212,15 +212,15 @@ public class MemWalWriteSpec {
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuild a spec from a {@code get_memwal_spec} response body.
|
||||
* Rebuild a spec from a {@code get_rte_spec} response body.
|
||||
*
|
||||
* <p>A null {@code maintained_indexes} selects every index the table has; an empty list selects
|
||||
* none.
|
||||
*/
|
||||
static MemWalWriteSpec fromJson(JsonNode node) {
|
||||
static RTEWriteSpec fromJson(JsonNode node) {
|
||||
JsonNode shardingNode = node.get("sharding");
|
||||
if (shardingNode == null || shardingNode.get("mode") == null) {
|
||||
throw new IllegalStateException("get_memwal_spec response has no sharding mode");
|
||||
throw new IllegalStateException("get_rte_spec response has no sharding mode");
|
||||
}
|
||||
Sharding sharding = Sharding.fromWireName(shardingNode.get("mode").asText());
|
||||
|
||||
@@ -253,12 +253,12 @@ public class MemWalWriteSpec {
|
||||
.forEachRemaining(name -> defaults.put(name, defaultsNode.get(name).asText()));
|
||||
}
|
||||
|
||||
return new MemWalWriteSpec(sharding, column, numBuckets, maintainedIndexes, defaults);
|
||||
return new RTEWriteSpec(sharding, column, numBuckets, maintainedIndexes, defaults);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MemWalWriteSpec{sharding="
|
||||
return "RTEWriteSpec{sharding="
|
||||
+ sharding
|
||||
+ ", column="
|
||||
+ column
|
||||
+129
-133
@@ -41,17 +41,17 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Unit tests for the MemWAL LSM routes, run against a scripted local HTTP server.
|
||||
* Unit tests for the RTE LSM routes, run against a scripted local HTTP server.
|
||||
*
|
||||
* <p>The wire assertions mirror the Rust mocked-endpoint tests in {@code
|
||||
* rust/lancedb/src/remote/table.rs}, which are the contract these routes have to match.
|
||||
*/
|
||||
public class LanceDbTableMemWalTest {
|
||||
public class LanceDbTableRTETest {
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private HttpServer server;
|
||||
private LanceDbRestClient client;
|
||||
private LanceDbTableMemWal memWal;
|
||||
private LanceDbTableRTE rte;
|
||||
|
||||
private final List<String> requestPaths = Collections.synchronizedList(new ArrayList<String>());
|
||||
private final List<String> requestBodies = Collections.synchronizedList(new ArrayList<String>());
|
||||
@@ -101,7 +101,7 @@ public class LanceDbTableMemWalTest {
|
||||
.database("test-db")
|
||||
.endpoint("http://127.0.0.1:" + server.getAddress().getPort())
|
||||
.buildRestClient();
|
||||
memWal = new LanceDbTableMemWal(client, "my_table");
|
||||
rte = new LanceDbTableRTE(client, "my_table");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
@@ -115,12 +115,12 @@ public class LanceDbTableMemWalTest {
|
||||
// ===========================================================================
|
||||
|
||||
@Test
|
||||
public void testEnableMemWalUnsharded() throws Exception {
|
||||
enqueue("enable_memwal", 200, "");
|
||||
public void testEnableRTEUnsharded() throws Exception {
|
||||
enqueue("enable_rte", 200, "");
|
||||
|
||||
memWal.enableMemWal(MemWalWriteSpec.unsharded());
|
||||
rte.enableRTE(RTEWriteSpec.unsharded());
|
||||
|
||||
assertEquals("/v1/table/my_table/enable_memwal/", requestPaths.get(0));
|
||||
assertEquals("/v1/table/my_table/enable_rte/", requestPaths.get(0));
|
||||
JsonNode body = MAPPER.readTree(requestBodies.get(0));
|
||||
assertEquals("unsharded", body.get("sharding").get("mode").asText());
|
||||
assertFalse(body.get("sharding").has("column"));
|
||||
@@ -128,11 +128,10 @@ public class LanceDbTableMemWalTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEnableMemWalBucket() throws Exception {
|
||||
enqueue("enable_memwal", 200, "");
|
||||
public void testEnableRTEBucket() throws Exception {
|
||||
enqueue("enable_rte", 200, "");
|
||||
|
||||
memWal.enableMemWal(
|
||||
MemWalWriteSpec.bucket("id", 16).withMaintainedIndexes(Arrays.asList("id_idx")));
|
||||
rte.enableRTE(RTEWriteSpec.bucket("id", 16).withMaintainedIndexes(Arrays.asList("id_idx")));
|
||||
|
||||
JsonNode body = MAPPER.readTree(requestBodies.get(0));
|
||||
assertEquals("bucket", body.get("sharding").get("mode").asText());
|
||||
@@ -143,10 +142,10 @@ public class LanceDbTableMemWalTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEnableMemWalIdentity() throws Exception {
|
||||
enqueue("enable_memwal", 200, "");
|
||||
public void testEnableRTEIdentity() throws Exception {
|
||||
enqueue("enable_rte", 200, "");
|
||||
|
||||
memWal.enableMemWal(MemWalWriteSpec.identity("tenant"));
|
||||
rte.enableRTE(RTEWriteSpec.identity("tenant"));
|
||||
|
||||
JsonNode body = MAPPER.readTree(requestBodies.get(0));
|
||||
assertEquals("identity", body.get("sharding").get("mode").asText());
|
||||
@@ -160,55 +159,54 @@ public class LanceDbTableMemWalTest {
|
||||
*/
|
||||
@Test
|
||||
public void testMaintainedIndexesNullAndEmptyAreDistinctOnTheWire() throws Exception {
|
||||
enqueue("enable_memwal", 200, "");
|
||||
enqueue("enable_rte", 200, "");
|
||||
|
||||
memWal.enableMemWal(MemWalWriteSpec.unsharded());
|
||||
rte.enableRTE(RTEWriteSpec.unsharded());
|
||||
JsonNode fresh = MAPPER.readTree(requestBodies.get(0));
|
||||
assertTrue(fresh.has("maintained_indexes"), "the key must be present");
|
||||
assertTrue(fresh.get("maintained_indexes").isNull(), "a fresh spec sends null, not []");
|
||||
|
||||
memWal.enableMemWal(
|
||||
MemWalWriteSpec.unsharded().withMaintainedIndexes(Collections.<String>emptyList()));
|
||||
rte.enableRTE(RTEWriteSpec.unsharded().withMaintainedIndexes(Collections.<String>emptyList()));
|
||||
JsonNode none = MAPPER.readTree(requestBodies.get(1));
|
||||
assertTrue(none.get("maintained_indexes").isArray());
|
||||
assertEquals(0, none.get("maintained_indexes").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEnableMemWalWriterConfigDefaults() throws Exception {
|
||||
enqueue("enable_memwal", 200, "");
|
||||
public void testEnableRTEWriterConfigDefaults() throws Exception {
|
||||
enqueue("enable_rte", 200, "");
|
||||
|
||||
Map<String, String> defaults = new HashMap<String, String>();
|
||||
defaults.put("max_memtable_rows", "50000");
|
||||
memWal.enableMemWal(MemWalWriteSpec.unsharded().withWriterConfigDefaults(defaults));
|
||||
rte.enableRTE(RTEWriteSpec.unsharded().withWriterConfigDefaults(defaults));
|
||||
|
||||
JsonNode body = MAPPER.readTree(requestBodies.get(0));
|
||||
assertEquals("50000", body.get("writer_config_defaults").get("max_memtable_rows").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDisableMemWal() {
|
||||
enqueue("disable_memwal", 200, "");
|
||||
public void testDisableRTE() {
|
||||
enqueue("disable_rte", 200, "");
|
||||
|
||||
memWal.disableMemWal();
|
||||
rte.disableRTE();
|
||||
|
||||
assertEquals("/v1/table/my_table/disable_memwal/", requestPaths.get(0));
|
||||
assertEquals("/v1/table/my_table/disable_rte/", requestPaths.get(0));
|
||||
assertEquals("", requestBodies.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetMemWalSpec() {
|
||||
public void testGetRTESpec() {
|
||||
enqueue(
|
||||
"get_memwal_spec",
|
||||
"get_rte_spec",
|
||||
200,
|
||||
"{\"memwal_spec\":{\"sharding\":{\"mode\":\"bucket\",\"column\":\"id\","
|
||||
"{\"rte_spec\":{\"sharding\":{\"mode\":\"bucket\",\"column\":\"id\","
|
||||
+ "\"num_buckets\":16},\"maintained_indexes\":[\"id_idx\"],"
|
||||
+ "\"writer_config_defaults\":{\"durable_write\":\"true\"}}}");
|
||||
|
||||
Optional<MemWalWriteSpec> spec = memWal.getMemWalSpec();
|
||||
Optional<RTEWriteSpec> spec = rte.getRTESpec();
|
||||
|
||||
assertTrue(spec.isPresent());
|
||||
assertEquals(MemWalWriteSpec.Sharding.BUCKET, spec.get().sharding());
|
||||
assertEquals(RTEWriteSpec.Sharding.BUCKET, spec.get().sharding());
|
||||
assertEquals("id", spec.get().column());
|
||||
assertEquals(Integer.valueOf(16), spec.get().numBuckets());
|
||||
assertEquals(Arrays.asList("id_idx"), spec.get().maintainedIndexes());
|
||||
@@ -217,28 +215,28 @@ public class LanceDbTableMemWalTest {
|
||||
|
||||
/** A null selection, every index the table has, reads back as null rather than an empty list. */
|
||||
@Test
|
||||
public void testGetMemWalSpecRoundTripsEveryIndexSelection() {
|
||||
public void testGetRTESpecRoundTripsEveryIndexSelection() {
|
||||
enqueue(
|
||||
"get_memwal_spec",
|
||||
"get_rte_spec",
|
||||
200,
|
||||
"{\"memwal_spec\":{\"sharding\":{\"mode\":\"unsharded\"},"
|
||||
"{\"rte_spec\":{\"sharding\":{\"mode\":\"unsharded\"},"
|
||||
+ "\"maintained_indexes\":null,\"writer_config_defaults\":{}}}");
|
||||
|
||||
Optional<MemWalWriteSpec> spec = memWal.getMemWalSpec();
|
||||
Optional<RTEWriteSpec> spec = rte.getRTESpec();
|
||||
|
||||
assertTrue(spec.isPresent());
|
||||
assertNull(spec.get().maintainedIndexes());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetMemWalSpecRoundTripsNoIndexSelection() {
|
||||
public void testGetRTESpecRoundTripsNoIndexSelection() {
|
||||
enqueue(
|
||||
"get_memwal_spec",
|
||||
"get_rte_spec",
|
||||
200,
|
||||
"{\"memwal_spec\":{\"sharding\":{\"mode\":\"unsharded\"},"
|
||||
"{\"rte_spec\":{\"sharding\":{\"mode\":\"unsharded\"},"
|
||||
+ "\"maintained_indexes\":[],\"writer_config_defaults\":{}}}");
|
||||
|
||||
Optional<MemWalWriteSpec> spec = memWal.getMemWalSpec();
|
||||
Optional<RTEWriteSpec> spec = rte.getRTESpec();
|
||||
|
||||
assertTrue(spec.isPresent());
|
||||
assertEquals(Collections.emptyList(), spec.get().maintainedIndexes());
|
||||
@@ -249,32 +247,32 @@ public class LanceDbTableMemWalTest {
|
||||
* rejected: reading a string or an object as null would turn a malformed response into a policy.
|
||||
*/
|
||||
@Test
|
||||
public void testGetMemWalSpecRejectsANonArrayMaintainedIndexes() {
|
||||
public void testGetRTESpecRejectsANonArrayMaintainedIndexes() {
|
||||
enqueue(
|
||||
"get_memwal_spec",
|
||||
"get_rte_spec",
|
||||
200,
|
||||
"{\"memwal_spec\":{\"sharding\":{\"mode\":\"unsharded\"},"
|
||||
"{\"rte_spec\":{\"sharding\":{\"mode\":\"unsharded\"},"
|
||||
+ "\"maintained_indexes\":\"id_idx\",\"writer_config_defaults\":{}}}");
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> memWal.getMemWalSpec());
|
||||
assertThrows(IllegalStateException.class, () -> rte.getRTESpec());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetMemWalSpecRejectsNonStringIndexNames() {
|
||||
public void testGetRTESpecRejectsNonStringIndexNames() {
|
||||
enqueue(
|
||||
"get_memwal_spec",
|
||||
"get_rte_spec",
|
||||
200,
|
||||
"{\"memwal_spec\":{\"sharding\":{\"mode\":\"unsharded\"},"
|
||||
"{\"rte_spec\":{\"sharding\":{\"mode\":\"unsharded\"},"
|
||||
+ "\"maintained_indexes\":[7],\"writer_config_defaults\":{}}}");
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> memWal.getMemWalSpec());
|
||||
assertThrows(IllegalStateException.class, () -> rte.getRTESpec());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetMemWalSpecAbsent() {
|
||||
enqueue("get_memwal_spec", 200, "{\"memwal_spec\":null}");
|
||||
public void testGetRTESpecAbsent() {
|
||||
enqueue("get_rte_spec", 200, "{\"rte_spec\":null}");
|
||||
|
||||
assertFalse(memWal.getMemWalSpec().isPresent());
|
||||
assertFalse(rte.getRTESpec().isPresent());
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
@@ -282,12 +280,12 @@ public class LanceDbTableMemWalTest {
|
||||
// ===========================================================================
|
||||
|
||||
@Test
|
||||
public void testGetMemWalStats() throws Exception {
|
||||
enqueue("get_memwal_stats", 200, stats(tableShard("shard-0", false, 7L, 8L)));
|
||||
public void testGetRTEStats() throws Exception {
|
||||
enqueue("get_rte_stats", 200, stats(tableShard("shard-0", false, 7L, 8L)));
|
||||
|
||||
Optional<MemWalStats> got = memWal.getMemWalStats(true);
|
||||
Optional<RTEStats> got = rte.getRTEStats(true);
|
||||
|
||||
assertEquals("/v1/table/my_table/get_memwal_stats/", requestPaths.get(0));
|
||||
assertEquals("/v1/table/my_table/get_rte_stats/", requestPaths.get(0));
|
||||
assertTrue(MAPPER.readTree(requestBodies.get(0)).get("include_sstable_rows").asBoolean());
|
||||
assertTrue(got.isPresent());
|
||||
TableShardStats decoded = got.get().tableShards().get(0);
|
||||
@@ -305,18 +303,18 @@ public class LanceDbTableMemWalTest {
|
||||
|
||||
/** The optional fields decode when the server does send them. */
|
||||
@Test
|
||||
public void testGetMemWalStatsDecodesOptionalFields() {
|
||||
public void testGetRTEStatsDecodesOptionalFields() {
|
||||
enqueue(
|
||||
"get_memwal_stats",
|
||||
"get_rte_stats",
|
||||
200,
|
||||
"{\"memwal_stats\":{\"table_shards\":[{\"shard_id\":\"shard-0\",\"status\":\"Active\","
|
||||
"{\"rte_stats\":{\"table_shards\":[{\"shard_id\":\"shard-0\",\"status\":\"Active\","
|
||||
+ "\"writer_epoch\":1,\"manifest_version\":2,\"current_generation\":9,"
|
||||
+ "\"replay_after_wal_entry_position\":3,\"wal_entry_position_last_seen\":11,"
|
||||
+ "\"sstables\":[{\"generation\":7,\"bytes\":1024,\"rows\":42}],"
|
||||
+ "\"compacting\":true,\"memtables\":[{\"generation\":8,\"rows\":5,"
|
||||
+ "\"bytes\":64,\"batches\":2,\"indexes\":[\"id_idx\"]}]}]}}");
|
||||
|
||||
TableShardStats decoded = memWal.getMemWalStats(true).get().tableShards().get(0);
|
||||
TableShardStats decoded = rte.getRTEStats(true).get().tableShards().get(0);
|
||||
|
||||
assertEquals(3, decoded.replayAfterWalEntryPosition());
|
||||
assertEquals(11, decoded.walEntryPositionLastSeen());
|
||||
@@ -332,17 +330,17 @@ public class LanceDbTableMemWalTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetMemWalStatsAbsentWhenMemWalDisabled() {
|
||||
enqueue("get_memwal_stats", 200, "{\"memwal_stats\":null}");
|
||||
public void testGetRTEStatsAbsentWhenRTEDisabled() {
|
||||
enqueue("get_rte_stats", 200, "{\"rte_stats\":null}");
|
||||
|
||||
assertFalse(memWal.getMemWalStats().isPresent());
|
||||
assertFalse(rte.getRTEStats().isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetMemWalStatsDefaultsToExcludingGenerationRows() throws Exception {
|
||||
enqueue("get_memwal_stats", 200, stats());
|
||||
public void testGetRTEStatsDefaultsToExcludingGenerationRows() throws Exception {
|
||||
enqueue("get_rte_stats", 200, stats());
|
||||
|
||||
memWal.getMemWalStats();
|
||||
rte.getRTEStats();
|
||||
|
||||
assertFalse(MAPPER.readTree(requestBodies.get(0)).get("include_sstable_rows").asBoolean());
|
||||
}
|
||||
@@ -353,22 +351,22 @@ public class LanceDbTableMemWalTest {
|
||||
|
||||
@Test
|
||||
public void testFlushAndCompactRoutes() {
|
||||
enqueue("flush_memwal", 200, "");
|
||||
enqueue("compact_memwal", 200, "");
|
||||
enqueue("flush_rte", 200, "");
|
||||
enqueue("compact_rte", 200, "");
|
||||
|
||||
memWal.flushMemWal();
|
||||
memWal.compactMemWal();
|
||||
rte.flushRTE();
|
||||
rte.compactRTE();
|
||||
|
||||
assertEquals("/v1/table/my_table/flush_memwal/", requestPaths.get(0));
|
||||
assertEquals("/v1/table/my_table/compact_memwal/", requestPaths.get(1));
|
||||
assertEquals("/v1/table/my_table/flush_rte/", requestPaths.get(0));
|
||||
assertEquals("/v1/table/my_table/compact_rte/", requestPaths.get(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpErrorCarriesStatus() {
|
||||
enqueue("flush_memwal", 404, "no such table");
|
||||
enqueue("flush_rte", 404, "no such table");
|
||||
|
||||
LanceDbRestClient.HttpException e =
|
||||
assertThrows(LanceDbRestClient.HttpException.class, () -> memWal.flushMemWal());
|
||||
assertThrows(LanceDbRestClient.HttpException.class, () -> rte.flushRTE());
|
||||
assertEquals(404, e.statusCode());
|
||||
}
|
||||
|
||||
@@ -377,98 +375,97 @@ public class LanceDbTableMemWalTest {
|
||||
// ===========================================================================
|
||||
|
||||
@Test
|
||||
public void testCheckpointReturnsWhenMemWalDisabled() {
|
||||
enqueue("flush_memwal", 200, "");
|
||||
enqueue("get_memwal_stats", 200, "{\"memwal_stats\":null}");
|
||||
public void testCheckpointReturnsWhenRTEDisabled() {
|
||||
enqueue("flush_rte", 200, "");
|
||||
enqueue("get_rte_stats", 200, "{\"rte_stats\":null}");
|
||||
|
||||
memWal.checkpointMemWal();
|
||||
rte.checkpointRTE();
|
||||
|
||||
assertEquals(0, countCalls("compact_memwal"), "nothing to compact when the LSM path is off");
|
||||
assertEquals(0, countCalls("compact_rte"), "nothing to compact when the LSM path is off");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCheckpointReturnsWhenNoGenerationsOutstanding() {
|
||||
enqueue("flush_memwal", 200, "");
|
||||
enqueue("flush_rte", 200, "");
|
||||
// A table shard with no SSTables yields no target, so the drain never starts.
|
||||
enqueue("get_memwal_stats", 200, stats(tableShard("shard-0", false)));
|
||||
enqueue("get_rte_stats", 200, stats(tableShard("shard-0", false)));
|
||||
|
||||
memWal.checkpointMemWal();
|
||||
rte.checkpointRTE();
|
||||
|
||||
assertEquals(0, countCalls("compact_memwal"));
|
||||
assertEquals(0, countCalls("compact_rte"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCheckpointConvergesOnceTargetGenerationsAreGone() {
|
||||
enqueue("flush_memwal", 200, "");
|
||||
enqueue("flush_rte", 200, "");
|
||||
// Watermark read: shard-0 holds sstables 7 and 8, so target = 8.
|
||||
enqueue("get_memwal_stats", 200, stats(tableShard("shard-0", false, 7L, 8L)));
|
||||
enqueue("get_rte_stats", 200, stats(tableShard("shard-0", false, 7L, 8L)));
|
||||
// First drain poll: both still outstanding, nothing compacting -> dispatch a pass.
|
||||
enqueue("get_memwal_stats", 200, stats(tableShard("shard-0", false, 7L, 8L)));
|
||||
enqueue("get_rte_stats", 200, stats(tableShard("shard-0", false, 7L, 8L)));
|
||||
// Second drain poll: drained past the target -> done.
|
||||
enqueue("get_memwal_stats", 200, stats(tableShard("shard-0", false, 9L)));
|
||||
enqueue("compact_memwal", 200, "");
|
||||
enqueue("get_rte_stats", 200, stats(tableShard("shard-0", false, 9L)));
|
||||
enqueue("compact_rte", 200, "");
|
||||
|
||||
memWal.checkpointMemWal();
|
||||
rte.checkpointRTE();
|
||||
|
||||
assertEquals(1, countCalls("compact_memwal"), "one pass dispatched");
|
||||
assertEquals(3, countCalls("get_memwal_stats"), "watermark read plus two drain polls");
|
||||
assertEquals(1, countCalls("compact_rte"), "one pass dispatched");
|
||||
assertEquals(3, countCalls("get_rte_stats"), "watermark read plus two drain polls");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCheckpointDoesNotPileOnWhileEveryTargetBucketIsCompacting() {
|
||||
enqueue("flush_memwal", 200, "");
|
||||
enqueue("get_memwal_stats", 200, stats(tableShard("shard-0", true, 4L)));
|
||||
enqueue("flush_rte", 200, "");
|
||||
enqueue("get_rte_stats", 200, stats(tableShard("shard-0", true, 4L)));
|
||||
// Still compacting on the first poll, so no pass is dispatched; then it drains.
|
||||
enqueue("get_memwal_stats", 200, stats(tableShard("shard-0", true, 4L)));
|
||||
enqueue("get_memwal_stats", 200, stats(tableShard("shard-0", false, 5L)));
|
||||
enqueue("get_rte_stats", 200, stats(tableShard("shard-0", true, 4L)));
|
||||
enqueue("get_rte_stats", 200, stats(tableShard("shard-0", false, 5L)));
|
||||
|
||||
memWal.checkpointMemWal();
|
||||
rte.checkpointRTE();
|
||||
|
||||
assertEquals(0, countCalls("compact_memwal"), "a latched table shard is left alone");
|
||||
assertEquals(0, countCalls("compact_rte"), "a latched table shard is left alone");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCheckpointRetriesFromFlushAfterLostClaim() {
|
||||
// 421 on the watermark read: the node lost its claim, so the whole thing restarts
|
||||
// from flush rather than retrying the read in place.
|
||||
enqueue("flush_memwal", 200, "");
|
||||
enqueue("get_memwal_stats", 421, "no claim");
|
||||
enqueue("get_memwal_stats", 200, stats(tableShard("shard-0", false)));
|
||||
enqueue("flush_rte", 200, "");
|
||||
enqueue("get_rte_stats", 421, "no claim");
|
||||
enqueue("get_rte_stats", 200, stats(tableShard("shard-0", false)));
|
||||
|
||||
memWal.checkpointMemWal();
|
||||
rte.checkpointRTE();
|
||||
|
||||
assertEquals(2, countCalls("flush_memwal"), "re-issued from flush");
|
||||
assertEquals(2, countCalls("flush_rte"), "re-issued from flush");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCheckpointRetriesRetryableStatusInPlace() {
|
||||
enqueue("flush_memwal", 429, "latch held");
|
||||
enqueue("flush_memwal", 200, "");
|
||||
enqueue("get_memwal_stats", 200, stats(tableShard("shard-0", false)));
|
||||
enqueue("flush_rte", 429, "latch held");
|
||||
enqueue("flush_rte", 200, "");
|
||||
enqueue("get_rte_stats", 200, stats(tableShard("shard-0", false)));
|
||||
|
||||
memWal.checkpointMemWal();
|
||||
rte.checkpointRTE();
|
||||
|
||||
assertEquals(2, countCalls("flush_memwal"), "429 retried in place, not re-issued");
|
||||
assertEquals(2, countCalls("flush_rte"), "429 retried in place, not re-issued");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCheckpointPropagatesTerminalStatus() {
|
||||
enqueue("flush_memwal", 400, "bad request");
|
||||
enqueue("flush_rte", 400, "bad request");
|
||||
|
||||
LanceDbRestClient.HttpException e =
|
||||
assertThrows(LanceDbRestClient.HttpException.class, () -> memWal.checkpointMemWal());
|
||||
assertThrows(LanceDbRestClient.HttpException.class, () -> rte.checkpointRTE());
|
||||
assertEquals(400, e.statusCode());
|
||||
assertEquals(1, countCalls("flush_memwal"), "a terminal status is not retried");
|
||||
assertEquals(1, countCalls("flush_rte"), "a terminal status is not retried");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCheckpointGivesUpAfterRepeatedLostClaims() {
|
||||
enqueue("flush_memwal", 421, "no claim");
|
||||
enqueue("flush_rte", 421, "no claim");
|
||||
|
||||
IllegalStateException e =
|
||||
assertThrows(IllegalStateException.class, () -> memWal.checkpointMemWal());
|
||||
IllegalStateException e = assertThrows(IllegalStateException.class, () -> rte.checkpointRTE());
|
||||
assertTrue(e.getMessage().contains("kept losing its claim"), e.getMessage());
|
||||
assertEquals(4, countCalls("flush_memwal"), "the initial attempt plus MAX_REISSUES");
|
||||
assertEquals(4, countCalls("flush_rte"), "the initial attempt plus MAX_REISSUES");
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
@@ -478,24 +475,24 @@ public class LanceDbTableMemWalTest {
|
||||
/**
|
||||
* A stats payload that does not decode must fail closed. Every one of these bodies used to be
|
||||
* read as "no table shards", which is indistinguishable from a drained table, so {@code
|
||||
* checkpointMemWal} reported convergence for a checkpoint that never ran.
|
||||
* checkpointRTE} reported convergence for a checkpoint that never ran.
|
||||
*/
|
||||
@Test
|
||||
public void testCheckpointRejectsMalformedStats() {
|
||||
Map<String, String> malformed = new LinkedHashMap<String, String>();
|
||||
malformed.put("no response body at all", "");
|
||||
malformed.put("stats object with no table shards", "{\"memwal_stats\":{}}");
|
||||
malformed.put("stats object with no table shards", "{\"rte_stats\":{}}");
|
||||
malformed.put(
|
||||
"table shard missing its required fields", "{\"memwal_stats\":{\"table_shards\":[{}]}}");
|
||||
"table shard missing its required fields", "{\"rte_stats\":{\"table_shards\":[{}]}}");
|
||||
malformed.put(
|
||||
"table shard missing sstables",
|
||||
"{\"memwal_stats\":{\"table_shards\":[{\"shard_id\":\"shard-0\",\"status\":\"Active\","
|
||||
"{\"rte_stats\":{\"table_shards\":[{\"shard_id\":\"shard-0\",\"status\":\"Active\","
|
||||
+ "\"writer_epoch\":1,\"manifest_version\":2,\"current_generation\":9,"
|
||||
+ "\"replay_after_wal_entry_position\":0,\"wal_entry_position_last_seen\":0,"
|
||||
+ "\"compacting\":false}]}}");
|
||||
malformed.put(
|
||||
"generation with a non-numeric generation number",
|
||||
"{\"memwal_stats\":{\"table_shards\":[{\"shard_id\":\"shard-0\",\"status\":\"Active\","
|
||||
"{\"rte_stats\":{\"table_shards\":[{\"shard_id\":\"shard-0\",\"status\":\"Active\","
|
||||
+ "\"writer_epoch\":1,\"manifest_version\":2,\"current_generation\":9,"
|
||||
+ "\"replay_after_wal_entry_position\":0,\"wal_entry_position_last_seen\":0,"
|
||||
+ "\"sstables\":[{\"generation\":\"7\",\"bytes\":1024}],"
|
||||
@@ -503,25 +500,25 @@ public class LanceDbTableMemWalTest {
|
||||
|
||||
for (Map.Entry<String, String> each : malformed.entrySet()) {
|
||||
setUpFresh();
|
||||
enqueue("flush_memwal", 200, "");
|
||||
enqueue("get_memwal_stats", 200, each.getValue());
|
||||
enqueue("flush_rte", 200, "");
|
||||
enqueue("get_rte_stats", 200, each.getValue());
|
||||
|
||||
assertThrows(
|
||||
IllegalStateException.class,
|
||||
() -> memWal.checkpointMemWal(),
|
||||
() -> rte.checkpointRTE(),
|
||||
each.getKey() + " must not report convergence");
|
||||
}
|
||||
}
|
||||
|
||||
/** The one shape that legitimately means "this table has no MemWAL write path". */
|
||||
/** The one shape that legitimately means "this table has no RTE write path". */
|
||||
@Test
|
||||
public void testCheckpointTreatsNullStatsAsNotWalBacked() {
|
||||
enqueue("flush_memwal", 200, "");
|
||||
enqueue("get_memwal_stats", 200, "{\"memwal_stats\":null}");
|
||||
enqueue("flush_rte", 200, "");
|
||||
enqueue("get_rte_stats", 200, "{\"rte_stats\":null}");
|
||||
|
||||
memWal.checkpointMemWal();
|
||||
rte.checkpointRTE();
|
||||
|
||||
assertEquals(1, countCalls("get_memwal_stats"));
|
||||
assertEquals(1, countCalls("get_rte_stats"));
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
@@ -531,19 +528,18 @@ public class LanceDbTableMemWalTest {
|
||||
/**
|
||||
* The transport must not retry on the checkpoint loop's behalf. Apache HttpClient's default
|
||||
* strategy retries exactly 429 and 503 — the two statuses {@code isRetryable} owns — which
|
||||
* doubled every budget here and also retried {@code compact_memwal} in place, where the loop is
|
||||
* doubled every budget here and also retried {@code compact_rte} in place, where the loop is
|
||||
* built to fall through to a fresh stats poll instead.
|
||||
*/
|
||||
@Test
|
||||
public void testCheckpointRetryBudgetIsNotDoubledByTheTransport() {
|
||||
enqueue("flush_memwal", 429, "latch held");
|
||||
enqueue("flush_rte", 429, "latch held");
|
||||
|
||||
LanceDbRestClient.HttpException e =
|
||||
assertThrows(LanceDbRestClient.HttpException.class, () -> memWal.checkpointMemWal());
|
||||
assertThrows(LanceDbRestClient.HttpException.class, () -> rte.checkpointRTE());
|
||||
|
||||
assertEquals(429, e.statusCode(), "the exhausted budget propagates the last error as itself");
|
||||
assertEquals(
|
||||
9, countCalls("flush_memwal"), "the initial request plus MAX_RETRIES, and no more");
|
||||
assertEquals(9, countCalls("flush_rte"), "the initial request plus MAX_RETRIES, and no more");
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
@@ -558,9 +554,9 @@ public class LanceDbTableMemWalTest {
|
||||
return numbers;
|
||||
}
|
||||
|
||||
/** Build a {@code memwal_stats} response body from table shard fragments. */
|
||||
/** Build a {@code rte_stats} response body from table shard fragments. */
|
||||
private static String stats(String... tableShards) {
|
||||
return "{\"memwal_stats\":{\"table_shards\":[" + String.join(",", tableShards) + "]}}";
|
||||
return "{\"rte_stats\":{\"table_shards\":[" + String.join(",", tableShards) + "]}}";
|
||||
}
|
||||
|
||||
private static String tableShard(String shardId, boolean compacting, Long... sstables) {
|
||||
@@ -600,7 +596,7 @@ public class LanceDbTableMemWalTest {
|
||||
return requestPaths.stream().filter(path -> operationOf(path).equals(operation)).count();
|
||||
}
|
||||
|
||||
/** {@code /v1/table/my_table/flush_memwal/} -> {@code flush_memwal}. */
|
||||
/** {@code /v1/table/my_table/flush_rte/} -> {@code flush_rte}. */
|
||||
private static String operationOf(String path) {
|
||||
String[] segments = path.split("/");
|
||||
return segments.length == 0 ? "" : segments[segments.length - 1];
|
||||
@@ -642,11 +642,11 @@ describe.each(arrowVersions)(
|
||||
);
|
||||
});
|
||||
|
||||
it("should expose useMemWal on takeRowIds as the base-only escape hatch", async () => {
|
||||
it("should expose useRTE on takeRowIds as the base-only escape hatch", async () => {
|
||||
await table.add([{ id: 1 }, { id: 2 }, { id: 3 }]);
|
||||
// useMemWal(false) is reachable on TakeQuery (the escape hatch for MemWAL tables,
|
||||
// useRTE(false) is reachable on TakeQuery (the escape hatch for RTE tables,
|
||||
// where take-by-row-id auto-routes to the LSM scanner and is rejected).
|
||||
const res = await table.takeRowIds([0, 2]).useMemWal(false).toArray();
|
||||
const res = await table.takeRowIds([0, 2]).useRTE(false).toArray();
|
||||
expect(res.map((r) => r.id)).toEqual([1, 3]);
|
||||
});
|
||||
|
||||
@@ -4998,7 +4998,7 @@ describe("setUnenforcedPrimaryKey", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("enableMemWal / disableMemWal", () => {
|
||||
describe("enableRTE / disableRTE", () => {
|
||||
let tmpDir: tmp.DirResult;
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -5018,16 +5018,16 @@ describe("enableMemWal / disableMemWal", () => {
|
||||
const table = await makeTable(conn);
|
||||
|
||||
await table.setUnenforcedPrimaryKey("id");
|
||||
await table.enableMemWal({
|
||||
await table.enableRTE({
|
||||
specType: "bucket",
|
||||
column: "id",
|
||||
numBuckets: 4,
|
||||
});
|
||||
await table.disableMemWal();
|
||||
await table.disableRTE();
|
||||
// A second unset errors — there is no spec left to remove.
|
||||
await expect(table.disableMemWal()).rejects.toThrow();
|
||||
await expect(table.disableRTE()).rejects.toThrow();
|
||||
// A fresh spec can be installed after unset.
|
||||
await table.enableMemWal({
|
||||
await table.enableRTE({
|
||||
specType: "bucket",
|
||||
column: "id",
|
||||
numBuckets: 8,
|
||||
@@ -5039,8 +5039,8 @@ describe("enableMemWal / disableMemWal", () => {
|
||||
const table = await makeTable(conn);
|
||||
|
||||
await table.setUnenforcedPrimaryKey("id");
|
||||
await table.enableMemWal({ specType: "unsharded" });
|
||||
await table.disableMemWal();
|
||||
await table.enableRTE({ specType: "unsharded" });
|
||||
await table.disableRTE();
|
||||
});
|
||||
|
||||
it("installs an identity spec", async () => {
|
||||
@@ -5048,8 +5048,8 @@ describe("enableMemWal / disableMemWal", () => {
|
||||
const table = await makeTable(conn);
|
||||
|
||||
await table.setUnenforcedPrimaryKey("id");
|
||||
await table.enableMemWal({ specType: "identity", column: "id" });
|
||||
await table.disableMemWal();
|
||||
await table.enableRTE({ specType: "identity", column: "id" });
|
||||
await table.disableRTE();
|
||||
});
|
||||
|
||||
it("rejects an invalid spec", async () => {
|
||||
@@ -5059,7 +5059,7 @@ describe("enableMemWal / disableMemWal", () => {
|
||||
await table.setUnenforcedPrimaryKey("id");
|
||||
// num_buckets out of range.
|
||||
await expect(
|
||||
table.enableMemWal({
|
||||
table.enableRTE({
|
||||
specType: "bucket",
|
||||
column: "id",
|
||||
numBuckets: 0,
|
||||
@@ -5067,7 +5067,7 @@ describe("enableMemWal / disableMemWal", () => {
|
||||
).rejects.toThrow();
|
||||
// Column mismatch.
|
||||
await expect(
|
||||
table.enableMemWal({
|
||||
table.enableRTE({
|
||||
specType: "bucket",
|
||||
column: "missing",
|
||||
numBuckets: 4,
|
||||
@@ -5075,13 +5075,13 @@ describe("enableMemWal / disableMemWal", () => {
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("reads back the installed spec via getMemWalSpec", async () => {
|
||||
it("reads back the installed spec via getRTESpec", async () => {
|
||||
const conn = await connect(tmpDir.name);
|
||||
const table = await makeTable(conn);
|
||||
await table.setUnenforcedPrimaryKey("id");
|
||||
|
||||
// Nothing installed yet.
|
||||
expect(await table.getMemWalSpec()).toBeUndefined();
|
||||
expect(await table.getRTESpec()).toBeUndefined();
|
||||
|
||||
// A real scalar index is needed to name it as a maintained index.
|
||||
await table.add([{ id: 1 }, { id: 2 }, { id: 3 }]);
|
||||
@@ -5092,14 +5092,14 @@ describe("enableMemWal / disableMemWal", () => {
|
||||
// defaults. Lance writer-config keys are canonically snake_case.
|
||||
// biome-ignore lint/style/useNamingConvention: Lance writer-config keys are snake_case
|
||||
const writerConfigDefaults = { durable_write: "false" };
|
||||
await table.enableMemWal({
|
||||
await table.enableRTE({
|
||||
specType: "bucket",
|
||||
column: "id",
|
||||
numBuckets: 4,
|
||||
maintainedIndexes: [indexName],
|
||||
writerConfigDefaults,
|
||||
});
|
||||
const spec = await table.getMemWalSpec();
|
||||
const spec = await table.getRTESpec();
|
||||
expect(spec).toBeDefined();
|
||||
expect(spec?.specType).toBe("bucket");
|
||||
expect(spec?.column).toBe("id");
|
||||
@@ -5108,19 +5108,19 @@ describe("enableMemWal / disableMemWal", () => {
|
||||
expect(spec?.writerConfigDefaults).toEqual(writerConfigDefaults);
|
||||
|
||||
// After unset, undefined again.
|
||||
await table.disableMemWal();
|
||||
expect(await table.getMemWalSpec()).toBeUndefined();
|
||||
await table.disableRTE();
|
||||
expect(await table.getRTESpec()).toBeUndefined();
|
||||
|
||||
// Identity round-trips (column recovered from the schema).
|
||||
await table.enableMemWal({ specType: "identity", column: "id" });
|
||||
const identity = await table.getMemWalSpec();
|
||||
await table.enableRTE({ specType: "identity", column: "id" });
|
||||
const identity = await table.getRTESpec();
|
||||
expect(identity?.specType).toBe("identity");
|
||||
expect(identity?.column).toBe("id");
|
||||
await table.disableMemWal();
|
||||
await table.disableRTE();
|
||||
|
||||
// Unsharded round-trips (no routing column).
|
||||
await table.enableMemWal({ specType: "unsharded" });
|
||||
const unsharded = await table.getMemWalSpec();
|
||||
await table.enableRTE({ specType: "unsharded" });
|
||||
const unsharded = await table.getRTESpec();
|
||||
expect(unsharded?.specType).toBe("unsharded");
|
||||
expect(unsharded?.column).toBeFalsy();
|
||||
});
|
||||
@@ -5149,7 +5149,7 @@ describe("LSM merge insert", () => {
|
||||
]);
|
||||
await table.setUnenforcedPrimaryKey("id");
|
||||
// numBuckets = 1: every row routes to the single bucket.
|
||||
await table.enableMemWal({
|
||||
await table.enableRTE({
|
||||
specType: "bucket",
|
||||
column: "id",
|
||||
numBuckets: 1,
|
||||
@@ -5169,22 +5169,22 @@ describe("LSM merge insert", () => {
|
||||
{ id: "c", value: 3 },
|
||||
{ id: "d", value: 4 },
|
||||
]);
|
||||
// LSM path: rows go to the MemWAL, so only numRows is populated.
|
||||
// LSM path: rows go to the RTE, so only numRows is populated.
|
||||
expect(res.numRows).toBe(2);
|
||||
expect(res.version).toBe(0);
|
||||
expect(res.numInsertedRows).toBe(0);
|
||||
|
||||
await table.closeMemWalWriters();
|
||||
await table.closeRTEWriters();
|
||||
});
|
||||
|
||||
it("falls back to the standard path with useMemWal(false)", async () => {
|
||||
it("falls back to the standard path with useRTE(false)", async () => {
|
||||
const conn = await connect(tmpDir.name);
|
||||
const table = await bucketTable(conn);
|
||||
|
||||
const res = await table
|
||||
.mergeInsert("id")
|
||||
.whenNotMatchedInsertAll()
|
||||
.useMemWal(false)
|
||||
.useRTE(false)
|
||||
.execute([
|
||||
{ id: "b", value: 9 },
|
||||
{ id: "e", value: 5 },
|
||||
@@ -5207,7 +5207,7 @@ describe("LSM merge insert", () => {
|
||||
expect(res.numRows).toBe(1);
|
||||
});
|
||||
|
||||
it("rejects a non-upsert merge under a MemWAL spec", async () => {
|
||||
it("rejects a non-upsert merge under an RTE spec", async () => {
|
||||
const conn = await connect(tmpDir.name);
|
||||
const table = await bucketTable(conn);
|
||||
|
||||
@@ -5219,7 +5219,7 @@ describe("LSM merge insert", () => {
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("auto-routes reads through the MemWAL scanner", async () => {
|
||||
it("auto-routes reads through the RTE scanner", async () => {
|
||||
const conn = await connect(tmpDir.name);
|
||||
const table = await bucketTable(conn); // base ids "a", "b"
|
||||
|
||||
@@ -5233,24 +5233,22 @@ describe("LSM merge insert", () => {
|
||||
const lsm = await table.query().toArray();
|
||||
expect(lsm.map((r) => r.id).sort()).toEqual(["a", "b", "c"]);
|
||||
|
||||
// useMemWal(false) bypasses the MemWAL and reads the base table only.
|
||||
const baseOnly = await table.query().useMemWal(false).toArray();
|
||||
// useRTE(false) bypasses the RTE and reads the base table only.
|
||||
const baseOnly = await table.query().useRTE(false).toArray();
|
||||
expect(baseOnly.map((r) => r.id).sort()).toEqual(["a", "b"]);
|
||||
});
|
||||
|
||||
it("reads the base table when no MemWAL spec is installed", async () => {
|
||||
it("reads the base table when no RTE spec is installed", async () => {
|
||||
const conn = await connect(tmpDir.name);
|
||||
const table = await conn.createEmptyTable(
|
||||
"plain",
|
||||
new arrow.Schema([new arrow.Field("id", new arrow.Utf8(), false)]),
|
||||
);
|
||||
// No spec: default read and useMemWal(false) both succeed against the base table.
|
||||
// No spec: default read and useRTE(false) both succeed against the base table.
|
||||
await expect(table.query().toArray()).resolves.toBeDefined();
|
||||
await expect(
|
||||
table.query().useMemWal(false).toArray(),
|
||||
).resolves.toBeDefined();
|
||||
// useMemWal(true) demands MemWAL routing; without a spec it errors.
|
||||
await expect(table.query().useMemWal(true).toArray()).rejects.toThrow();
|
||||
await expect(table.query().useRTE(false).toArray()).resolves.toBeDefined();
|
||||
// useRTE(true) demands RTE routing; without a spec it errors.
|
||||
await expect(table.query().useRTE(true).toArray()).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5268,42 +5266,42 @@ describe("LSM convergence and stats", () => {
|
||||
new arrow.Schema([new arrow.Field("id", new arrow.Utf8(), false)]),
|
||||
);
|
||||
await table.setUnenforcedPrimaryKey("id");
|
||||
await table.enableMemWal({ specType: "unsharded" });
|
||||
await table.enableRTE({ specType: "unsharded" });
|
||||
return table;
|
||||
}
|
||||
|
||||
// These four route through the server that owns the MemWAL, so a local table
|
||||
// These four route through the server that owns the RTE, so a local table
|
||||
// rejects them rather than answering. What is asserted here is that the
|
||||
// bindings reach the core at all; the behavior against a real endpoint is
|
||||
// covered by the mocked endpoint tests in rust/lancedb/src/remote/table.rs.
|
||||
it("rejects flushMemWal on a local table", async () => {
|
||||
it("rejects flushRTE on a local table", async () => {
|
||||
const conn = await connect(tmpDir.name);
|
||||
const table = await lsmTable(conn);
|
||||
|
||||
await expect(table.flushMemWal()).rejects.toThrow(/not supported/i);
|
||||
await expect(table.flushRTE()).rejects.toThrow(/not supported/i);
|
||||
});
|
||||
|
||||
it("rejects compactMemWal on a local table", async () => {
|
||||
it("rejects compactRTE on a local table", async () => {
|
||||
const conn = await connect(tmpDir.name);
|
||||
const table = await lsmTable(conn);
|
||||
|
||||
await expect(table.compactMemWal()).rejects.toThrow(/not supported/i);
|
||||
await expect(table.compactRTE()).rejects.toThrow(/not supported/i);
|
||||
});
|
||||
|
||||
it("rejects getMemWalStats on a local table", async () => {
|
||||
it("rejects getRTEStats on a local table", async () => {
|
||||
const conn = await connect(tmpDir.name);
|
||||
const table = await lsmTable(conn);
|
||||
|
||||
await expect(table.getMemWalStats()).rejects.toThrow(/not supported/i);
|
||||
await expect(table.getMemWalStats(true)).rejects.toThrow(/not supported/i);
|
||||
await expect(table.getRTEStats()).rejects.toThrow(/not supported/i);
|
||||
await expect(table.getRTEStats(true)).rejects.toThrow(/not supported/i);
|
||||
});
|
||||
|
||||
it("rejects checkpointMemWal on a local table", async () => {
|
||||
it("rejects checkpointRTE on a local table", async () => {
|
||||
const conn = await connect(tmpDir.name);
|
||||
const table = await lsmTable(conn);
|
||||
|
||||
// checkpointMemWal freezes first, so it surfaces flushMemWal's rejection.
|
||||
await expect(table.checkpointMemWal()).rejects.toThrow(/not supported/i);
|
||||
// checkpointRTE freezes first, so it surfaces flushRTE's rejection.
|
||||
await expect(table.checkpointRTE()).rejects.toThrow(/not supported/i);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -168,8 +168,8 @@ export {
|
||||
WriteProgress,
|
||||
FtsToken,
|
||||
TokenizeTableOptions,
|
||||
MemWalWriteSpec,
|
||||
MemWalStats,
|
||||
RTEWriteSpec,
|
||||
RTEStats,
|
||||
TableShardStats,
|
||||
SsTableStats,
|
||||
MemtableStats,
|
||||
|
||||
@@ -88,27 +88,27 @@ export class MergeInsertBuilder {
|
||||
);
|
||||
}
|
||||
/**
|
||||
* Control MemWAL routing for this merge.
|
||||
* Control RTE routing for this merge.
|
||||
*
|
||||
* By default (unset), a `mergeInsert` on a table with a MemWAL write spec is
|
||||
* By default (unset), a `mergeInsert` on a table with an RTE write spec is
|
||||
* routed through Lance's MemWAL shard writer, and a table without one uses the
|
||||
* standard path.
|
||||
*
|
||||
* @param enable - `true` forces MemWAL routing and errors if the table has no
|
||||
* MemWAL write spec. `false` forces the standard write path even when a spec is set.
|
||||
* @param enable - `true` forces RTE routing and errors if the table has no
|
||||
* RTE write spec. `false` forces the standard write path even when a spec is set.
|
||||
*/
|
||||
useMemWal(enable: boolean): MergeInsertBuilder {
|
||||
return new MergeInsertBuilder(this.#native.useMemWal(enable), this.#schema);
|
||||
useRTE(enable: boolean): MergeInsertBuilder {
|
||||
return new MergeInsertBuilder(this.#native.useRTE(enable), this.#schema);
|
||||
}
|
||||
/**
|
||||
* Controls how an LSM merge checks that its input targets a single shard.
|
||||
*
|
||||
* When a table has a MemWAL write spec, every row in a `mergeInsert` call must
|
||||
* When a table has an RTE write spec, every row in a `mergeInsert` call must
|
||||
* route to the same shard. When `true` (the default), every row is inspected
|
||||
* to verify this. When `false`, only the first row is inspected and the
|
||||
* shard it routes to is used for the whole input — a faster path for callers
|
||||
* that have already pre-sharded their input. Has no effect on tables without
|
||||
* a MemWAL write spec.
|
||||
* an RTE write spec.
|
||||
*
|
||||
* @param validateSingleShard - Whether to check every row routes to one shard. Defaults to `true`.
|
||||
*/
|
||||
|
||||
+15
-15
@@ -677,26 +677,26 @@ export class StandardQueryBase<
|
||||
}
|
||||
|
||||
/**
|
||||
* Control MemWAL read routing for this query.
|
||||
* Control RTE read routing for this query.
|
||||
*
|
||||
* By default (unset), when the table carries a MemWAL write spec (see
|
||||
* {@link Table#enableMemWal}), reads are routed through the LSM scanner so
|
||||
* By default (unset), when the table carries an RTE write spec (see
|
||||
* {@link Table#enableRTE}), reads are routed through the LSM scanner so
|
||||
* they also return data written via the `mergeInsert` LSM path that has not yet
|
||||
* been compacted into the base table (the active/frozen in-memory memtables and
|
||||
* the SSTables), deduplicated by primary key; a table without a spec
|
||||
* reads the base table.
|
||||
*
|
||||
* @param enable - `true` forces the LSM scanner and errors if the table has no
|
||||
* MemWAL write spec. `false` bypasses the MemWAL and reads the base table only,
|
||||
* RTE write spec. `false` bypasses the RTE and reads the base table only,
|
||||
* even when a spec is present.
|
||||
*
|
||||
* Note: the LSM scanner does not support every query shape (e.g. reranking,
|
||||
* hybrid search, `orderBy`). On a MemWAL table those shapes error unless
|
||||
* `useMemWal(false)` is set, because a base-only read would silently exclude
|
||||
* un-compacted MemWAL data.
|
||||
* hybrid search, `orderBy`). On an RTE table those shapes error unless
|
||||
* `useRTE(false)` is set, because a base-only read would silently exclude
|
||||
* un-compacted RTE data.
|
||||
*/
|
||||
useMemWal(enable: boolean): this {
|
||||
this.doCall((inner: NativeQueryType) => inner.useMemWal(enable));
|
||||
useRTE(enable: boolean): this {
|
||||
this.doCall((inner: NativeQueryType) => inner.useRTE(enable));
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -776,7 +776,7 @@ export class VectorQuery extends StandardQueryBase<NativeVectorQuery> {
|
||||
* probing may continue when too few candidates are found.
|
||||
* Any explicit effort, including 0.5, overrides nprobes in either call order.
|
||||
* Explicit minimum and maximum bounds still apply. This is not a recall
|
||||
* guarantee and does not change refinement or HNSW ef. The MemWAL LSM
|
||||
* guarantee and does not change refinement or HNSW ef. The RTE LSM
|
||||
* scanner does not yet support this option.
|
||||
*
|
||||
* @example
|
||||
@@ -1082,16 +1082,16 @@ export class TakeQuery extends QueryBase<NativeTakeQuery> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Control MemWAL read routing for this take query.
|
||||
* Control RTE read routing for this take query.
|
||||
*
|
||||
* `false` bypasses the MemWAL and reads the base table only — the escape hatch,
|
||||
* `false` bypasses the RTE and reads the base table only — the escape hatch,
|
||||
* since take-by-row-id/offset is not supported on the LSM scanner and, on a
|
||||
* MemWAL table, auto-routes to it and errors otherwise.
|
||||
* RTE table, auto-routes to it and errors otherwise.
|
||||
*
|
||||
* @param enable - `false` reads the base table only.
|
||||
*/
|
||||
useMemWal(enable: boolean): this {
|
||||
this.doCall((inner: NativeTakeQuery) => inner.useMemWal(enable));
|
||||
useRTE(enable: boolean): this {
|
||||
this.doCall((inner: NativeTakeQuery) => inner.useRTE(enable));
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
+54
-54
@@ -35,9 +35,9 @@ import {
|
||||
FunctionErrorsOptions,
|
||||
IndexConfig,
|
||||
IndexStatistics,
|
||||
MemWalStats,
|
||||
Branches as NativeBranches,
|
||||
OptimizeStats,
|
||||
RTEStats,
|
||||
RefreshColumnResult,
|
||||
RefreshMaterializedViewResult,
|
||||
TableStatistics,
|
||||
@@ -61,7 +61,7 @@ export { IndexConfig } from "./native";
|
||||
export {
|
||||
TableShardStats,
|
||||
SsTableStats,
|
||||
MemWalStats,
|
||||
RTEStats,
|
||||
MemtableStats,
|
||||
} from "./native";
|
||||
|
||||
@@ -207,8 +207,8 @@ export type TokenizeTableOptions =
|
||||
};
|
||||
|
||||
/**
|
||||
* Specification selecting Lance's MemWAL LSM-style write path for
|
||||
* `mergeInsert`.
|
||||
* Specification enabling the realtime engine (RTE), which routes
|
||||
* `mergeInsert` through Lance's MemWAL LSM-style write path.
|
||||
*
|
||||
* `specType` is `"bucket"`, `"identity"`, or `"unsharded"`. For `"bucket"`,
|
||||
* `column` and `numBuckets` are required; for `"identity"`, `column` is
|
||||
@@ -217,7 +217,7 @@ export type TokenizeTableOptions =
|
||||
* `column` value, or upserts of that key can land in different shards and a
|
||||
* stale version can win).
|
||||
*/
|
||||
export interface MemWalWriteSpec {
|
||||
export interface RTEWriteSpec {
|
||||
/** One of `"bucket"`, `"identity"`, or `"unsharded"`. */
|
||||
specType: "bucket" | "identity" | "unsharded";
|
||||
/** Bucket and identity variants: the sharding column. */
|
||||
@@ -225,7 +225,7 @@ export interface MemWalWriteSpec {
|
||||
/** Bucket variant: the number of buckets, in `[1, 1024]`. */
|
||||
numBuckets?: number;
|
||||
/**
|
||||
* Indexes the MemWAL keeps up to date. Omit for every index the table has,
|
||||
* Indexes the RTE keeps up to date. Omit for every index the table has,
|
||||
* including ones created later. Pass `[]` for none.
|
||||
*/
|
||||
maintainedIndexes?: string[];
|
||||
@@ -758,10 +758,10 @@ export abstract class Table {
|
||||
*/
|
||||
abstract setUnenforcedPrimaryKey(columns: string | string[]): Promise<void>;
|
||||
/**
|
||||
* Install an {@link MemWalWriteSpec} on this table, selecting Lance's MemWAL
|
||||
* Install an {@link RTEWriteSpec} on this table, selecting Lance's MemWAL
|
||||
* LSM-style write path for future `mergeInsert` calls.
|
||||
*
|
||||
* `MemWalWriteSpec` chooses one of three sharding strategies via `specType`:
|
||||
* `RTEWriteSpec` chooses one of three sharding strategies via `specType`:
|
||||
*
|
||||
* - `"bucket"` — hash-bucket writes by the single-column unenforced primary
|
||||
* key (`column` and `numBuckets` required).
|
||||
@@ -773,15 +773,15 @@ export abstract class Table {
|
||||
* requires it to be the single column being bucketed.
|
||||
*
|
||||
* Omitting `maintainedIndexes` maintains every index the table has,
|
||||
* including ones created later, and skips a kind the MemWAL cannot maintain.
|
||||
* including ones created later, and skips a kind the RTE cannot maintain.
|
||||
* Naming them pins an exact set, and a still-building index is rejected
|
||||
* rather than quietly omitted.
|
||||
* @param {MemWalWriteSpec} spec The sharding spec to install.
|
||||
* @param {RTEWriteSpec} spec The sharding spec to install.
|
||||
* @returns {Promise<void>}
|
||||
* @example
|
||||
* ```ts
|
||||
* await table.setUnenforcedPrimaryKey("id");
|
||||
* await table.enableMemWal({
|
||||
* await table.enableRTE({
|
||||
* specType: "bucket",
|
||||
* column: "id",
|
||||
* numBuckets: 16,
|
||||
@@ -789,36 +789,36 @@ export abstract class Table {
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
abstract enableMemWal(spec: MemWalWriteSpec): Promise<void>;
|
||||
abstract enableRTE(spec: RTEWriteSpec): Promise<void>;
|
||||
/**
|
||||
* Remove the {@link MemWalWriteSpec} from this table, reverting to the standard
|
||||
* Remove the {@link RTEWriteSpec} from this table, reverting to the standard
|
||||
* `mergeInsert` write path.
|
||||
*
|
||||
* Errors if no spec is currently set.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
abstract disableMemWal(): Promise<void>;
|
||||
abstract disableRTE(): Promise<void>;
|
||||
/**
|
||||
* Read the {@link MemWalWriteSpec} currently installed on this table.
|
||||
* Read the {@link RTEWriteSpec} currently installed on this table.
|
||||
*
|
||||
* Resolves to `undefined` when the MemWAL write path is not enabled (no
|
||||
* spec has been set, or it was removed with {@link Table#disableMemWal}).
|
||||
* Resolves to `undefined` when the RTE write path is not enabled (no
|
||||
* spec has been set, or it was removed with {@link Table#disableRTE}).
|
||||
* The spec is the one installed, including its maintained-index selection:
|
||||
* an absent `maintainedIndexes` for every index the table has, an empty
|
||||
* array for none.
|
||||
* @returns {Promise<MemWalWriteSpec | undefined>}
|
||||
* @returns {Promise<RTEWriteSpec | undefined>}
|
||||
*/
|
||||
abstract getMemWalSpec(): Promise<MemWalWriteSpec | undefined>;
|
||||
abstract getRTESpec(): Promise<RTEWriteSpec | undefined>;
|
||||
/**
|
||||
* Drain and close any cached MemWAL shard writers held for this table.
|
||||
* Drain and close any cached RTE shard writers held for this table.
|
||||
*
|
||||
* When an {@link MemWalWriteSpec} is installed, `mergeInsert` opens MemWAL
|
||||
* When an {@link RTEWriteSpec} is installed, `mergeInsert` opens RTE
|
||||
* shard writers and caches them for reuse across calls. This closes them,
|
||||
* flushing pending data; writers reopen lazily on the next `mergeInsert`.
|
||||
* It is a no-op when no writers are cached.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
abstract closeMemWalWriters(): Promise<void>;
|
||||
abstract closeRTEWriters(): Promise<void>;
|
||||
/**
|
||||
* Freeze every table shard's active memtable into a new SSTable.
|
||||
*
|
||||
@@ -826,18 +826,18 @@ export abstract class Table {
|
||||
* so this is safe to call repeatedly.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
abstract flushMemWal(): Promise<void>;
|
||||
abstract flushRTE(): Promise<void>;
|
||||
/**
|
||||
* Trigger a background SSTable compaction pass per table shard.
|
||||
*
|
||||
* Returns once the passes are *dispatched*, not once they finish — watch
|
||||
* {@link Table#getMemWalStats} for progress, or use
|
||||
* {@link Table#checkpointMemWal} to wait for convergence.
|
||||
* {@link Table#getRTEStats} for progress, or use
|
||||
* {@link Table#checkpointRTE} to wait for convergence.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
abstract compactMemWal(): Promise<void>;
|
||||
abstract compactRTE(): Promise<void>;
|
||||
/**
|
||||
* Converge this table's MemWAL write path into its base table.
|
||||
* Converge this table's RTE write path into its base table.
|
||||
*
|
||||
* Freezes once, then triggers compaction and polls until the SSTables that existed
|
||||
* at the start is gone. The target set is fixed at the start, so
|
||||
@@ -852,26 +852,26 @@ export abstract class Table {
|
||||
* @returns {Promise<void>}
|
||||
* @example
|
||||
* ```ts
|
||||
* const before = await table.getMemWalStats();
|
||||
* await table.checkpointMemWal();
|
||||
* const after = await table.getMemWalStats();
|
||||
* const before = await table.getRTEStats();
|
||||
* await table.checkpointRTE();
|
||||
* const after = await table.getRTEStats();
|
||||
* ```
|
||||
*/
|
||||
abstract checkpointMemWal(): Promise<void>;
|
||||
abstract checkpointRTE(): Promise<void>;
|
||||
/**
|
||||
* Read live per-table-shard MemWAL state.
|
||||
* Read live per-table-shard RTE state.
|
||||
*
|
||||
* Answers "how far behind is my fresh tier", "which table shard is hot", and
|
||||
* "why is my fresh-tier vector search brute-force". Mutates no table state.
|
||||
*
|
||||
* Resolves to `undefined` only when the MemWAL write path is not enabled.
|
||||
* Resolves to `undefined` only when the RTE write path is not enabled.
|
||||
* @param {boolean} includeSstableRows Also count rows per SSTable.
|
||||
* Off by default because each count opens an uncached Lance dataset.
|
||||
* @returns {Promise<MemWalStats | undefined>}
|
||||
* @returns {Promise<RTEStats | undefined>}
|
||||
*/
|
||||
abstract getMemWalStats(
|
||||
abstract getRTEStats(
|
||||
includeSstableRows?: boolean,
|
||||
): Promise<MemWalStats | undefined>;
|
||||
): Promise<RTEStats | undefined>;
|
||||
/** Retrieve the version of the table */
|
||||
|
||||
abstract version(): Promise<number>;
|
||||
@@ -1480,43 +1480,43 @@ export class LocalTable extends Table {
|
||||
return await this.inner.setUnenforcedPrimaryKey(cols);
|
||||
}
|
||||
|
||||
async enableMemWal(spec: MemWalWriteSpec): Promise<void> {
|
||||
return await this.inner.enableMemWal(spec);
|
||||
async enableRTE(spec: RTEWriteSpec): Promise<void> {
|
||||
return await this.inner.enableRTE(spec);
|
||||
}
|
||||
|
||||
async disableMemWal(): Promise<void> {
|
||||
return await this.inner.disableMemWal();
|
||||
async disableRTE(): Promise<void> {
|
||||
return await this.inner.disableRTE();
|
||||
}
|
||||
|
||||
async getMemWalSpec(): Promise<MemWalWriteSpec | undefined> {
|
||||
async getRTESpec(): Promise<RTEWriteSpec | undefined> {
|
||||
// The native binding types `specType` as a plain `string`; narrow it back
|
||||
// to the public union. The Rust `From` impl only ever emits one of the
|
||||
// three valid values, so the cast is safe.
|
||||
return ((await this.inner.getMemWalSpec()) ?? undefined) as
|
||||
| MemWalWriteSpec
|
||||
return ((await this.inner.getRTESpec()) ?? undefined) as
|
||||
| RTEWriteSpec
|
||||
| undefined;
|
||||
}
|
||||
|
||||
async closeMemWalWriters(): Promise<void> {
|
||||
return await this.inner.closeMemWalWriters();
|
||||
async closeRTEWriters(): Promise<void> {
|
||||
return await this.inner.closeRTEWriters();
|
||||
}
|
||||
|
||||
async flushMemWal(): Promise<void> {
|
||||
return await this.inner.flushMemWal();
|
||||
async flushRTE(): Promise<void> {
|
||||
return await this.inner.flushRTE();
|
||||
}
|
||||
|
||||
async compactMemWal(): Promise<void> {
|
||||
return await this.inner.compactMemWal();
|
||||
async compactRTE(): Promise<void> {
|
||||
return await this.inner.compactRTE();
|
||||
}
|
||||
|
||||
async checkpointMemWal(): Promise<void> {
|
||||
return await this.inner.checkpointMemWal();
|
||||
async checkpointRTE(): Promise<void> {
|
||||
return await this.inner.checkpointRTE();
|
||||
}
|
||||
|
||||
async getMemWalStats(
|
||||
async getRTEStats(
|
||||
includeSstableRows: boolean = false,
|
||||
): Promise<MemWalStats | undefined> {
|
||||
return (await this.inner.getMemWalStats(includeSstableRows)) ?? undefined;
|
||||
): Promise<RTEStats | undefined> {
|
||||
return (await this.inner.getRTEStats(includeSstableRows)) ?? undefined;
|
||||
}
|
||||
|
||||
async version(): Promise<number> {
|
||||
|
||||
+3
-3
@@ -50,10 +50,10 @@ impl NativeMergeInsertBuilder {
|
||||
this
|
||||
}
|
||||
|
||||
#[napi(js_name = "useMemWal")]
|
||||
pub fn use_memwal(&self, enable: bool) -> Self {
|
||||
#[napi(js_name = "useRTE")]
|
||||
pub fn use_rte(&self, enable: bool) -> Self {
|
||||
let mut this = self.clone();
|
||||
this.inner.use_memwal(enable);
|
||||
this.inner.use_rte(enable);
|
||||
this
|
||||
}
|
||||
|
||||
|
||||
+9
-9
@@ -168,9 +168,9 @@ impl Query {
|
||||
self.inner = self.inner.clone().with_row_id();
|
||||
}
|
||||
|
||||
#[napi(js_name = "useMemWal")]
|
||||
pub fn use_memwal(&mut self, enable: bool) {
|
||||
self.inner = self.inner.clone().use_memwal(enable);
|
||||
#[napi(js_name = "useRTE")]
|
||||
pub fn use_rte(&mut self, enable: bool) {
|
||||
self.inner = self.inner.clone().use_rte(enable);
|
||||
}
|
||||
|
||||
#[napi]
|
||||
@@ -399,9 +399,9 @@ impl VectorQuery {
|
||||
self.inner = self.inner.clone().with_row_id();
|
||||
}
|
||||
|
||||
#[napi(js_name = "useMemWal")]
|
||||
pub fn use_memwal(&mut self, enable: bool) {
|
||||
self.inner = self.inner.clone().use_memwal(enable);
|
||||
#[napi(js_name = "useRTE")]
|
||||
pub fn use_rte(&mut self, enable: bool) {
|
||||
self.inner = self.inner.clone().use_rte(enable);
|
||||
}
|
||||
|
||||
#[napi]
|
||||
@@ -514,9 +514,9 @@ impl TakeQuery {
|
||||
self.inner = self.inner.clone().with_row_id();
|
||||
}
|
||||
|
||||
#[napi(js_name = "useMemWal")]
|
||||
pub fn use_memwal(&mut self, enable: bool) {
|
||||
self.inner = self.inner.clone().use_memwal(enable);
|
||||
#[napi(js_name = "useRTE")]
|
||||
pub fn use_rte(&mut self, enable: bool) {
|
||||
self.inner = self.inner.clone().use_rte(enable);
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
|
||||
+47
-50
@@ -580,60 +580,57 @@ impl Table {
|
||||
.default_error()
|
||||
}
|
||||
|
||||
#[napi(catch_unwind, js_name = "enableMemWal")]
|
||||
pub async fn enable_memwal(&self, spec: MemWalWriteSpec) -> napi::Result<()> {
|
||||
let native_spec = lancedb::table::MemWalWriteSpec::try_from(spec)?;
|
||||
#[napi(catch_unwind, js_name = "enableRTE")]
|
||||
pub async fn enable_rte(&self, spec: RTEWriteSpec) -> napi::Result<()> {
|
||||
let native_spec = lancedb::table::RTEWriteSpec::try_from(spec)?;
|
||||
self.inner_ref()?
|
||||
.enable_memwal(native_spec)
|
||||
.enable_rte(native_spec)
|
||||
.await
|
||||
.default_error()
|
||||
}
|
||||
|
||||
#[napi(catch_unwind, js_name = "disableMemWal")]
|
||||
pub async fn disable_memwal(&self) -> napi::Result<()> {
|
||||
self.inner_ref()?.disable_memwal().await.default_error()
|
||||
#[napi(catch_unwind, js_name = "disableRTE")]
|
||||
pub async fn disable_rte(&self) -> napi::Result<()> {
|
||||
self.inner_ref()?.disable_rte().await.default_error()
|
||||
}
|
||||
|
||||
#[napi(catch_unwind, js_name = "getMemWalSpec")]
|
||||
pub async fn get_memwal_spec(&self) -> napi::Result<Option<MemWalWriteSpec>> {
|
||||
let spec = self.inner_ref()?.get_memwal_spec().await.default_error()?;
|
||||
Ok(spec.map(MemWalWriteSpec::from))
|
||||
#[napi(catch_unwind, js_name = "getRTESpec")]
|
||||
pub async fn get_rte_spec(&self) -> napi::Result<Option<RTEWriteSpec>> {
|
||||
let spec = self.inner_ref()?.get_rte_spec().await.default_error()?;
|
||||
Ok(spec.map(RTEWriteSpec::from))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind, js_name = "closeMemWalWriters")]
|
||||
pub async fn close_memwal_writers(&self) -> napi::Result<()> {
|
||||
self.inner_ref()?
|
||||
.close_memwal_writers()
|
||||
.await
|
||||
.default_error()
|
||||
#[napi(catch_unwind, js_name = "closeRTEWriters")]
|
||||
pub async fn close_rte_writers(&self) -> napi::Result<()> {
|
||||
self.inner_ref()?.close_rte_writers().await.default_error()
|
||||
}
|
||||
|
||||
#[napi(catch_unwind, js_name = "flushMemWal")]
|
||||
pub async fn flush_memwal(&self) -> napi::Result<()> {
|
||||
self.inner_ref()?.flush_memwal().await.default_error()
|
||||
#[napi(catch_unwind, js_name = "flushRTE")]
|
||||
pub async fn flush_rte(&self) -> napi::Result<()> {
|
||||
self.inner_ref()?.flush_rte().await.default_error()
|
||||
}
|
||||
|
||||
#[napi(catch_unwind, js_name = "compactMemWal")]
|
||||
pub async fn compact_memwal(&self) -> napi::Result<()> {
|
||||
self.inner_ref()?.compact_memwal().await.default_error()
|
||||
#[napi(catch_unwind, js_name = "compactRTE")]
|
||||
pub async fn compact_rte(&self) -> napi::Result<()> {
|
||||
self.inner_ref()?.compact_rte().await.default_error()
|
||||
}
|
||||
|
||||
#[napi(catch_unwind, js_name = "checkpointMemWal")]
|
||||
pub async fn checkpoint_memwal(&self) -> napi::Result<()> {
|
||||
self.inner_ref()?.checkpoint_memwal().await.default_error()
|
||||
#[napi(catch_unwind, js_name = "checkpointRTE")]
|
||||
pub async fn checkpoint_rte(&self) -> napi::Result<()> {
|
||||
self.inner_ref()?.checkpoint_rte().await.default_error()
|
||||
}
|
||||
|
||||
#[napi(catch_unwind, js_name = "getMemWalStats")]
|
||||
pub async fn get_memwal_stats(
|
||||
#[napi(catch_unwind, js_name = "getRTEStats")]
|
||||
pub async fn get_rte_stats(
|
||||
&self,
|
||||
include_sstable_rows: bool,
|
||||
) -> napi::Result<Option<MemWalStats>> {
|
||||
) -> napi::Result<Option<RTEStats>> {
|
||||
let stats = self
|
||||
.inner_ref()?
|
||||
.get_memwal_stats(include_sstable_rows)
|
||||
.get_rte_stats(include_sstable_rows)
|
||||
.await
|
||||
.default_error()?;
|
||||
Ok(stats.map(MemWalStats::from))
|
||||
Ok(stats.map(RTEStats::from))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
@@ -946,53 +943,53 @@ impl From<LanceDbFtsToken> for FtsToken {
|
||||
}
|
||||
}
|
||||
|
||||
/// Specification selecting Lance's MemWAL LSM-style write path for
|
||||
/// `mergeInsert`.
|
||||
/// Specification enabling the realtime engine (RTE), which routes
|
||||
/// `mergeInsert` through Lance's MemWAL LSM-style write path.
|
||||
///
|
||||
/// `specType` must be `"bucket"`, `"identity"`, or `"unsharded"`. For
|
||||
/// `"bucket"`, `column` and `numBuckets` are required; for `"identity"`,
|
||||
/// `column` is required.
|
||||
#[napi(object)]
|
||||
#[napi(object, js_name = "RTEWriteSpec")]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct MemWalWriteSpec {
|
||||
pub struct RTEWriteSpec {
|
||||
/// One of `"bucket"`, `"identity"`, or `"unsharded"`.
|
||||
pub spec_type: String,
|
||||
/// Bucket and identity variants: the sharding column.
|
||||
pub column: Option<String>,
|
||||
/// Bucket variant: the number of buckets, in `[1, 1024]`.
|
||||
pub num_buckets: Option<u32>,
|
||||
/// Indexes the MemWAL keeps up to date. Omitted resolves every
|
||||
/// Indexes the RTE keeps up to date. Omitted resolves every
|
||||
/// maintainable index on install; an empty array means none.
|
||||
pub maintained_indexes: Option<Vec<String>>,
|
||||
/// Default `ShardWriter` configuration recorded in the MemWAL index.
|
||||
pub writer_config_defaults: Option<HashMap<String, String>>,
|
||||
}
|
||||
|
||||
impl TryFrom<MemWalWriteSpec> for lancedb::table::MemWalWriteSpec {
|
||||
impl TryFrom<RTEWriteSpec> for lancedb::table::RTEWriteSpec {
|
||||
type Error = napi::Error;
|
||||
|
||||
fn try_from(value: MemWalWriteSpec) -> napi::Result<Self> {
|
||||
fn try_from(value: RTEWriteSpec) -> napi::Result<Self> {
|
||||
let writer_config_defaults = value.writer_config_defaults.unwrap_or_default();
|
||||
let spec = match value.spec_type.as_str() {
|
||||
"bucket" => {
|
||||
let column = value.column.ok_or_else(|| {
|
||||
napi::Error::from_reason("MemWalWriteSpec bucket requires `column`")
|
||||
napi::Error::from_reason("RTEWriteSpec bucket requires `column`")
|
||||
})?;
|
||||
let num_buckets = value.num_buckets.ok_or_else(|| {
|
||||
napi::Error::from_reason("MemWalWriteSpec bucket requires `numBuckets`")
|
||||
napi::Error::from_reason("RTEWriteSpec bucket requires `numBuckets`")
|
||||
})?;
|
||||
Self::bucket(column, num_buckets)
|
||||
}
|
||||
"identity" => {
|
||||
let column = value.column.ok_or_else(|| {
|
||||
napi::Error::from_reason("MemWalWriteSpec identity requires `column`")
|
||||
napi::Error::from_reason("RTEWriteSpec identity requires `column`")
|
||||
})?;
|
||||
Self::identity(column)
|
||||
}
|
||||
"unsharded" => Self::unsharded(),
|
||||
other => {
|
||||
return Err(napi::Error::from_reason(format!(
|
||||
"MemWalWriteSpec `specType` must be 'bucket', 'identity', or 'unsharded', got '{}'",
|
||||
"RTEWriteSpec `specType` must be 'bucket', 'identity', or 'unsharded', got '{}'",
|
||||
other
|
||||
)));
|
||||
}
|
||||
@@ -1003,9 +1000,9 @@ impl TryFrom<MemWalWriteSpec> for lancedb::table::MemWalWriteSpec {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<lancedb::table::MemWalWriteSpec> for MemWalWriteSpec {
|
||||
fn from(spec: lancedb::table::MemWalWriteSpec) -> Self {
|
||||
use lancedb::table::MemWalWriteSpec as Native;
|
||||
impl From<lancedb::table::RTEWriteSpec> for RTEWriteSpec {
|
||||
fn from(spec: lancedb::table::RTEWriteSpec) -> Self {
|
||||
use lancedb::table::RTEWriteSpec as Native;
|
||||
match spec {
|
||||
Native::Bucket {
|
||||
column,
|
||||
@@ -1148,19 +1145,19 @@ impl From<lancedb::table::TableShardStats> for TableShardStats {
|
||||
}
|
||||
}
|
||||
|
||||
/// Live per-table-shard MemWAL state, as returned by `Table#getMemWalStats`.
|
||||
/// Live per-table-shard RTE state, as returned by `Table#getRTEStats`.
|
||||
///
|
||||
/// Nothing here is derived: sums and differences (total SSTable bytes, WAL lag) are
|
||||
/// the caller's to compute.
|
||||
#[napi(object)]
|
||||
#[napi(object, js_name = "RTEStats")]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct MemWalStats {
|
||||
pub struct RTEStats {
|
||||
/// One entry per table shard backing this table.
|
||||
pub table_shards: Vec<TableShardStats>,
|
||||
}
|
||||
|
||||
impl From<lancedb::table::MemWalStats> for MemWalStats {
|
||||
fn from(stats: lancedb::table::MemWalStats) -> Self {
|
||||
impl From<lancedb::table::RTEStats> for RTEStats {
|
||||
fn from(stats: lancedb::table::RTEStats) -> Self {
|
||||
Self {
|
||||
table_shards: stats.table_shards.into_iter().map(Into::into).collect(),
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ from ._lancedb import FtsToken
|
||||
from ._lancedb import FunctionErrorFragment as FunctionErrorFragment
|
||||
from ._lancedb import FunctionErrorRecord as FunctionErrorRecord
|
||||
from ._lancedb import FunctionErrors as FunctionErrors
|
||||
from ._lancedb import MemWalWriteSpec
|
||||
from ._lancedb import RTEWriteSpec
|
||||
from ._lancedb import tokenize as _tokenize
|
||||
from .common import URI, sanitize_uri
|
||||
from urllib.parse import urlparse
|
||||
@@ -610,7 +610,7 @@ __all__ = [
|
||||
"SqlQuery",
|
||||
"LanceDBConnection",
|
||||
"LanceNamespaceDBConnection",
|
||||
"MemWalWriteSpec",
|
||||
"RTEWriteSpec",
|
||||
"RemoteDBConnection",
|
||||
"Session",
|
||||
"Table",
|
||||
|
||||
@@ -538,17 +538,17 @@ class Table:
|
||||
async def initial_storage_options(self) -> Optional[Dict[str, str]]: ...
|
||||
async def latest_storage_options(self) -> Optional[Dict[str, str]]: ...
|
||||
async def set_unenforced_primary_key(self, columns: List[str]) -> None: ...
|
||||
async def enable_memwal(self, spec: MemWalWriteSpec) -> None: ...
|
||||
async def disable_memwal(self) -> None: ...
|
||||
async def get_memwal_spec(self) -> Optional[MemWalWriteSpec]: ...
|
||||
async def enable_rte(self, spec: RTEWriteSpec) -> None: ...
|
||||
async def disable_rte(self) -> None: ...
|
||||
async def get_rte_spec(self) -> Optional[RTEWriteSpec]: ...
|
||||
# WAL-PK-FUSION: delete both.
|
||||
def hybrid_pk_fusion_learned(self) -> bool: ...
|
||||
def note_hybrid_pk_fusion(self) -> None: ...
|
||||
async def checkpoint_memwal(self) -> None: ...
|
||||
async def flush_memwal(self) -> None: ...
|
||||
async def compact_memwal(self) -> None: ...
|
||||
async def get_memwal_stats(self, include_sstable_rows: bool) -> Optional[dict]: ...
|
||||
async def close_memwal_writers(self) -> None: ...
|
||||
async def checkpoint_rte(self) -> None: ...
|
||||
async def flush_rte(self) -> None: ...
|
||||
async def compact_rte(self) -> None: ...
|
||||
async def get_rte_stats(self, include_sstable_rows: bool) -> Optional[dict]: ...
|
||||
async def close_rte_writers(self) -> None: ...
|
||||
@property
|
||||
def tags(self) -> Tags: ...
|
||||
@property
|
||||
@@ -661,7 +661,7 @@ class Query:
|
||||
def fast_search(self): ...
|
||||
def with_row_id(self): ...
|
||||
def postfilter(self): ...
|
||||
def use_memwal(self, enable: bool): ...
|
||||
def use_rte(self, enable: bool): ...
|
||||
def nearest_to(self, query_vec: pa.Array) -> VectorQuery: ...
|
||||
def nearest_to_text(self, query: dict) -> FTSQuery: ...
|
||||
def order_by(self, ordering: Optional[List[ColumnOrdering]]): ...
|
||||
@@ -678,7 +678,7 @@ class Query:
|
||||
class TakeQuery:
|
||||
def select(self, columns: List[str]): ...
|
||||
def with_row_id(self): ...
|
||||
def use_memwal(self, enable: bool): ...
|
||||
def use_rte(self, enable: bool): ...
|
||||
async def output_schema(self) -> pa.Schema: ...
|
||||
async def execute(self) -> RecordBatchStream: ...
|
||||
async def explain_plan(self, verbose: Optional[bool]) -> str: ...
|
||||
@@ -697,7 +697,7 @@ class FTSQuery:
|
||||
def fast_search(self): ...
|
||||
def with_row_id(self): ...
|
||||
def postfilter(self): ...
|
||||
def use_memwal(self, enable: bool): ...
|
||||
def use_rte(self, enable: bool): ...
|
||||
def get_query(self) -> str: ...
|
||||
def add_query_vector(self, query_vec: pa.Array) -> None: ...
|
||||
def nearest_to(self, query_vec: pa.Array) -> HybridQuery: ...
|
||||
@@ -725,7 +725,7 @@ class VectorQuery:
|
||||
def column(self, column: str): ...
|
||||
def distance_type(self, distance_type: str): ...
|
||||
def postfilter(self): ...
|
||||
def use_memwal(self, enable: bool): ...
|
||||
def use_rte(self, enable: bool): ...
|
||||
def refine_factor(self, refine_factor: int): ...
|
||||
def nprobes(self, nprobes: int): ...
|
||||
def search_effort(self, search_effort: Optional[float]): ...
|
||||
@@ -750,7 +750,7 @@ class HybridQuery:
|
||||
def fast_search(self): ...
|
||||
def with_row_id(self): ...
|
||||
def postfilter(self): ...
|
||||
def use_memwal(self, enable: bool): ...
|
||||
def use_rte(self, enable: bool): ...
|
||||
def distance_type(self, distance_type: str): ...
|
||||
def refine_factor(self, refine_factor: int): ...
|
||||
def nprobes(self, nprobes: int): ...
|
||||
@@ -778,7 +778,7 @@ class PyQueryRequest:
|
||||
select_source_columns: Optional[Dict[str, str]]
|
||||
fast_search: Optional[bool]
|
||||
with_row_id: Optional[bool]
|
||||
use_memwal: Optional[bool]
|
||||
use_rte: Optional[bool]
|
||||
column: Optional[str]
|
||||
query_vector: Optional[List[pa.Array]]
|
||||
nprobes: Optional[int]
|
||||
@@ -839,26 +839,22 @@ class FtsToken:
|
||||
text: str
|
||||
position: int
|
||||
|
||||
class MemWalWriteSpec:
|
||||
"""Specification selecting Lance's MemWAL LSM-style write path for
|
||||
`merge_insert`."""
|
||||
class RTEWriteSpec:
|
||||
"""Specification enabling the realtime engine (RTE), which routes
|
||||
`merge_insert` through Lance's MemWAL LSM-style write path."""
|
||||
|
||||
@staticmethod
|
||||
def bucket(column: str, num_buckets: int) -> "MemWalWriteSpec": ...
|
||||
def bucket(column: str, num_buckets: int) -> "RTEWriteSpec": ...
|
||||
@staticmethod
|
||||
def identity(column: str) -> "MemWalWriteSpec": ...
|
||||
def identity(column: str) -> "RTEWriteSpec": ...
|
||||
@staticmethod
|
||||
def unsharded() -> "MemWalWriteSpec": ...
|
||||
def with_maintained_indexes(
|
||||
self, indexes: Optional[List[str]]
|
||||
) -> "MemWalWriteSpec":
|
||||
"""Set which indexes the MemWAL keeps up to date. None resolves every
|
||||
def unsharded() -> "RTEWriteSpec": ...
|
||||
def with_maintained_indexes(self, indexes: Optional[List[str]]) -> "RTEWriteSpec":
|
||||
"""Set which indexes the RTE keeps up to date. None resolves every
|
||||
index on the table at install, failing if one cannot be maintained;
|
||||
a list is verbatim, empty means none."""
|
||||
...
|
||||
def with_writer_config_defaults(
|
||||
self, defaults: Dict[str, str]
|
||||
) -> "MemWalWriteSpec":
|
||||
def with_writer_config_defaults(self, defaults: Dict[str, str]) -> "RTEWriteSpec":
|
||||
"""Return a copy of this spec recording the given default
|
||||
`ShardWriter` configuration in the MemWAL index."""
|
||||
...
|
||||
@@ -872,7 +868,7 @@ class MemWalWriteSpec:
|
||||
def num_buckets(self) -> Optional[int]: ...
|
||||
@property
|
||||
def maintained_indexes(self) -> Optional[List[str]]:
|
||||
"""Indexes the MemWAL keeps up to date, or None for every supported one."""
|
||||
"""Indexes the RTE keeps up to date, or None for every supported one."""
|
||||
...
|
||||
@property
|
||||
def writer_config_defaults(self) -> Dict[str, str]: ...
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""WAL-PK-FUSION: hybrid search's primary-key fallback for MemWAL tables.
|
||||
"""WAL-PK-FUSION: hybrid search's primary-key fallback for RTE tables.
|
||||
|
||||
Hybrid search joins its vector and full-text legs on `_rowid`, which a MemWAL
|
||||
Hybrid search joins its vector and full-text legs on `_rowid`, which an RTE
|
||||
table cannot supply: the fresh tier has no stable row id, so the server rejects
|
||||
`with_row_id` before it plans. When that happens the legs are joined on a
|
||||
surrogate `_rowid` built from the table's primary key instead.
|
||||
|
||||
This is a stopgap until MemWAL supports `_rowid`, and everything it needs lives
|
||||
This is a stopgap until RTE supports `_rowid`, and everything it needs lives
|
||||
here so it can be removed in one pass:
|
||||
|
||||
1. Delete this file and `tests/test_wal_hybrid.py`.
|
||||
@@ -69,21 +69,21 @@ def _pk_columns(schema: pa.Schema) -> List[str]:
|
||||
# builds it from the same words -- so this substring survives either path and
|
||||
# the wrapping each adds. It is a coupling to a message rather than a code,
|
||||
# because the refusal arrives as a generic 400; if the server ever rewords it
|
||||
# the fallback stops firing and hybrid on a MemWAL table errors visibly again,
|
||||
# the fallback stops firing and hybrid on an RTE table errors visibly again,
|
||||
# which is loud rather than silently wrong.
|
||||
_WAL_ROW_ID_REFUSAL = "does not support with_row_id"
|
||||
|
||||
WAL_ROW_ID_UNSUPPORTED = (
|
||||
"hybrid search on a MemWAL table cannot return _rowid: the fresh tier has "
|
||||
"hybrid search on an RTE table cannot return _rowid: the fresh tier has "
|
||||
"no stable row id, and the ids the fusion joins on are synthesized from "
|
||||
"the primary key. Set use_memwal(False) to read the base table only (results "
|
||||
"will exclude un-compacted MemWAL data)"
|
||||
"the primary key. Set use_rte(False) to read the base table only (results "
|
||||
"will exclude un-compacted RTE data)"
|
||||
)
|
||||
|
||||
|
||||
def _is_wal_row_id_refusal(error: BaseException) -> bool:
|
||||
"""Whether `error` is the server declining `_rowid` because the table is
|
||||
MemWAL-backed, as opposed to any other failure the query might hit."""
|
||||
RTE-backed, as opposed to any other failure the query might hit."""
|
||||
return _WAL_ROW_ID_REFUSAL in str(error)
|
||||
|
||||
|
||||
@@ -112,7 +112,7 @@ def _stamp_surrogate_row_ids(
|
||||
"""Give each table a `_rowid` column derived from its primary key.
|
||||
|
||||
The fusion only ever compares that column for equality — to deduplicate, to
|
||||
group by in a reranker, and to restore the original scores — so on a MemWAL
|
||||
group by in a reranker, and to restore the original scores — so on an RTE
|
||||
table, where the server has no stable row id to hand out, any injective
|
||||
mapping of the primary key does the same job. Ids are assigned in first-seen
|
||||
order across `tables`, so passing them in fusion order (vector, then FTS)
|
||||
@@ -124,7 +124,7 @@ def _stamp_surrogate_row_ids(
|
||||
"""
|
||||
if not pk_columns:
|
||||
raise ValueError(
|
||||
"hybrid search on a MemWAL table needs an unenforced primary key to "
|
||||
"hybrid search on an RTE table needs an unenforced primary key to "
|
||||
"deduplicate on, and this table declares none"
|
||||
)
|
||||
|
||||
@@ -151,13 +151,13 @@ def _stamp_surrogate_row_ids(
|
||||
return stamped
|
||||
|
||||
|
||||
def pk_fusion_learned(table, use_memwal: Optional[bool]) -> bool:
|
||||
def pk_fusion_learned(table, use_rte: Optional[bool]) -> bool:
|
||||
"""Whether a previous hybrid query on `table` was refused `_rowid`, so this
|
||||
one should go straight to the primary key.
|
||||
|
||||
Learned from a refusal, never probed, so asking is free.
|
||||
"""
|
||||
if table is None or use_memwal is False:
|
||||
if table is None or use_rte is False:
|
||||
return False
|
||||
# Only an unambiguous True forks to the key: a table type that answers the
|
||||
# question loosely keeps the `_rowid` path.
|
||||
@@ -165,7 +165,7 @@ def pk_fusion_learned(table, use_memwal: Optional[bool]) -> bool:
|
||||
|
||||
|
||||
class PkFusion:
|
||||
"""How the legs of a hybrid query on a MemWAL table are joined: on a
|
||||
"""How the legs of a hybrid query on an RTE table are joined: on a
|
||||
surrogate `_rowid` built from the primary key."""
|
||||
|
||||
def __init__(self, pk_columns: List[str]):
|
||||
@@ -190,16 +190,16 @@ class PkFusion:
|
||||
# has turned `_with_row_id` on — including `return_score="all"`.
|
||||
if blob_v2_projection_sources(schema, projection):
|
||||
raise NotImplementedError(
|
||||
"hybrid search cannot project a blob column on a MemWAL table: "
|
||||
"hybrid search cannot project a blob column on an RTE table: "
|
||||
"fetching blobs needs a real _rowid, and the fresh tier has no "
|
||||
"stable one. Set use_memwal(False) to read the base table only "
|
||||
"(results will exclude un-compacted MemWAL data)"
|
||||
"stable one. Set use_rte(False) to read the base table only "
|
||||
"(results will exclude un-compacted RTE data)"
|
||||
)
|
||||
return cls(_pk_columns(schema))
|
||||
|
||||
def inject(self, columns):
|
||||
"""`columns` with the key columns it is missing, to project in place of
|
||||
the `_rowid` a MemWAL table would refuse."""
|
||||
the `_rowid` an RTE table would refuse."""
|
||||
columns, self.injected = _with_pk_columns(columns, self.pk_columns)
|
||||
return columns
|
||||
|
||||
@@ -226,7 +226,7 @@ class PkFusion:
|
||||
|
||||
|
||||
def _check_refusal(error: Exception, *, fused: bool, caller_requested_row_id: bool):
|
||||
"""Re-raise `error` unless it is a MemWAL `_rowid` refusal worth retrying on
|
||||
"""Re-raise `error` unless it is an RTE `_rowid` refusal worth retrying on
|
||||
the primary key."""
|
||||
if fused or not _is_wal_row_id_refusal(error):
|
||||
raise error
|
||||
@@ -248,7 +248,7 @@ def with_pk_fallback(
|
||||
`_rowid`.
|
||||
|
||||
`_rowid` is asked for first rather than paying a round trip up front to
|
||||
find out: only a MemWAL table refuses, and the refusal has to be handled
|
||||
find out: only an RTE table refuses, and the refusal has to be handled
|
||||
anyway -- a write spec installed elsewhere can arrive between any two
|
||||
queries. It costs nothing server-side: it is raised before the query is
|
||||
planned. `fused` reports whether the attempt already used the key.
|
||||
|
||||
@@ -37,7 +37,7 @@ class LanceMergeInsertBuilder(object):
|
||||
self._when_not_matched_by_source_condition_expr = None
|
||||
self._timeout = None
|
||||
self._use_index = True
|
||||
self._use_memwal = None
|
||||
self._use_rte = None
|
||||
self._validate_single_shard = None
|
||||
|
||||
def when_matched_update_all(
|
||||
@@ -115,22 +115,22 @@ class LanceMergeInsertBuilder(object):
|
||||
self._use_index = use_index
|
||||
return self
|
||||
|
||||
def use_memwal(self, enable: bool) -> LanceMergeInsertBuilder:
|
||||
def use_rte(self, enable: bool) -> LanceMergeInsertBuilder:
|
||||
"""
|
||||
Control MemWAL routing for this merge.
|
||||
Control RTE routing for this merge.
|
||||
|
||||
By default (unset), a `merge_insert` on a table with a MemWAL write spec is
|
||||
By default (unset), a `merge_insert` on a table with an RTE write spec is
|
||||
routed through Lance's MemWAL shard writer, and a table without one uses
|
||||
the standard path.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
enable: bool
|
||||
``True`` forces MemWAL routing and errors if the table has no MemWAL
|
||||
``True`` forces RTE routing and errors if the table has no RTE
|
||||
write spec. ``False`` forces the standard write path even when a spec
|
||||
is set.
|
||||
"""
|
||||
self._use_memwal = enable
|
||||
self._use_rte = enable
|
||||
return self
|
||||
|
||||
def validate_single_shard(
|
||||
@@ -139,13 +139,13 @@ class LanceMergeInsertBuilder(object):
|
||||
"""
|
||||
Controls how an LSM merge checks that its input targets a single shard.
|
||||
|
||||
When a table has a MemWAL write spec, every row in a `merge_insert` call
|
||||
When a table has an RTE write spec, every row in a `merge_insert` call
|
||||
must route to the same shard. When `True` (the default), every row is
|
||||
inspected to verify this. When `False`, only the first row is inspected
|
||||
and the shard it routes to is used for the whole input — a faster path
|
||||
for callers that have already pre-sharded their input.
|
||||
|
||||
Has no effect on tables without a MemWAL write spec.
|
||||
Has no effect on tables without an RTE write spec.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
|
||||
@@ -48,7 +48,7 @@ class PermutationBuilder:
|
||||
By default, the permutation builder will create a single split that contains all
|
||||
rows in the same order as the base table.
|
||||
|
||||
Tables with a MemWAL write spec are rejected: unflushed rows have no row id.
|
||||
Tables with an RTE write spec are rejected: unflushed rows have no row id.
|
||||
"""
|
||||
self._async = async_permutation_builder(table)
|
||||
|
||||
|
||||
@@ -887,10 +887,10 @@ class Query(pydantic.BaseModel):
|
||||
# if true, will only search the indexed data
|
||||
fast_search: Optional[bool] = None
|
||||
|
||||
# MemWAL LSM read routing: None auto-routes when the table carries a write
|
||||
# RTE LSM read routing: None auto-routes when the table carries a write
|
||||
# spec, True forces the LSM scanner (errors without a spec), False reads the
|
||||
# base table only
|
||||
use_memwal: Optional[bool] = None
|
||||
use_rte: Optional[bool] = None
|
||||
|
||||
# size of the nearest neighbor list maintained during HNSW search
|
||||
ef: Optional[int] = None
|
||||
@@ -910,9 +910,9 @@ class Query(pydantic.BaseModel):
|
||||
query.full_text_query = req.full_text_search
|
||||
query.columns = req.select
|
||||
query.with_row_id = req.with_row_id
|
||||
# use_memwal is a genuine tri-state (None / True / False); preserve it as-is
|
||||
# use_rte is a genuine tri-state (None / True / False); preserve it as-is
|
||||
# so a round-tripped query keeps an explicit False.
|
||||
query.use_memwal = req.use_memwal
|
||||
query.use_rte = req.use_rte
|
||||
query.vector_column = req.column
|
||||
query.vector = req.query_vector
|
||||
query.distance_type = req.distance_type
|
||||
@@ -1085,7 +1085,7 @@ class LanceQueryBuilder(ABC):
|
||||
self._with_row_address = None
|
||||
self._fragments = None
|
||||
self._fragment_ids = None
|
||||
self._use_memwal = None
|
||||
self._use_rte = None
|
||||
self._vector = None
|
||||
self._text = None
|
||||
self._ef = None
|
||||
@@ -1520,10 +1520,10 @@ class LanceQueryBuilder(ABC):
|
||||
self._fragment_ids = fragment_ids
|
||||
return self
|
||||
|
||||
def use_memwal(self, enable: bool) -> Self:
|
||||
"""Control MemWAL LSM read routing for this query.
|
||||
def use_rte(self, enable: bool) -> Self:
|
||||
"""Control RTE LSM read routing for this query.
|
||||
|
||||
By default (unset), a query against a table with a MemWAL write spec is
|
||||
By default (unset), a query against a table with an RTE write spec is
|
||||
routed through the LSM scanner so it also returns data written via the
|
||||
``merge_insert`` LSM path that has not yet been compacted into the base
|
||||
table (active/frozen memtables + SSTables); a table without a
|
||||
@@ -1532,8 +1532,8 @@ class LanceQueryBuilder(ABC):
|
||||
Parameters
|
||||
----------
|
||||
enable : bool
|
||||
``True`` forces the LSM scanner and errors if the table has no MemWAL
|
||||
write spec. ``False`` bypasses the MemWAL and reads the base table
|
||||
``True`` forces the LSM scanner and errors if the table has no RTE
|
||||
write spec. ``False`` bypasses the RTE and reads the base table
|
||||
only, even when a spec is present.
|
||||
|
||||
Returns
|
||||
@@ -1541,7 +1541,7 @@ class LanceQueryBuilder(ABC):
|
||||
LanceQueryBuilder
|
||||
The LanceQueryBuilder object.
|
||||
"""
|
||||
self._use_memwal = enable
|
||||
self._use_rte = enable
|
||||
return self
|
||||
|
||||
def explain_plan(self, verbose: Optional[bool] = False) -> str:
|
||||
@@ -1878,7 +1878,7 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
|
||||
probing may continue when too few candidates are found. Any explicit
|
||||
effort, including 0.5, overrides nprobes in either call order. Explicit
|
||||
minimum and maximum bounds still apply. This is not a recall guarantee
|
||||
and does not change refinement or HNSW ef. MemWAL LSM queries do not
|
||||
and does not change refinement or HNSW ef. RTE LSM queries do not
|
||||
yet support this option.
|
||||
|
||||
Examples
|
||||
@@ -2055,7 +2055,7 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
|
||||
with_row_address=self._with_row_address,
|
||||
fragments=self._fragments,
|
||||
fragment_ids=self._fragment_ids,
|
||||
use_memwal=self._use_memwal,
|
||||
use_rte=self._use_rte,
|
||||
offset=self._offset,
|
||||
fast_search=self._fast_search,
|
||||
ef=self._ef,
|
||||
@@ -2280,7 +2280,7 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
|
||||
with_row_address=self._with_row_address,
|
||||
fragments=self._fragments,
|
||||
fragment_ids=self._fragment_ids,
|
||||
use_memwal=self._use_memwal,
|
||||
use_rte=self._use_rte,
|
||||
full_text_query=FullTextSearchQuery(
|
||||
query=self._query_with_phrase_semantics(), columns=self._fts_columns
|
||||
),
|
||||
@@ -2362,7 +2362,7 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder):
|
||||
with_row_address=self._with_row_address,
|
||||
fragments=self._fragments,
|
||||
fragment_ids=self._fragment_ids,
|
||||
use_memwal=self._use_memwal,
|
||||
use_rte=self._use_rte,
|
||||
offset=self._offset,
|
||||
order_by=self._order_by,
|
||||
)
|
||||
@@ -2458,7 +2458,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
|
||||
"""Set whether to return row ids.
|
||||
|
||||
Recorded separately from `_with_row_id`, which `rerank(return_score=
|
||||
"all")` also sets for its own use — on a MemWAL table only a caller who
|
||||
"all")` also sets for its own use — on an RTE table only a caller who
|
||||
asked is refused, and the reranker still falls back to the primary key.
|
||||
"""
|
||||
self._caller_requested_row_id = with_row_id
|
||||
@@ -2728,7 +2728,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
|
||||
if reranker.score == "all":
|
||||
# WAL-PK-FUSION: without the fallback, `self.with_row_id(True)`.
|
||||
# Not through `with_row_id`, which records caller intent: the
|
||||
# reranker's need for row ids must not refuse a MemWAL table.
|
||||
# reranker's need for row ids must not refuse an RTE table.
|
||||
self._with_row_id = True
|
||||
|
||||
return self
|
||||
@@ -2766,7 +2766,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
|
||||
probing may continue when too few candidates are found. Any explicit
|
||||
effort, including 0.5, overrides nprobes in either call order. Explicit
|
||||
minimum and maximum bounds still apply. This is not a recall guarantee
|
||||
and does not change refinement or HNSW ef. MemWAL LSM queries do not
|
||||
and does not change refinement or HNSW ef. RTE LSM queries do not
|
||||
yet support this option.
|
||||
|
||||
Examples
|
||||
@@ -3040,7 +3040,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
|
||||
# WAL-PK-FUSION: without the fallback, select `self._columns` as is.
|
||||
self._pk_fusion = None
|
||||
columns = self._columns
|
||||
if _wal_hybrid.pk_fusion_learned(self._table, self._use_memwal):
|
||||
if _wal_hybrid.pk_fusion_learned(self._table, self._use_rte):
|
||||
self._pk_fusion = _wal_hybrid.PkFusion.for_query(
|
||||
self._table.schema,
|
||||
self._columns,
|
||||
@@ -3057,9 +3057,9 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
|
||||
if self._with_row_id and self._pk_fusion is None:
|
||||
self._vector_query.with_row_id(True)
|
||||
self._fts_query.with_row_id(True)
|
||||
if self._use_memwal is not None:
|
||||
self._vector_query.use_memwal(self._use_memwal)
|
||||
self._fts_query.use_memwal(self._use_memwal)
|
||||
if self._use_rte is not None:
|
||||
self._vector_query.use_rte(self._use_rte)
|
||||
self._fts_query.use_rte(self._use_rte)
|
||||
if self._phrase_query:
|
||||
self._fts_query.phrase_query(True)
|
||||
if self._distance_type:
|
||||
@@ -3723,12 +3723,12 @@ class AsyncStandardQuery(AsyncQueryBase):
|
||||
self._inner.fast_search()
|
||||
return self
|
||||
|
||||
def use_memwal(self, enable: bool) -> Self:
|
||||
def use_rte(self, enable: bool) -> Self:
|
||||
"""
|
||||
Control MemWAL LSM read routing for this query.
|
||||
Control RTE LSM read routing for this query.
|
||||
|
||||
By default (unset), a query against a table with a MemWAL write spec (see
|
||||
[AsyncTable.enable_memwal][lancedb.table.AsyncTable.enable_memwal])
|
||||
By default (unset), a query against a table with an RTE write spec (see
|
||||
[AsyncTable.enable_rte][lancedb.table.AsyncTable.enable_rte])
|
||||
is routed through the LSM scanner so it also returns data written via the
|
||||
``merge_insert`` LSM path that has not yet been compacted into the base
|
||||
table (the active/frozen in-memory memtables and the SSTables),
|
||||
@@ -3737,11 +3737,11 @@ class AsyncStandardQuery(AsyncQueryBase):
|
||||
Parameters
|
||||
----------
|
||||
enable : bool
|
||||
``True`` forces the LSM scanner and errors if the table has no MemWAL
|
||||
write spec. ``False`` bypasses the MemWAL and reads the base table
|
||||
``True`` forces the LSM scanner and errors if the table has no RTE
|
||||
write spec. ``False`` bypasses the RTE and reads the base table
|
||||
only, even when a spec is present.
|
||||
"""
|
||||
self._inner.use_memwal(enable)
|
||||
self._inner.use_rte(enable)
|
||||
return self
|
||||
|
||||
def postfilter(self) -> Self:
|
||||
@@ -4064,7 +4064,7 @@ class AsyncVectorQueryBase:
|
||||
minimum and maximum bounds remain effective. Zero starts at the caller
|
||||
minimum and one searches all partitions within the maximum. Later
|
||||
probing may continue to obtain enough candidates. This is not a recall
|
||||
guarantee and does not change refinement or HNSW ef. MemWAL LSM queries
|
||||
guarantee and does not change refinement or HNSW ef. RTE LSM queries
|
||||
do not yet support this option.
|
||||
|
||||
Examples
|
||||
@@ -4388,7 +4388,7 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
|
||||
# WAL-PK-FUSION: without the fallback, keep only the two `with_row_id`
|
||||
# calls.
|
||||
self._pk_fusion = None
|
||||
if _wal_hybrid.pk_fusion_learned(self._table, fts_req.use_memwal):
|
||||
if _wal_hybrid.pk_fusion_learned(self._table, fts_req.use_rte):
|
||||
self._pk_fusion = _wal_hybrid.PkFusion.for_query(
|
||||
await self._table.schema(),
|
||||
_query_request_projection(fts_req),
|
||||
@@ -4577,13 +4577,13 @@ class AsyncTakeQuery(AsyncQueryBase):
|
||||
def __init__(self, inner: LanceTakeQuery, table: Optional["AsyncTable"] = None):
|
||||
super().__init__(inner, table)
|
||||
|
||||
def use_memwal(self, enable: bool) -> "AsyncTakeQuery":
|
||||
"""Control MemWAL LSM read routing for this take query.
|
||||
def use_rte(self, enable: bool) -> "AsyncTakeQuery":
|
||||
"""Control RTE LSM read routing for this take query.
|
||||
|
||||
``False`` bypasses the MemWAL and reads the base table only — the escape
|
||||
``False`` bypasses the RTE and reads the base table only — the escape
|
||||
hatch, since take-by-row-id/offset is not supported on the LSM scanner.
|
||||
"""
|
||||
self._inner.use_memwal(enable)
|
||||
self._inner.use_rte(enable)
|
||||
return self
|
||||
|
||||
async def _plain_scan_to_pandas(
|
||||
@@ -4644,14 +4644,14 @@ class BaseQueryBuilder(object):
|
||||
self._inner.with_row_id()
|
||||
return self
|
||||
|
||||
def use_memwal(self, enable: bool) -> Self:
|
||||
def use_rte(self, enable: bool) -> Self:
|
||||
"""
|
||||
Control MemWAL LSM read routing for this query.
|
||||
Control RTE LSM read routing for this query.
|
||||
|
||||
``False`` bypasses the MemWAL and reads the base table only, the escape
|
||||
``False`` bypasses the RTE and reads the base table only, the escape
|
||||
hatch for shapes the LSM scanner cannot honor (e.g. take-by-row-id).
|
||||
"""
|
||||
self._inner.use_memwal(enable)
|
||||
self._inner.use_rte(enable)
|
||||
return self
|
||||
|
||||
def with_row_address(self, with_row_address: bool = True) -> Self:
|
||||
|
||||
@@ -31,7 +31,7 @@ from lancedb._lancedb import (
|
||||
DropColumnsResult,
|
||||
FtsToken,
|
||||
IndexConfig,
|
||||
MemWalWriteSpec,
|
||||
RTEWriteSpec,
|
||||
MergeResult,
|
||||
UpdateResult,
|
||||
)
|
||||
@@ -1037,17 +1037,17 @@ class RemoteTable(Table):
|
||||
"""Set the unenforced primary key for this table to a single column."""
|
||||
return LOOP.run(self._table.set_unenforced_primary_key(columns))
|
||||
|
||||
def enable_memwal(self, spec: "MemWalWriteSpec") -> None:
|
||||
"""Install an MemWalWriteSpec."""
|
||||
return LOOP.run(self._table.enable_memwal(spec))
|
||||
def enable_rte(self, spec: "RTEWriteSpec") -> None:
|
||||
"""Install an RTEWriteSpec."""
|
||||
return LOOP.run(self._table.enable_rte(spec))
|
||||
|
||||
def disable_memwal(self) -> None:
|
||||
"""Remove the MemWalWriteSpec."""
|
||||
return LOOP.run(self._table.disable_memwal())
|
||||
def disable_rte(self) -> None:
|
||||
"""Remove the RTEWriteSpec."""
|
||||
return LOOP.run(self._table.disable_rte())
|
||||
|
||||
def get_memwal_spec(self) -> Optional["MemWalWriteSpec"]:
|
||||
"""Read the installed MemWalWriteSpec, or ``None``."""
|
||||
return LOOP.run(self._table.get_memwal_spec())
|
||||
def get_rte_spec(self) -> Optional["RTEWriteSpec"]:
|
||||
"""Read the installed RTEWriteSpec, or ``None``."""
|
||||
return LOOP.run(self._table.get_rte_spec())
|
||||
|
||||
# WAL-PK-FUSION: delete both hooks.
|
||||
def _hybrid_pk_fusion_learned(self) -> bool:
|
||||
@@ -1057,31 +1057,31 @@ class RemoteTable(Table):
|
||||
def _note_hybrid_pk_fusion(self) -> None:
|
||||
self._table._note_hybrid_pk_fusion()
|
||||
|
||||
def checkpoint_memwal(self) -> None:
|
||||
def checkpoint_rte(self) -> None:
|
||||
"""Synchronous version of
|
||||
[`AsyncTable.checkpoint_memwal`][lancedb.AsyncTable.checkpoint_memwal]."""
|
||||
return LOOP.run(self._table.checkpoint_memwal())
|
||||
[`AsyncTable.checkpoint_rte`][lancedb.AsyncTable.checkpoint_rte]."""
|
||||
return LOOP.run(self._table.checkpoint_rte())
|
||||
|
||||
def flush_memwal(self) -> None:
|
||||
def flush_rte(self) -> None:
|
||||
"""Synchronous version of
|
||||
[`AsyncTable.flush_memwal`][lancedb.AsyncTable.flush_memwal]."""
|
||||
return LOOP.run(self._table.flush_memwal())
|
||||
[`AsyncTable.flush_rte`][lancedb.AsyncTable.flush_rte]."""
|
||||
return LOOP.run(self._table.flush_rte())
|
||||
|
||||
def compact_memwal(self) -> None:
|
||||
def compact_rte(self) -> None:
|
||||
"""Synchronous version of
|
||||
[`AsyncTable.compact_memwal`][lancedb.AsyncTable.compact_memwal]."""
|
||||
return LOOP.run(self._table.compact_memwal())
|
||||
[`AsyncTable.compact_rte`][lancedb.AsyncTable.compact_rte]."""
|
||||
return LOOP.run(self._table.compact_rte())
|
||||
|
||||
def get_memwal_stats(self, *, include_sstable_rows: bool = False) -> Optional[dict]:
|
||||
def get_rte_stats(self, *, include_sstable_rows: bool = False) -> Optional[dict]:
|
||||
"""Synchronous version of
|
||||
[`AsyncTable.get_memwal_stats`][lancedb.AsyncTable.get_memwal_stats]."""
|
||||
[`AsyncTable.get_rte_stats`][lancedb.AsyncTable.get_rte_stats]."""
|
||||
return LOOP.run(
|
||||
self._table.get_memwal_stats(include_sstable_rows=include_sstable_rows)
|
||||
self._table.get_rte_stats(include_sstable_rows=include_sstable_rows)
|
||||
)
|
||||
|
||||
def close_memwal_writers(self) -> None:
|
||||
def close_rte_writers(self) -> None:
|
||||
"""No-op for remote tables (no local shard writers)."""
|
||||
return LOOP.run(self._table.close_memwal_writers())
|
||||
return LOOP.run(self._table.close_rte_writers())
|
||||
|
||||
def drop_index(self, index_name: str):
|
||||
return LOOP.run(self._table.drop_index(index_name))
|
||||
|
||||
@@ -223,7 +223,7 @@ if TYPE_CHECKING:
|
||||
DeleteResult,
|
||||
DropColumnsResult,
|
||||
FtsToken,
|
||||
MemWalWriteSpec,
|
||||
RTEWriteSpec,
|
||||
MergeResult,
|
||||
UpdateResult,
|
||||
)
|
||||
@@ -4849,47 +4849,47 @@ class LanceTable(Table):
|
||||
[`AsyncTable.set_unenforced_primary_key`][lancedb.AsyncTable.set_unenforced_primary_key]."""
|
||||
return LOOP.run(self._table.set_unenforced_primary_key(columns))
|
||||
|
||||
def enable_memwal(self, spec: "MemWalWriteSpec") -> None:
|
||||
"""Install an MemWalWriteSpec. See
|
||||
[`AsyncTable.enable_memwal`][lancedb.AsyncTable.enable_memwal]."""
|
||||
return LOOP.run(self._table.enable_memwal(spec))
|
||||
def enable_rte(self, spec: "RTEWriteSpec") -> None:
|
||||
"""Install an RTEWriteSpec. See
|
||||
[`AsyncTable.enable_rte`][lancedb.AsyncTable.enable_rte]."""
|
||||
return LOOP.run(self._table.enable_rte(spec))
|
||||
|
||||
def disable_memwal(self) -> None:
|
||||
"""Remove the MemWalWriteSpec. See
|
||||
[`AsyncTable.disable_memwal`][lancedb.AsyncTable.disable_memwal]."""
|
||||
return LOOP.run(self._table.disable_memwal())
|
||||
def disable_rte(self) -> None:
|
||||
"""Remove the RTEWriteSpec. See
|
||||
[`AsyncTable.disable_rte`][lancedb.AsyncTable.disable_rte]."""
|
||||
return LOOP.run(self._table.disable_rte())
|
||||
|
||||
def get_memwal_spec(self) -> Optional["MemWalWriteSpec"]:
|
||||
"""Read the installed MemWalWriteSpec, or ``None``. See
|
||||
[`AsyncTable.get_memwal_spec`][lancedb.AsyncTable.get_memwal_spec]."""
|
||||
return LOOP.run(self._table.get_memwal_spec())
|
||||
def get_rte_spec(self) -> Optional["RTEWriteSpec"]:
|
||||
"""Read the installed RTEWriteSpec, or ``None``. See
|
||||
[`AsyncTable.get_rte_spec`][lancedb.AsyncTable.get_rte_spec]."""
|
||||
return LOOP.run(self._table.get_rte_spec())
|
||||
|
||||
def checkpoint_memwal(self) -> None:
|
||||
def checkpoint_rte(self) -> None:
|
||||
"""Synchronous version of
|
||||
[`AsyncTable.checkpoint_memwal`][lancedb.AsyncTable.checkpoint_memwal]."""
|
||||
return LOOP.run(self._table.checkpoint_memwal())
|
||||
[`AsyncTable.checkpoint_rte`][lancedb.AsyncTable.checkpoint_rte]."""
|
||||
return LOOP.run(self._table.checkpoint_rte())
|
||||
|
||||
def flush_memwal(self) -> None:
|
||||
def flush_rte(self) -> None:
|
||||
"""Synchronous version of
|
||||
[`AsyncTable.flush_memwal`][lancedb.AsyncTable.flush_memwal]."""
|
||||
return LOOP.run(self._table.flush_memwal())
|
||||
[`AsyncTable.flush_rte`][lancedb.AsyncTable.flush_rte]."""
|
||||
return LOOP.run(self._table.flush_rte())
|
||||
|
||||
def compact_memwal(self) -> None:
|
||||
def compact_rte(self) -> None:
|
||||
"""Synchronous version of
|
||||
[`AsyncTable.compact_memwal`][lancedb.AsyncTable.compact_memwal]."""
|
||||
return LOOP.run(self._table.compact_memwal())
|
||||
[`AsyncTable.compact_rte`][lancedb.AsyncTable.compact_rte]."""
|
||||
return LOOP.run(self._table.compact_rte())
|
||||
|
||||
def get_memwal_stats(self, *, include_sstable_rows: bool = False) -> Optional[dict]:
|
||||
def get_rte_stats(self, *, include_sstable_rows: bool = False) -> Optional[dict]:
|
||||
"""Synchronous version of
|
||||
[`AsyncTable.get_memwal_stats`][lancedb.AsyncTable.get_memwal_stats]."""
|
||||
[`AsyncTable.get_rte_stats`][lancedb.AsyncTable.get_rte_stats]."""
|
||||
return LOOP.run(
|
||||
self._table.get_memwal_stats(include_sstable_rows=include_sstable_rows)
|
||||
self._table.get_rte_stats(include_sstable_rows=include_sstable_rows)
|
||||
)
|
||||
|
||||
def close_memwal_writers(self) -> None:
|
||||
"""Close cached MemWAL shard writers. See
|
||||
[`AsyncTable.close_memwal_writers`][lancedb.AsyncTable.close_memwal_writers]."""
|
||||
return LOOP.run(self._table.close_memwal_writers())
|
||||
def close_rte_writers(self) -> None:
|
||||
"""Close cached RTE shard writers. See
|
||||
[`AsyncTable.close_rte_writers`][lancedb.AsyncTable.close_rte_writers]."""
|
||||
return LOOP.run(self._table.close_rte_writers())
|
||||
|
||||
def uses_v2_manifest_paths(self) -> bool:
|
||||
"""
|
||||
@@ -5547,24 +5547,24 @@ class AsyncTable:
|
||||
columns = list(columns)
|
||||
await self._inner.set_unenforced_primary_key(columns)
|
||||
|
||||
async def enable_memwal(self, spec: "MemWalWriteSpec") -> None:
|
||||
"""Install an MemWalWriteSpec on this table.
|
||||
async def enable_rte(self, spec: "RTEWriteSpec") -> None:
|
||||
"""Install an RTEWriteSpec on this table.
|
||||
|
||||
The spec selects Lance's MemWAL LSM-style write path for future
|
||||
`merge_insert` calls. ``MemWalWriteSpec`` chooses one of three sharding
|
||||
`merge_insert` calls. ``RTEWriteSpec`` chooses one of three sharding
|
||||
strategies:
|
||||
|
||||
- ``MemWalWriteSpec.bucket(column, num_buckets)`` — hash-bucket writes by
|
||||
- ``RTEWriteSpec.bucket(column, num_buckets)`` — hash-bucket writes by
|
||||
the single-column unenforced primary key.
|
||||
- ``MemWalWriteSpec.identity(column)`` — shard by the raw value of a
|
||||
- ``RTEWriteSpec.identity(column)`` — shard by the raw value of a
|
||||
scalar column.
|
||||
- ``MemWalWriteSpec.unsharded()`` — route every write to a single shard.
|
||||
- ``RTEWriteSpec.unsharded()`` — route every write to a single shard.
|
||||
|
||||
All variants require the table to have an unenforced primary key set
|
||||
via [`set_unenforced_primary_key`]; bucket sharding additionally
|
||||
requires it to be the single column being bucketed.
|
||||
|
||||
By default the MemWAL maintains every index on the table, resolved
|
||||
By default the RTE maintains every index on the table, resolved
|
||||
here — a snapshot, so an index created afterwards needs the spec unset
|
||||
and set again. This fails if one cannot be maintained; name the set
|
||||
with ``with_maintained_indexes`` to install anyway. That pins an exact
|
||||
@@ -5573,30 +5573,30 @@ class AsyncTable:
|
||||
|
||||
Parameters
|
||||
----------
|
||||
spec : MemWalWriteSpec
|
||||
spec : RTEWriteSpec
|
||||
The sharding spec to install.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> from lancedb import MemWalWriteSpec
|
||||
>>> from lancedb import RTEWriteSpec
|
||||
>>> # table.set_unenforced_primary_key("id")
|
||||
>>> # table.enable_memwal(MemWalWriteSpec.bucket("id", 16))
|
||||
>>> # table.enable_rte(RTEWriteSpec.bucket("id", 16))
|
||||
"""
|
||||
await self._inner.enable_memwal(spec)
|
||||
await self._inner.enable_rte(spec)
|
||||
|
||||
async def disable_memwal(self) -> None:
|
||||
"""Remove the MemWalWriteSpec from this table.
|
||||
async def disable_rte(self) -> None:
|
||||
"""Remove the RTEWriteSpec from this table.
|
||||
|
||||
Reverts to the standard `merge_insert` write path. Errors if no spec
|
||||
is currently set.
|
||||
"""
|
||||
await self._inner.disable_memwal()
|
||||
await self._inner.disable_rte()
|
||||
|
||||
async def get_memwal_spec(self) -> Optional["MemWalWriteSpec"]:
|
||||
"""Read the MemWalWriteSpec currently installed on this table.
|
||||
async def get_rte_spec(self) -> Optional["RTEWriteSpec"]:
|
||||
"""Read the RTEWriteSpec currently installed on this table.
|
||||
|
||||
Returns ``None`` when the MemWAL write path is not enabled at all — no
|
||||
spec has been set, or one was removed with `disable_memwal`.
|
||||
Returns ``None`` when the RTE write path is not enabled at all — no
|
||||
spec has been set, or one was removed with `disable_rte`.
|
||||
That is a different answer from a spec whose ``maintained_indexes``
|
||||
is ``None``, which is an installed spec selecting indexes
|
||||
automatically.
|
||||
@@ -5606,7 +5606,7 @@ class AsyncTable:
|
||||
or gains later, ``[]`` maintains none, and a non-empty list maintains
|
||||
exactly those. All three round-trip.
|
||||
"""
|
||||
return await self._inner.get_memwal_spec()
|
||||
return await self._inner.get_rte_spec()
|
||||
|
||||
# WAL-PK-FUSION: delete both hooks.
|
||||
def _hybrid_pk_fusion_learned(self) -> bool:
|
||||
@@ -5617,12 +5617,12 @@ class AsyncTable:
|
||||
"""See [`Table._note_hybrid_pk_fusion`][lancedb.table.Table]."""
|
||||
self._inner.note_hybrid_pk_fusion()
|
||||
|
||||
async def checkpoint_memwal(self) -> None:
|
||||
"""Converge this table's MemWAL write path into its base table.
|
||||
async def checkpoint_rte(self) -> None:
|
||||
"""Converge this table's RTE write path into its base table.
|
||||
|
||||
One flush, freezing every memtable into an SSTable, then compaction triggers
|
||||
until every SSTable that existed at that moment has reached base.
|
||||
The loop runs client-side, reading progress from ``get_memwal_stats``.
|
||||
The loop runs client-side, reading progress from ``get_rte_stats``.
|
||||
|
||||
Best-effort: SSTables created *while* it runs are deliberately not
|
||||
waited on, which is what lets it terminate on a table taking writes.
|
||||
@@ -5637,56 +5637,56 @@ class AsyncTable:
|
||||
``asyncio.wait_for`` for a wall-clock bound; abandoning it partway
|
||||
costs nothing.
|
||||
"""
|
||||
await self._inner.checkpoint_memwal()
|
||||
await self._inner.checkpoint_rte()
|
||||
|
||||
async def flush_memwal(self) -> None:
|
||||
async def flush_rte(self) -> None:
|
||||
"""Freeze every table shard's active memtable into an SSTable.
|
||||
|
||||
Does not touch the base table — compacting SSTables into base is
|
||||
`compact_memwal`. On a node that has not claimed this table, this claims
|
||||
`compact_rte`. On a node that has not claimed this table, this claims
|
||||
it and replays its WAL log first.
|
||||
"""
|
||||
await self._inner.flush_memwal()
|
||||
await self._inner.flush_rte()
|
||||
|
||||
async def compact_memwal(self) -> None:
|
||||
async def compact_rte(self) -> None:
|
||||
"""Trigger a background SSTable compaction pass per table shard.
|
||||
|
||||
Returns once the passes are dispatched, not once they finish: watch
|
||||
``get_memwal_stats`` for progress, or use ``checkpoint_memwal`` to loop
|
||||
``get_rte_stats`` for progress, or use ``checkpoint_rte`` to loop
|
||||
until the current SSTables have reached base.
|
||||
"""
|
||||
await self._inner.compact_memwal()
|
||||
await self._inner.compact_rte()
|
||||
|
||||
async def get_memwal_stats(
|
||||
async def get_rte_stats(
|
||||
self, *, include_sstable_rows: bool = False
|
||||
) -> Optional[dict]:
|
||||
"""Read live per-table-shard MemWAL state.
|
||||
"""Read live per-table-shard RTE state.
|
||||
|
||||
Answers "how far behind is my fresh tier", "which table shard is hot", and
|
||||
"why is my fresh-tier vector search brute-force". Mutates no table
|
||||
state, though on a node that has not claimed this table it claims it,
|
||||
exactly as a read would.
|
||||
|
||||
Returns ``None`` only when the MemWAL write path is not enabled.
|
||||
Returns ``None`` only when the RTE write path is not enabled.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
include_sstable_rows
|
||||
Report a row count per SSTable. Off by default: each count
|
||||
opens an uncached Lance dataset, and ``checkpoint_memwal`` polls this
|
||||
opens an uncached Lance dataset, and ``checkpoint_rte`` polls this
|
||||
needing only generation numbers.
|
||||
"""
|
||||
return await self._inner.get_memwal_stats(include_sstable_rows)
|
||||
return await self._inner.get_rte_stats(include_sstable_rows)
|
||||
|
||||
async def close_memwal_writers(self) -> None:
|
||||
"""Drain and close any cached MemWAL shard writers for this table.
|
||||
async def close_rte_writers(self) -> None:
|
||||
"""Drain and close any cached RTE shard writers for this table.
|
||||
|
||||
When a MemWAL write spec is installed, `merge_insert` opens MemWAL shard
|
||||
When an RTE write spec is installed, `merge_insert` opens RTE shard
|
||||
writers and caches them for reuse across calls. This closes them,
|
||||
flushing pending data; writers reopen lazily on the next
|
||||
`merge_insert`. It is a no-op when no writers are cached.
|
||||
"""
|
||||
await self._inner.close_memwal_writers()
|
||||
await self._inner.close_rte_writers()
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
@@ -6575,8 +6575,8 @@ class AsyncTable:
|
||||
take_query = self.take_offsets(query.take_offsets)
|
||||
if query.columns:
|
||||
take_query = take_query.select(query.columns)
|
||||
if query.use_memwal is not None:
|
||||
take_query = take_query.use_memwal(query.use_memwal)
|
||||
if query.use_rte is not None:
|
||||
take_query = take_query.use_rte(query.use_rte)
|
||||
if query.with_row_id:
|
||||
take_query = take_query.with_row_id()
|
||||
return take_query
|
||||
@@ -6592,8 +6592,8 @@ class AsyncTable:
|
||||
async_query = async_query.where(query.filter)
|
||||
if query.fast_search:
|
||||
async_query = async_query.fast_search()
|
||||
if query.use_memwal is not None:
|
||||
async_query = async_query.use_memwal(query.use_memwal)
|
||||
if query.use_rte is not None:
|
||||
async_query = async_query.use_rte(query.use_rte)
|
||||
if query.with_row_id:
|
||||
async_query = async_query.with_row_id()
|
||||
if query.order_by:
|
||||
@@ -6719,7 +6719,7 @@ class AsyncTable:
|
||||
when_not_matched_by_source_condition_expr=merge._when_not_matched_by_source_condition_expr,
|
||||
timeout=merge._timeout,
|
||||
use_index=merge._use_index,
|
||||
use_memwal=merge._use_memwal,
|
||||
use_rte=merge._use_rte,
|
||||
validate_single_shard=merge._validate_single_shard,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Tests for the MemWAL LSM ``merge_insert`` dispatch."""
|
||||
"""Tests for the RTE LSM ``merge_insert`` dispatch."""
|
||||
|
||||
from datetime import timedelta
|
||||
|
||||
import lancedb
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
from lancedb._lancedb import MemWalWriteSpec
|
||||
from lancedb._lancedb import RTEWriteSpec
|
||||
from lancedb.index import FTS, IvfPq
|
||||
|
||||
SCHEMA = pa.schema(
|
||||
@@ -49,12 +49,12 @@ def _region_reader(rows):
|
||||
|
||||
|
||||
def _bucket_table(tmp_path):
|
||||
"""A table with ``id`` as the primary key and a single-bucket MemWAL spec."""
|
||||
"""A table with ``id`` as the primary key and a single-bucket RTE spec."""
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
|
||||
table = db.create_table("t", _reader([1, 2, 3]))
|
||||
table.set_unenforced_primary_key("id")
|
||||
# num_buckets = 1: every row routes to the single bucket.
|
||||
table.enable_memwal(MemWalWriteSpec.bucket("id", 1))
|
||||
table.enable_rte(RTEWriteSpec.bucket("id", 1))
|
||||
return table
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@ def test_lsm_merge_insert_bucket(tmp_path):
|
||||
.when_not_matched_insert_all()
|
||||
.execute(_reader([3, 4, 5]))
|
||||
)
|
||||
# LSM path: rows go to the MemWAL, so only num_rows is populated.
|
||||
# LSM path: rows go to the RTE, so only num_rows is populated.
|
||||
assert result.num_rows == 3
|
||||
assert result.version == 0
|
||||
assert result.num_inserted_rows == 0
|
||||
@@ -78,7 +78,7 @@ def test_lsm_merge_insert_unsharded(tmp_path):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
|
||||
table = db.create_table("t", _reader([1, 2, 3]))
|
||||
table.set_unenforced_primary_key("id")
|
||||
table.enable_memwal(MemWalWriteSpec.unsharded())
|
||||
table.enable_rte(RTEWriteSpec.unsharded())
|
||||
result = (
|
||||
table.merge_insert("id")
|
||||
.when_matched_update_all()
|
||||
@@ -92,7 +92,7 @@ def test_lsm_merge_insert_identity(tmp_path):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
|
||||
table = db.create_table("t", _region_reader([(1, "us"), (2, "us")]))
|
||||
table.set_unenforced_primary_key("id")
|
||||
table.enable_memwal(MemWalWriteSpec.identity("region"))
|
||||
table.enable_rte(RTEWriteSpec.identity("region"))
|
||||
# All rows share one identity value, so they route to one shard.
|
||||
result = (
|
||||
table.merge_insert([])
|
||||
@@ -103,31 +103,31 @@ def test_lsm_merge_insert_identity(tmp_path):
|
||||
assert result.num_rows == 2
|
||||
|
||||
|
||||
def test_lsm_merge_insert_use_memwal_false(tmp_path):
|
||||
def test_lsm_merge_insert_use_rte_false(tmp_path):
|
||||
table = _bucket_table(tmp_path) # rows id = 1, 2, 3
|
||||
# use_memwal(False) opts out: the standard path runs and commits even with a spec.
|
||||
# use_rte(False) opts out: the standard path runs and commits even with a spec.
|
||||
result = (
|
||||
table.merge_insert("id")
|
||||
.when_not_matched_insert_all()
|
||||
.use_memwal(False)
|
||||
.use_rte(False)
|
||||
.execute(_reader([3, 4, 5]))
|
||||
)
|
||||
assert result.num_inserted_rows == 2
|
||||
assert table.count_rows() == 5
|
||||
|
||||
|
||||
def test_lsm_merge_insert_use_memwal_true_without_spec_errors(tmp_path):
|
||||
# A table with a primary key but no MemWAL write spec installed.
|
||||
def test_lsm_merge_insert_use_rte_true_without_spec_errors(tmp_path):
|
||||
# A table with a primary key but no RTE write spec installed.
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
|
||||
table = db.create_table("t", _reader([1, 2, 3]))
|
||||
table.set_unenforced_primary_key("id")
|
||||
# use_memwal(True) demands MemWAL routing; without a spec it errors.
|
||||
with pytest.raises(Exception, match="use_memwal"):
|
||||
# use_rte(True) demands RTE routing; without a spec it errors.
|
||||
with pytest.raises(Exception, match="use_rte"):
|
||||
(
|
||||
table.merge_insert("id")
|
||||
.when_matched_update_all()
|
||||
.when_not_matched_insert_all()
|
||||
.use_memwal(True)
|
||||
.use_rte(True)
|
||||
.execute(_reader([3, 4, 5]))
|
||||
)
|
||||
|
||||
@@ -145,7 +145,7 @@ def test_lsm_merge_insert_validate_single_shard_off(tmp_path):
|
||||
|
||||
|
||||
def test_lsm_merge_insert_no_spec_uses_standard_path(tmp_path):
|
||||
# A table with a primary key but no MemWAL write spec installed.
|
||||
# A table with a primary key but no RTE write spec installed.
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
|
||||
table = db.create_table("t", _reader([1, 2, 3]))
|
||||
table.set_unenforced_primary_key("id")
|
||||
@@ -186,7 +186,7 @@ def test_lsm_close_writers(tmp_path):
|
||||
.when_not_matched_insert_all()
|
||||
.execute(_reader([7, 8]))
|
||||
)
|
||||
table.close_memwal_writers()
|
||||
table.close_rte_writers()
|
||||
# The writer reopens lazily on the next merge_insert.
|
||||
result = (
|
||||
table.merge_insert([])
|
||||
@@ -204,14 +204,14 @@ async def test_async_lsm_merge_insert(tmp_path):
|
||||
)
|
||||
table = await db.create_table("t", _reader([1, 2, 3]))
|
||||
await table.set_unenforced_primary_key("id")
|
||||
await table.enable_memwal(MemWalWriteSpec.bucket("id", 1))
|
||||
await table.enable_rte(RTEWriteSpec.bucket("id", 1))
|
||||
|
||||
builder = (
|
||||
table.merge_insert([]).when_matched_update_all().when_not_matched_insert_all()
|
||||
)
|
||||
result = await builder.execute(_reader([3, 4, 5]))
|
||||
assert result.num_rows == 3
|
||||
await table.close_memwal_writers()
|
||||
await table.close_rte_writers()
|
||||
|
||||
|
||||
def _lsm_upsert(table, ids):
|
||||
@@ -228,7 +228,7 @@ def test_lsm_read_sees_active_memtable(tmp_path):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
|
||||
table = db.create_table("t", _reader([1, 2, 3])) # base ids 1,2,3
|
||||
table.set_unenforced_primary_key("id")
|
||||
table.enable_memwal(MemWalWriteSpec.unsharded())
|
||||
table.enable_rte(RTEWriteSpec.unsharded())
|
||||
|
||||
_lsm_upsert(table, [4, 5]) # active memtable only, not committed to base
|
||||
|
||||
@@ -236,8 +236,8 @@ def test_lsm_read_sees_active_memtable(tmp_path):
|
||||
lsm = table.search().to_arrow()
|
||||
assert sorted(lsm["id"].to_pylist()) == [1, 2, 3, 4, 5]
|
||||
|
||||
# use_memwal(False) bypasses the MemWAL and reads the base table only.
|
||||
base_only = table.search().use_memwal(False).to_arrow()
|
||||
# use_rte(False) bypasses the RTE and reads the base table only.
|
||||
base_only = table.search().use_rte(False).to_arrow()
|
||||
assert sorted(base_only["id"].to_pylist()) == [1, 2, 3]
|
||||
|
||||
|
||||
@@ -245,7 +245,7 @@ def test_lsm_read_dedup_newest_wins(tmp_path):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
|
||||
table = db.create_table("t", _reader([1, 2, 3])) # id 2 -> value 1
|
||||
table.set_unenforced_primary_key("id")
|
||||
table.enable_memwal(MemWalWriteSpec.unsharded())
|
||||
table.enable_rte(RTEWriteSpec.unsharded())
|
||||
|
||||
_lsm_upsert(table, [2, 3, 4]) # ids 2,3,4 -> values 0,1,2
|
||||
|
||||
@@ -258,31 +258,31 @@ def test_lsm_read_dedup_newest_wins(tmp_path):
|
||||
def test_lsm_read_without_spec_reads_base(tmp_path):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
|
||||
table = db.create_table("t", _reader([1, 2, 3]))
|
||||
table.set_unenforced_primary_key("id") # no MemWAL write spec
|
||||
table.set_unenforced_primary_key("id") # no RTE write spec
|
||||
|
||||
# No spec: default read and use_memwal(False) both read the base table, no error.
|
||||
# No spec: default read and use_rte(False) both read the base table, no error.
|
||||
assert sorted(table.search().to_arrow()["id"].to_pylist()) == [1, 2, 3]
|
||||
assert sorted(table.search().use_memwal(False).to_arrow()["id"].to_pylist()) == [
|
||||
assert sorted(table.search().use_rte(False).to_arrow()["id"].to_pylist()) == [
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
]
|
||||
|
||||
|
||||
def test_lsm_read_unsupported_shape_errors_without_use_memwal_false(tmp_path):
|
||||
def test_lsm_read_unsupported_shape_errors_without_use_rte_false(tmp_path):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
|
||||
table = db.create_table("t", _reader([1, 2, 3]))
|
||||
table.set_unenforced_primary_key("id")
|
||||
table.enable_memwal(MemWalWriteSpec.unsharded())
|
||||
table.enable_rte(RTEWriteSpec.unsharded())
|
||||
_lsm_upsert(table, [4])
|
||||
|
||||
# with_row_id is unsupported by the LSM scanner; on a MemWAL table the default
|
||||
# with_row_id is unsupported by the LSM scanner; on an RTE table the default
|
||||
# (auto-routed) read hard-errors instead of silently reading a stale base.
|
||||
with pytest.raises(Exception):
|
||||
table.search().with_row_id(True).to_arrow()
|
||||
|
||||
# use_memwal(False) is the escape hatch: it reads the base table only.
|
||||
base = table.search().with_row_id(True).use_memwal(False).to_arrow()
|
||||
# use_rte(False) is the escape hatch: it reads the base table only.
|
||||
base = table.search().with_row_id(True).use_rte(False).to_arrow()
|
||||
assert sorted(base["id"].to_pylist()) == [1, 2, 3]
|
||||
|
||||
|
||||
@@ -293,7 +293,7 @@ async def test_async_lsm_read(tmp_path):
|
||||
)
|
||||
table = await db.create_table("t", _reader([1, 2, 3]))
|
||||
await table.set_unenforced_primary_key("id")
|
||||
await table.enable_memwal(MemWalWriteSpec.unsharded())
|
||||
await table.enable_rte(RTEWriteSpec.unsharded())
|
||||
|
||||
builder = (
|
||||
table.merge_insert([]).when_matched_update_all().when_not_matched_insert_all()
|
||||
@@ -331,7 +331,7 @@ def _vector_reader(rows):
|
||||
def _vector_table(tmp_path):
|
||||
"""Base table whose vector column is indexed so its rows are visible to the LSM
|
||||
vector scanner (the base arm uses ``fast_search`` — indexed data only), plus an
|
||||
unsharded MemWAL spec that maintains that index for the memtable.
|
||||
unsharded RTE spec that maintains that index for the memtable.
|
||||
|
||||
Rows 1,2 are category ``a``, row 3 is ``b``, and 4..60 are filler ``c`` that
|
||||
give the tiny IVF index enough data to train.
|
||||
@@ -353,9 +353,7 @@ def _vector_table(tmp_path):
|
||||
"vector", config=IvfPq(num_partitions=1, num_sub_vectors=2, num_bits=4)
|
||||
)
|
||||
index_name = table.list_indices()[0].name
|
||||
table.enable_memwal(
|
||||
MemWalWriteSpec.unsharded().with_maintained_indexes([index_name])
|
||||
)
|
||||
table.enable_rte(RTEWriteSpec.unsharded().with_maintained_indexes([index_name]))
|
||||
return table
|
||||
|
||||
|
||||
@@ -379,9 +377,9 @@ def test_lsm_read_vector_sees_memtable(tmp_path):
|
||||
assert {1, 2, 3} <= ids # indexed base rows
|
||||
assert 1000 in ids # in-flight memtable row
|
||||
|
||||
# use_memwal(False) bypasses the MemWAL, so the in-flight row is not visible.
|
||||
# use_rte(False) bypasses the RTE, so the in-flight row is not visible.
|
||||
base_ids = set(
|
||||
table.search(query).use_memwal(False).limit(100).to_arrow()["id"].to_pylist()
|
||||
table.search(query).use_rte(False).limit(100).to_arrow()["id"].to_pylist()
|
||||
)
|
||||
assert {1, 2, 3} <= base_ids
|
||||
assert 1000 not in base_ids
|
||||
@@ -453,9 +451,7 @@ def test_lsm_read_fts_sees_memtable(tmp_path):
|
||||
# Native FTS index (tantivy is not compatible with the LSM memtable index).
|
||||
table.create_index("text", config=FTS())
|
||||
index_name = table.list_indices()[0].name
|
||||
table.enable_memwal(
|
||||
MemWalWriteSpec.unsharded().with_maintained_indexes([index_name])
|
||||
)
|
||||
table.enable_rte(RTEWriteSpec.unsharded().with_maintained_indexes([index_name]))
|
||||
|
||||
# in-flight doc 4 lands in the memtable's maintained FTS index.
|
||||
(
|
||||
@@ -498,8 +494,8 @@ def test_lsm_read_vector_unsupported_knobs_error(tmp_path):
|
||||
with pytest.raises(Exception, match="use_index"):
|
||||
table.search(query).bypass_vector_index().to_arrow()
|
||||
|
||||
# use_memwal(False) is the escape hatch: the base-only standard path honors them.
|
||||
base = table.search(query).distance_range(0.0, 100.0).use_memwal(False).to_arrow()
|
||||
# use_rte(False) is the escape hatch: the base-only standard path honors them.
|
||||
base = table.search(query).distance_range(0.0, 100.0).use_rte(False).to_arrow()
|
||||
assert 1000 not in set(base["id"].to_pylist())
|
||||
|
||||
|
||||
@@ -544,7 +540,7 @@ def test_lsm_read_fts_unmaintained_index_errors(tmp_path):
|
||||
table.create_index("text", config=FTS())
|
||||
# No maintained indexes: the active memtable FTS arm cannot serve un-compacted
|
||||
# docs, so the search would silently omit them — reject instead.
|
||||
table.enable_memwal(MemWalWriteSpec.unsharded().with_maintained_indexes([]))
|
||||
table.enable_rte(RTEWriteSpec.unsharded().with_maintained_indexes([]))
|
||||
with pytest.raises(Exception, match="maintained"):
|
||||
table.search("fox", query_type="fts", fts_columns="text").to_arrow()
|
||||
|
||||
@@ -553,7 +549,7 @@ def test_lsm_read_time_travel_errors(tmp_path):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
|
||||
table = db.create_table("t", _reader([1, 2, 3]))
|
||||
table.set_unenforced_primary_key("id")
|
||||
table.enable_memwal(MemWalWriteSpec.unsharded())
|
||||
table.enable_rte(RTEWriteSpec.unsharded())
|
||||
pinned = table.version
|
||||
table.add(_reader([4, 5])) # standard add commits a newer version
|
||||
table.checkout(pinned) # detached head at the historical version
|
||||
@@ -562,8 +558,8 @@ def test_lsm_read_time_travel_errors(tmp_path):
|
||||
# historical version is rejected.
|
||||
with pytest.raises(Exception, match="time-travel"):
|
||||
table.search().to_arrow()
|
||||
# use_memwal(False) reads the base table at the pinned version.
|
||||
base = table.search().use_memwal(False).to_arrow()
|
||||
# use_rte(False) reads the base table at the pinned version.
|
||||
base = table.search().use_rte(False).to_arrow()
|
||||
assert sorted(base["id"].to_pylist()) == [1, 2, 3]
|
||||
|
||||
|
||||
@@ -571,14 +567,14 @@ def test_lsm_read_take_row_ids_errors(tmp_path):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
|
||||
table = db.create_table("t", _reader([1, 2, 3]))
|
||||
table.set_unenforced_primary_key("id")
|
||||
table.enable_memwal(MemWalWriteSpec.unsharded())
|
||||
table.enable_rte(RTEWriteSpec.unsharded())
|
||||
_lsm_upsert(table, [4])
|
||||
# take-by-row-id auto-routes through the LSM scanner, which has no stable _rowid,
|
||||
# so it hard-errors instead of failing with an opaque column-not-found error.
|
||||
with pytest.raises(Exception, match="row id"):
|
||||
table.take_row_ids([0, 1]).to_arrow()
|
||||
# use_memwal(False) is the escape hatch: it reads the base table.
|
||||
base = table.take_row_ids([0, 1]).use_memwal(False).to_arrow()
|
||||
# use_rte(False) is the escape hatch: it reads the base table.
|
||||
base = table.take_row_ids([0, 1]).use_rte(False).to_arrow()
|
||||
assert base.num_rows == 2
|
||||
|
||||
|
||||
@@ -588,9 +584,7 @@ def test_lsm_read_fts_postfilter_errors(tmp_path):
|
||||
table.set_unenforced_primary_key("id")
|
||||
table.create_index("text", config=FTS())
|
||||
index_name = table.list_indices()[0].name
|
||||
table.enable_memwal(
|
||||
MemWalWriteSpec.unsharded().with_maintained_indexes([index_name])
|
||||
)
|
||||
table.enable_rte(RTEWriteSpec.unsharded().with_maintained_indexes([index_name]))
|
||||
# The LSM scanner always prefilters; postfilter on FTS changes result semantics,
|
||||
# so it hard-errors (previously only the vector arm rejected it).
|
||||
with pytest.raises(Exception, match="postfilter"):
|
||||
@@ -608,7 +602,7 @@ def test_lsm_read_fts_multiple_same_type_indexes_errors(tmp_path):
|
||||
table.set_unenforced_primary_key("id")
|
||||
table.create_index("text", config=FTS(), name="fts_a")
|
||||
table.create_index("text", config=FTS(), name="fts_b", replace=False)
|
||||
table.enable_memwal(MemWalWriteSpec.unsharded().with_maintained_indexes(["fts_a"]))
|
||||
table.enable_rte(RTEWriteSpec.unsharded().with_maintained_indexes(["fts_a"]))
|
||||
# Two FTS indexes on the column: the base planner's chosen index is ambiguous, so
|
||||
# the scanner can't pick a catch-up watermark and rejects rather than risk
|
||||
# dropping rows the actually-used index has not caught up to.
|
||||
@@ -629,7 +623,7 @@ def test_lsm_read_vector_unmaintained_index_errors(tmp_path):
|
||||
)
|
||||
# Spec with NO maintained indexes: the base vector index's catch-up is untracked,
|
||||
# so the scanner rejects rather than risk dropping compacted-but-unindexed rows.
|
||||
table.enable_memwal(MemWalWriteSpec.unsharded().with_maintained_indexes([]))
|
||||
table.enable_rte(RTEWriteSpec.unsharded().with_maintained_indexes([]))
|
||||
with pytest.raises(Exception, match="maintained"):
|
||||
table.search([1.0] * VECTOR_DIM).to_arrow()
|
||||
|
||||
@@ -642,7 +636,7 @@ def test_lsm_read_fts_optimized_index_not_rejected(tmp_path):
|
||||
table.add(_fts_reader([(i, "lazy fox") for i in range(6, 11)]))
|
||||
table.optimize() # may split the FTS index into multiple physical segments
|
||||
name = table.list_indices()[0].name
|
||||
table.enable_memwal(MemWalWriteSpec.unsharded().with_maintained_indexes([name]))
|
||||
table.enable_rte(RTEWriteSpec.unsharded().with_maintained_indexes([name]))
|
||||
# Multiple physical segments of one logical index must not be miscounted as
|
||||
# multiple indexes and rejected.
|
||||
ids = set(
|
||||
|
||||
@@ -1844,10 +1844,10 @@ def lsm_test_table(lsm_handler):
|
||||
"""A remote table whose LSM routes are served by ``lsm_handler``.
|
||||
|
||||
``lsm_handler(request, route)`` is called for ``/v1/table/test/<route>/``
|
||||
where route is one of flush_memwal, compact_memwal, get_memwal_stats, and is
|
||||
where route is one of flush_rte, compact_rte, get_rte_stats, and is
|
||||
responsible for writing the response.
|
||||
"""
|
||||
routes = ("flush_memwal", "compact_memwal", "get_memwal_stats")
|
||||
routes = ("flush_rte", "compact_rte", "get_rte_stats")
|
||||
|
||||
def handler(request):
|
||||
match = re.fullmatch(r"/v1/table/test/(\w+)/", request.path)
|
||||
@@ -1879,7 +1879,7 @@ def send_json(request, payload, status=200):
|
||||
request.wfile.write(json.dumps(payload).encode())
|
||||
|
||||
|
||||
def test_get_memwal_stats_sync():
|
||||
def test_get_rte_stats_sync():
|
||||
"""The sync wrapper round-trips the server payload into a dict."""
|
||||
table_shard = {
|
||||
"shard_id": "b0",
|
||||
@@ -1904,29 +1904,29 @@ def test_get_memwal_stats_sync():
|
||||
seen_bodies = []
|
||||
|
||||
def lsm_handler(request, route):
|
||||
assert route == "get_memwal_stats"
|
||||
assert route == "get_rte_stats"
|
||||
seen_bodies.append(read_json_body(request))
|
||||
send_json(request, {"memwal_stats": {"table_shards": [table_shard]}})
|
||||
send_json(request, {"rte_stats": {"table_shards": [table_shard]}})
|
||||
|
||||
with lsm_test_table(lsm_handler) as table:
|
||||
assert table.get_memwal_stats() == {"table_shards": [table_shard]}
|
||||
assert table.get_rte_stats() == {"table_shards": [table_shard]}
|
||||
# Off by default, and forwarded when asked for.
|
||||
assert seen_bodies == [{"include_sstable_rows": False}]
|
||||
table.get_memwal_stats(include_sstable_rows=True)
|
||||
table.get_rte_stats(include_sstable_rows=True)
|
||||
assert seen_bodies[-1] == {"include_sstable_rows": True}
|
||||
|
||||
|
||||
def test_get_memwal_stats_sync_returns_none_when_memwal_disabled():
|
||||
"""A null envelope means the MemWAL write path is not enabled, not an error."""
|
||||
def test_get_rte_stats_sync_returns_none_when_rte_disabled():
|
||||
"""A null envelope means the RTE write path is not enabled, not an error."""
|
||||
|
||||
def lsm_handler(request, route):
|
||||
send_json(request, {"memwal_stats": None})
|
||||
send_json(request, {"rte_stats": None})
|
||||
|
||||
with lsm_test_table(lsm_handler) as table:
|
||||
assert table.get_memwal_stats() is None
|
||||
assert table.get_rte_stats() is None
|
||||
|
||||
|
||||
def test_flush_and_compact_memwal_sync():
|
||||
def test_flush_and_compact_rte_sync():
|
||||
"""Both are one-shot POSTs answered 202 with no body."""
|
||||
called = []
|
||||
|
||||
@@ -1936,12 +1936,12 @@ def test_flush_and_compact_memwal_sync():
|
||||
request.end_headers()
|
||||
|
||||
with lsm_test_table(lsm_handler) as table:
|
||||
assert table.flush_memwal() is None
|
||||
assert table.compact_memwal() is None
|
||||
assert called == ["flush_memwal", "compact_memwal"]
|
||||
assert table.flush_rte() is None
|
||||
assert table.compact_rte() is None
|
||||
assert called == ["flush_rte", "compact_rte"]
|
||||
|
||||
|
||||
def test_checkpoint_memwal_sync():
|
||||
def test_checkpoint_rte_sync():
|
||||
"""Freeze, read the watermark, and return once no SSTables remain.
|
||||
|
||||
The convergence loop itself is covered in Rust; this pins the sync
|
||||
@@ -1951,17 +1951,17 @@ def test_checkpoint_memwal_sync():
|
||||
|
||||
def lsm_handler(request, route):
|
||||
called.append(route)
|
||||
if route == "get_memwal_stats":
|
||||
if route == "get_rte_stats":
|
||||
# An empty SSTable tier yields no target watermark, so the loop is done
|
||||
# after the freeze without ever polling compaction.
|
||||
send_json(request, {"memwal_stats": {"table_shards": []}})
|
||||
send_json(request, {"rte_stats": {"table_shards": []}})
|
||||
else:
|
||||
request.send_response(202)
|
||||
request.end_headers()
|
||||
|
||||
with lsm_test_table(lsm_handler) as table:
|
||||
assert table.checkpoint_memwal() is None
|
||||
assert called == ["flush_memwal", "get_memwal_stats"]
|
||||
assert table.checkpoint_rte() is None
|
||||
assert called == ["flush_rte", "get_rte_stats"]
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Tests for installing and clearing an MemWalWriteSpec via
|
||||
`Table.enable_memwal` / `Table.disable_memwal`.
|
||||
"""Tests for installing and clearing an RTEWriteSpec via
|
||||
`Table.enable_rte` / `Table.disable_rte`.
|
||||
"""
|
||||
|
||||
from datetime import timedelta
|
||||
@@ -10,7 +10,7 @@ from datetime import timedelta
|
||||
import lancedb
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
from lancedb._lancedb import MemWalWriteSpec
|
||||
from lancedb._lancedb import RTEWriteSpec
|
||||
from lancedb.index import BTree
|
||||
|
||||
SCHEMA = pa.schema(
|
||||
@@ -21,9 +21,9 @@ SCHEMA = pa.schema(
|
||||
)
|
||||
|
||||
|
||||
def test_memwal_spec_module_metadata():
|
||||
assert lancedb.MemWalWriteSpec is MemWalWriteSpec
|
||||
assert MemWalWriteSpec.__module__ == "lancedb._lancedb"
|
||||
def test_rte_spec_module_metadata():
|
||||
assert lancedb.RTEWriteSpec is RTEWriteSpec
|
||||
assert RTEWriteSpec.__module__ == "lancedb._lancedb"
|
||||
|
||||
|
||||
def _batch(ids, vs):
|
||||
@@ -43,49 +43,49 @@ def _make_table(tmp_path):
|
||||
return db, table
|
||||
|
||||
|
||||
def test_enable_memwal_validates(tmp_path):
|
||||
def test_enable_rte_validates(tmp_path):
|
||||
_db, table = _make_table(tmp_path)
|
||||
table.set_unenforced_primary_key("id")
|
||||
|
||||
# Out-of-range num_buckets.
|
||||
with pytest.raises(Exception, match="num_buckets"):
|
||||
table.enable_memwal(MemWalWriteSpec.bucket("id", 0))
|
||||
table.enable_rte(RTEWriteSpec.bucket("id", 0))
|
||||
with pytest.raises(Exception, match="num_buckets"):
|
||||
table.enable_memwal(MemWalWriteSpec.bucket("id", 1025))
|
||||
table.enable_rte(RTEWriteSpec.bucket("id", 1025))
|
||||
|
||||
# Happy path, then a set over the installed spec is refused.
|
||||
table.enable_memwal(MemWalWriteSpec.bucket("id", 4))
|
||||
table.enable_rte(RTEWriteSpec.bucket("id", 4))
|
||||
with pytest.raises(Exception, match="already set"):
|
||||
table.enable_memwal(MemWalWriteSpec.bucket("id", 8))
|
||||
table.enable_rte(RTEWriteSpec.bucket("id", 8))
|
||||
|
||||
|
||||
def test_disable_memwal(tmp_path):
|
||||
def test_disable_rte(tmp_path):
|
||||
_db, table = _make_table(tmp_path)
|
||||
table.set_unenforced_primary_key("id")
|
||||
|
||||
# unset errors when no spec is set.
|
||||
with pytest.raises(Exception, match="no MemWAL write spec"):
|
||||
table.disable_memwal()
|
||||
with pytest.raises(Exception, match="no RTE write spec"):
|
||||
table.disable_rte()
|
||||
|
||||
# Install a spec, then remove it; afterwards a fresh spec can be set.
|
||||
table.enable_memwal(MemWalWriteSpec.bucket("id", 4))
|
||||
table.disable_memwal()
|
||||
table.enable_rte(RTEWriteSpec.bucket("id", 4))
|
||||
table.disable_rte()
|
||||
# A second unset errors — there is no spec left to remove.
|
||||
with pytest.raises(Exception, match="no MemWAL write spec"):
|
||||
table.disable_memwal()
|
||||
table.enable_memwal(MemWalWriteSpec.bucket("id", 8))
|
||||
with pytest.raises(Exception, match="no RTE write spec"):
|
||||
table.disable_rte()
|
||||
table.enable_rte(RTEWriteSpec.bucket("id", 8))
|
||||
|
||||
|
||||
def test_enable_memwal_requires_primary_key(tmp_path):
|
||||
def test_enable_rte_requires_primary_key(tmp_path):
|
||||
_db, table = _make_table(tmp_path)
|
||||
for spec in (
|
||||
MemWalWriteSpec.unsharded(),
|
||||
MemWalWriteSpec.bucket("id", 4),
|
||||
MemWalWriteSpec.identity("id"),
|
||||
RTEWriteSpec.unsharded(),
|
||||
RTEWriteSpec.bucket("id", 4),
|
||||
RTEWriteSpec.identity("id"),
|
||||
):
|
||||
with pytest.raises(Exception, match="primary key"):
|
||||
table.enable_memwal(spec)
|
||||
assert table.get_memwal_spec() is None
|
||||
table.enable_rte(spec)
|
||||
assert table.get_rte_spec() is None
|
||||
|
||||
|
||||
def test_set_unsharded_spec(tmp_path):
|
||||
@@ -93,12 +93,12 @@ def test_set_unsharded_spec(tmp_path):
|
||||
# Lance MemWAL still requires a primary key on the dataset; Unsharded
|
||||
# just skips per-row hashing.
|
||||
table.set_unenforced_primary_key("id")
|
||||
table.enable_memwal(MemWalWriteSpec.unsharded())
|
||||
table.disable_memwal()
|
||||
table.enable_rte(RTEWriteSpec.unsharded())
|
||||
table.disable_rte()
|
||||
|
||||
|
||||
def test_memwal_spec_repr():
|
||||
s = MemWalWriteSpec.bucket("id", 4)
|
||||
def test_rte_spec_repr():
|
||||
s = RTEWriteSpec.bucket("id", 4)
|
||||
assert s.spec_type == "bucket"
|
||||
assert s.column == "id"
|
||||
assert s.num_buckets == 4
|
||||
@@ -109,20 +109,20 @@ def test_memwal_spec_repr():
|
||||
assert "id" in repr(s)
|
||||
assert "4" in repr(s)
|
||||
|
||||
u = MemWalWriteSpec.unsharded()
|
||||
u = RTEWriteSpec.unsharded()
|
||||
assert u.spec_type == "unsharded"
|
||||
assert u.column is None
|
||||
assert u.num_buckets is None
|
||||
assert "unsharded" in repr(u)
|
||||
|
||||
|
||||
def test_memwal_spec_with_maintained_indexes():
|
||||
s = MemWalWriteSpec.bucket("id", 4).with_maintained_indexes(["idx_a", "idx_b"])
|
||||
def test_rte_spec_with_maintained_indexes():
|
||||
s = RTEWriteSpec.bucket("id", 4).with_maintained_indexes(["idx_a", "idx_b"])
|
||||
assert s.maintained_indexes == ["idx_a", "idx_b"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_set_disable_memwal(tmp_path):
|
||||
async def test_async_set_disable_rte(tmp_path):
|
||||
db = await lancedb.connect_async(
|
||||
tmp_path, read_consistency_interval=timedelta(seconds=0)
|
||||
)
|
||||
@@ -132,11 +132,11 @@ async def test_async_set_disable_memwal(tmp_path):
|
||||
)
|
||||
|
||||
await table.set_unenforced_primary_key("id")
|
||||
await table.enable_memwal(MemWalWriteSpec.bucket("id", 4))
|
||||
await table.disable_memwal()
|
||||
await table.enable_rte(RTEWriteSpec.bucket("id", 4))
|
||||
await table.disable_rte()
|
||||
# A second unset errors.
|
||||
with pytest.raises(Exception, match="no MemWAL write spec"):
|
||||
await table.disable_memwal()
|
||||
with pytest.raises(Exception, match="no RTE write spec"):
|
||||
await table.disable_rte()
|
||||
|
||||
|
||||
def test_set_identity_spec(tmp_path):
|
||||
@@ -144,12 +144,12 @@ def test_set_identity_spec(tmp_path):
|
||||
# Identity sharding still requires an unenforced primary key on the
|
||||
# table; it shards by the raw value of the given column.
|
||||
table.set_unenforced_primary_key("id")
|
||||
table.enable_memwal(MemWalWriteSpec.identity("v"))
|
||||
table.disable_memwal()
|
||||
table.enable_rte(RTEWriteSpec.identity("v"))
|
||||
table.disable_rte()
|
||||
|
||||
|
||||
def test_memwal_spec_identity_and_writer_config_defaults():
|
||||
s = MemWalWriteSpec.identity("v")
|
||||
def test_rte_spec_identity_and_writer_config_defaults():
|
||||
s = RTEWriteSpec.identity("v")
|
||||
assert s.spec_type == "identity"
|
||||
assert s.column == "v"
|
||||
assert s.num_buckets is None
|
||||
@@ -160,12 +160,12 @@ def test_memwal_spec_identity_and_writer_config_defaults():
|
||||
assert "durable_write" in repr(s)
|
||||
|
||||
|
||||
def test_get_memwal_spec(tmp_path):
|
||||
def test_get_rte_spec(tmp_path):
|
||||
_db, table = _make_table(tmp_path)
|
||||
table.set_unenforced_primary_key("id")
|
||||
|
||||
# None when nothing is installed.
|
||||
assert table.get_memwal_spec() is None
|
||||
assert table.get_rte_spec() is None
|
||||
|
||||
# A real scalar index is needed to name it as a maintained index.
|
||||
table.create_index("id", config=BTree())
|
||||
@@ -173,12 +173,12 @@ def test_get_memwal_spec(tmp_path):
|
||||
|
||||
# Bucket spec round-trips, including maintained indexes and writer config
|
||||
# defaults.
|
||||
table.enable_memwal(
|
||||
MemWalWriteSpec.bucket("id", 4)
|
||||
table.enable_rte(
|
||||
RTEWriteSpec.bucket("id", 4)
|
||||
.with_maintained_indexes([idx_name])
|
||||
.with_writer_config_defaults({"durable_write": "false"})
|
||||
)
|
||||
spec = table.get_memwal_spec()
|
||||
spec = table.get_rte_spec()
|
||||
assert spec is not None
|
||||
assert spec.spec_type == "bucket"
|
||||
assert spec.column == "id"
|
||||
@@ -187,30 +187,30 @@ def test_get_memwal_spec(tmp_path):
|
||||
assert spec.writer_config_defaults == {"durable_write": "false"}
|
||||
|
||||
# After unset, None again.
|
||||
table.disable_memwal()
|
||||
assert table.get_memwal_spec() is None
|
||||
table.disable_rte()
|
||||
assert table.get_rte_spec() is None
|
||||
|
||||
# Identity round-trips (column recovered from the schema). An unnamed
|
||||
# maintained set reads back as None: what is stored is the intent to
|
||||
# maintain every index, not the set it resolves to now.
|
||||
table.enable_memwal(MemWalWriteSpec.identity("id"))
|
||||
spec = table.get_memwal_spec()
|
||||
table.enable_rte(RTEWriteSpec.identity("id"))
|
||||
spec = table.get_rte_spec()
|
||||
assert spec.spec_type == "identity"
|
||||
assert spec.column == "id"
|
||||
assert spec.maintained_indexes is None
|
||||
table.disable_memwal()
|
||||
table.disable_rte()
|
||||
|
||||
# Unsharded round-trips (no routing column). Opting out is distinct from
|
||||
# the unnamed default.
|
||||
table.enable_memwal(MemWalWriteSpec.unsharded().with_maintained_indexes([]))
|
||||
spec = table.get_memwal_spec()
|
||||
table.enable_rte(RTEWriteSpec.unsharded().with_maintained_indexes([]))
|
||||
spec = table.get_rte_spec()
|
||||
assert spec.spec_type == "unsharded"
|
||||
assert spec.column is None
|
||||
assert spec.maintained_indexes == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_get_memwal_spec(tmp_path):
|
||||
async def test_async_get_rte_spec(tmp_path):
|
||||
db = await lancedb.connect_async(
|
||||
tmp_path, read_consistency_interval=timedelta(seconds=0)
|
||||
)
|
||||
@@ -219,21 +219,21 @@ async def test_async_get_memwal_spec(tmp_path):
|
||||
pa.RecordBatchReader.from_batches(SCHEMA, [_batch(["seed"], [0])]),
|
||||
)
|
||||
|
||||
assert await table.get_memwal_spec() is None
|
||||
assert await table.get_rte_spec() is None
|
||||
await table.set_unenforced_primary_key("id")
|
||||
|
||||
# A real scalar index is needed to name it as a maintained index.
|
||||
await table.create_index("id", config=BTree())
|
||||
idx_name = (await table.list_indices())[0].name
|
||||
|
||||
await table.enable_memwal(
|
||||
MemWalWriteSpec.bucket("id", 8).with_maintained_indexes([idx_name])
|
||||
await table.enable_rte(
|
||||
RTEWriteSpec.bucket("id", 8).with_maintained_indexes([idx_name])
|
||||
)
|
||||
spec = await table.get_memwal_spec()
|
||||
spec = await table.get_rte_spec()
|
||||
assert spec is not None
|
||||
assert spec.spec_type == "bucket"
|
||||
assert spec.column == "id"
|
||||
assert spec.num_buckets == 8
|
||||
assert spec.maintained_indexes == [idx_name]
|
||||
await table.disable_memwal()
|
||||
assert await table.get_memwal_spec() is None
|
||||
await table.disable_rte()
|
||||
assert await table.get_rte_spec() is None
|
||||
@@ -14,7 +14,7 @@ from lancedb.rerankers import RRFReranker
|
||||
|
||||
|
||||
def _wal_table(schema: pa.Schema) -> mock.Mock:
|
||||
"""A MemWAL-backed table a previous query has already been refused
|
||||
"""An RTE-backed table a previous query has already been refused
|
||||
`_rowid` on, so the fusion goes straight to the primary key."""
|
||||
table = mock.Mock()
|
||||
table._hybrid_pk_fusion_learned.return_value = True
|
||||
@@ -51,7 +51,7 @@ def test_wal_hybrid_projects_the_key_instead_of_asking_for_row_ids():
|
||||
assert builder._pk_fusion.injected == ["id"]
|
||||
for leg in (builder._vector_query, builder._fts_query):
|
||||
assert leg._columns == ["text", "id"]
|
||||
# A MemWAL table rejects with_row_id before it plans.
|
||||
# An RTE table rejects with_row_id before it plans.
|
||||
assert leg._with_row_id is not True
|
||||
|
||||
|
||||
@@ -81,15 +81,15 @@ def test_base_table_hybrid_still_joins_on_row_ids():
|
||||
assert builder._vector_query._columns is None
|
||||
|
||||
|
||||
def test_wal_hybrid_with_use_memwal_false_joins_on_row_ids():
|
||||
builder = _wal_hybrid().use_memwal(False)
|
||||
def test_wal_hybrid_with_use_rte_false_joins_on_row_ids():
|
||||
builder = _wal_hybrid().use_rte(False)
|
||||
builder._create_query_builders()
|
||||
assert builder._pk_fusion is None
|
||||
|
||||
|
||||
def test_wal_hybrid_refuses_an_explicit_with_row_id():
|
||||
builder = _wal_hybrid().with_row_id(True)
|
||||
with pytest.raises(NotImplementedError, match="use_memwal"):
|
||||
with pytest.raises(NotImplementedError, match="use_rte"):
|
||||
builder._create_query_builders()
|
||||
|
||||
|
||||
@@ -141,7 +141,7 @@ def test_wal_hybrid_refuses_row_id_even_with_return_score_all(row_id_first: bool
|
||||
else:
|
||||
builder = builder.rerank(reranker).with_row_id(True)
|
||||
|
||||
with pytest.raises(NotImplementedError, match="use_memwal"):
|
||||
with pytest.raises(NotImplementedError, match="use_rte"):
|
||||
builder._create_query_builders()
|
||||
|
||||
|
||||
@@ -199,7 +199,7 @@ def test_fallback_explains_the_refusal_to_a_caller_who_asked_for_row_ids():
|
||||
def run():
|
||||
raise _REFUSAL
|
||||
|
||||
with pytest.raises(NotImplementedError, match="use_memwal") as info:
|
||||
with pytest.raises(NotImplementedError, match="use_rte") as info:
|
||||
with_pk_fallback(
|
||||
run, mock.Mock(), fused=lambda: False, caller_requested_row_id=True
|
||||
)
|
||||
|
||||
@@ -73,10 +73,10 @@ class MockPermutationServer:
|
||||
},
|
||||
},
|
||||
)
|
||||
if path == f"/v1/table/{self.name}/get_memwal_spec/":
|
||||
if path == f"/v1/table/{self.name}/get_rte_spec/":
|
||||
self._read_body(request)
|
||||
# Null spec: this table has no MemWAL write path.
|
||||
return self._json(request, {"memwal_spec": None})
|
||||
# Null spec: this table has no RTE write path.
|
||||
return self._json(request, {"rte_spec": None})
|
||||
if path == f"/v1/table/{self.name}/count_rows/":
|
||||
self._read_body(request)
|
||||
return self._json(request, self.num_rows)
|
||||
|
||||
+3
-3
@@ -16,8 +16,8 @@ use query::{FTSQuery, HybridQuery, Query, VectorQuery};
|
||||
use session::Session;
|
||||
use table::{
|
||||
AddColumnsResult, AddResult, AlterColumnsResult, DeleteResult, DropColumnsResult, FtsToken,
|
||||
FunctionErrorFragment, FunctionErrorRecord, FunctionErrors, MemWalWriteSpec, MergeResult,
|
||||
PyBlobFile, RefreshColumnResult, RefreshMaterializedViewResult, Table,
|
||||
FunctionErrorFragment, FunctionErrorRecord, FunctionErrors, MergeResult, PyBlobFile,
|
||||
RTEWriteSpec, RefreshColumnResult, RefreshMaterializedViewResult, Table,
|
||||
UpdateFieldMetadataResult, UpdateResult,
|
||||
};
|
||||
|
||||
@@ -104,7 +104,7 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
m.add_class::<UpdateFieldMetadataResult>()?;
|
||||
m.add_class::<AddResult>()?;
|
||||
m.add_class::<MergeResult>()?;
|
||||
m.add_class::<MemWalWriteSpec>()?;
|
||||
m.add_class::<RTEWriteSpec>()?;
|
||||
m.add_class::<DeleteResult>()?;
|
||||
m.add_class::<DropColumnsResult>()?;
|
||||
m.add_class::<UpdateResult>()?;
|
||||
|
||||
+14
-14
@@ -333,7 +333,7 @@ pub struct PyQueryRequest {
|
||||
pub select_source_columns: Option<HashMap<String, String>>,
|
||||
pub fast_search: Option<bool>,
|
||||
pub with_row_id: Option<bool>,
|
||||
pub use_memwal: Option<bool>,
|
||||
pub use_rte: Option<bool>,
|
||||
pub column: Option<String>,
|
||||
pub query_vector: Option<PyQueryVectors>,
|
||||
pub nprobes: Option<usize>,
|
||||
@@ -366,7 +366,7 @@ impl From<AnyQuery> for PyQueryRequest {
|
||||
select: PySelect(query_request.select),
|
||||
fast_search: Some(query_request.fast_search),
|
||||
with_row_id: Some(query_request.with_row_id),
|
||||
use_memwal: query_request.use_memwal,
|
||||
use_rte: query_request.use_rte,
|
||||
column: None,
|
||||
query_vector: None,
|
||||
nprobes: None,
|
||||
@@ -395,7 +395,7 @@ impl From<AnyQuery> for PyQueryRequest {
|
||||
select: PySelect(vector_query.base.select),
|
||||
fast_search: Some(vector_query.base.fast_search),
|
||||
with_row_id: Some(vector_query.base.with_row_id),
|
||||
use_memwal: vector_query.base.use_memwal,
|
||||
use_rte: vector_query.base.use_rte,
|
||||
column: vector_query.column,
|
||||
query_vector: Some(PyQueryVectors(vector_query.query_vector)),
|
||||
nprobes: vector_query.nprobes,
|
||||
@@ -540,8 +540,8 @@ impl Query {
|
||||
self.inner = self.inner.clone().fast_search();
|
||||
}
|
||||
|
||||
pub fn use_memwal(&mut self, enable: bool) {
|
||||
self.inner = self.inner.clone().use_memwal(enable);
|
||||
pub fn use_rte(&mut self, enable: bool) {
|
||||
self.inner = self.inner.clone().use_rte(enable);
|
||||
}
|
||||
|
||||
pub fn with_row_id(&mut self) {
|
||||
@@ -706,8 +706,8 @@ impl TakeQuery {
|
||||
self.inner = self.inner.clone().with_row_id();
|
||||
}
|
||||
|
||||
pub fn use_memwal(&mut self, enable: bool) {
|
||||
self.inner = self.inner.clone().use_memwal(enable);
|
||||
pub fn use_rte(&mut self, enable: bool) {
|
||||
self.inner = self.inner.clone().use_rte(enable);
|
||||
}
|
||||
|
||||
#[pyo3(signature = ())]
|
||||
@@ -819,8 +819,8 @@ impl FTSQuery {
|
||||
self.inner = self.inner.clone().fast_search();
|
||||
}
|
||||
|
||||
pub fn use_memwal(&mut self, enable: bool) {
|
||||
self.inner = self.inner.clone().use_memwal(enable);
|
||||
pub fn use_rte(&mut self, enable: bool) {
|
||||
self.inner = self.inner.clone().use_rte(enable);
|
||||
}
|
||||
|
||||
pub fn with_row_id(&mut self) {
|
||||
@@ -970,8 +970,8 @@ impl VectorQuery {
|
||||
self.inner = self.inner.clone().fast_search();
|
||||
}
|
||||
|
||||
pub fn use_memwal(&mut self, enable: bool) {
|
||||
self.inner = self.inner.clone().use_memwal(enable);
|
||||
pub fn use_rte(&mut self, enable: bool) {
|
||||
self.inner = self.inner.clone().use_rte(enable);
|
||||
}
|
||||
|
||||
pub fn with_row_id(&mut self) {
|
||||
@@ -1178,9 +1178,9 @@ impl HybridQuery {
|
||||
self.inner_fts.postfilter();
|
||||
}
|
||||
|
||||
pub fn use_memwal(&mut self, enable: bool) {
|
||||
self.inner_vec.use_memwal(enable);
|
||||
self.inner_fts.use_memwal(enable);
|
||||
pub fn use_rte(&mut self, enable: bool) {
|
||||
self.inner_vec.use_rte(enable);
|
||||
self.inner_fts.use_rte(enable);
|
||||
}
|
||||
|
||||
pub fn add_query_vector(&mut self, vector: Bound<'_, PyAny>) -> PyResult<()> {
|
||||
|
||||
+59
-58
@@ -39,13 +39,13 @@ use pyo3::{
|
||||
|
||||
mod scannable;
|
||||
|
||||
/// Convert `MemWalStats` to a Python dict, preserving the per-table-shard list.
|
||||
/// Convert `RTEStats` to a Python dict, preserving the per-table-shard list.
|
||||
///
|
||||
/// Deliberately not flattened to a table-level summary: a table is N
|
||||
/// table shards on one node, and the per-shard detail is the reason the
|
||||
/// endpoint exists — flattening hides the single hot table shard someone opened
|
||||
/// it to find.
|
||||
fn memwal_stats_to_py(py: Python<'_>, stats: &lancedb::table::MemWalStats) -> PyResult<Py<PyDict>> {
|
||||
fn rte_stats_to_py(py: Python<'_>, stats: &lancedb::table::RTEStats) -> PyResult<Py<PyDict>> {
|
||||
let out = PyDict::new(py);
|
||||
let table_shards = PyList::empty(py);
|
||||
for b in &stats.table_shards {
|
||||
@@ -261,8 +261,8 @@ fn fmt_maintained(maintained: &Option<Vec<String>>) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Specification selecting Lance's MemWAL LSM-style write path for
|
||||
/// `merge_insert`.
|
||||
/// Specification enabling the realtime engine (RTE), which routes
|
||||
/// `merge_insert` through Lance's MemWAL LSM-style write path.
|
||||
///
|
||||
/// Constructed via the `bucket(...)`, `identity(...)`, or `unsharded()`
|
||||
/// classmethods, then optionally chain `with_maintained_indexes(...)` and
|
||||
@@ -270,17 +270,17 @@ fn fmt_maintained(maintained: &Option<Vec<String>>) -> String {
|
||||
/// table has, including ones created later.
|
||||
#[pyclass(module = "lancedb._lancedb", from_py_object)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct MemWalWriteSpec {
|
||||
inner: lancedb::table::MemWalWriteSpec,
|
||||
pub struct RTEWriteSpec {
|
||||
inner: lancedb::table::RTEWriteSpec,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl MemWalWriteSpec {
|
||||
impl RTEWriteSpec {
|
||||
/// Hash-bucket sharding by the unenforced primary key column.
|
||||
#[staticmethod]
|
||||
pub fn bucket(column: String, num_buckets: u32) -> Self {
|
||||
Self {
|
||||
inner: lancedb::table::MemWalWriteSpec::bucket(column, num_buckets),
|
||||
inner: lancedb::table::RTEWriteSpec::bucket(column, num_buckets),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -294,20 +294,20 @@ impl MemWalWriteSpec {
|
||||
#[staticmethod]
|
||||
pub fn identity(column: String) -> Self {
|
||||
Self {
|
||||
inner: lancedb::table::MemWalWriteSpec::identity(column),
|
||||
inner: lancedb::table::RTEWriteSpec::identity(column),
|
||||
}
|
||||
}
|
||||
|
||||
/// No sharding — every `merge_insert` call writes to a single
|
||||
/// MemWAL shard.
|
||||
/// RTE shard.
|
||||
#[staticmethod]
|
||||
pub fn unsharded() -> Self {
|
||||
Self {
|
||||
inner: lancedb::table::MemWalWriteSpec::unsharded(),
|
||||
inner: lancedb::table::RTEWriteSpec::unsharded(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Set which indexes the MemWAL maintains. `None` (the default) is
|
||||
/// Set which indexes the RTE maintains. `None` (the default) is
|
||||
/// every index the table has, including ones created later; a list is
|
||||
/// verbatim, and an empty list maintains nothing.
|
||||
#[pyo3(signature = (indexes))]
|
||||
@@ -327,33 +327,33 @@ impl MemWalWriteSpec {
|
||||
|
||||
pub fn __repr__(&self) -> String {
|
||||
match &self.inner {
|
||||
lancedb::table::MemWalWriteSpec::Bucket {
|
||||
lancedb::table::RTEWriteSpec::Bucket {
|
||||
column,
|
||||
num_buckets,
|
||||
maintained_indexes,
|
||||
writer_config_defaults,
|
||||
} => format!(
|
||||
"MemWalWriteSpec.bucket(column={:?}, num_buckets={}, maintained_indexes={}, writer_config_defaults={:?})",
|
||||
"RTEWriteSpec.bucket(column={:?}, num_buckets={}, maintained_indexes={}, writer_config_defaults={:?})",
|
||||
column,
|
||||
num_buckets,
|
||||
fmt_maintained(maintained_indexes),
|
||||
writer_config_defaults,
|
||||
),
|
||||
lancedb::table::MemWalWriteSpec::Identity {
|
||||
lancedb::table::RTEWriteSpec::Identity {
|
||||
column,
|
||||
maintained_indexes,
|
||||
writer_config_defaults,
|
||||
} => format!(
|
||||
"MemWalWriteSpec.identity(column={:?}, maintained_indexes={}, writer_config_defaults={:?})",
|
||||
"RTEWriteSpec.identity(column={:?}, maintained_indexes={}, writer_config_defaults={:?})",
|
||||
column,
|
||||
fmt_maintained(maintained_indexes),
|
||||
writer_config_defaults,
|
||||
),
|
||||
lancedb::table::MemWalWriteSpec::Unsharded {
|
||||
lancedb::table::RTEWriteSpec::Unsharded {
|
||||
maintained_indexes,
|
||||
writer_config_defaults,
|
||||
} => format!(
|
||||
"MemWalWriteSpec.unsharded(maintained_indexes={}, writer_config_defaults={:?})",
|
||||
"RTEWriteSpec.unsharded(maintained_indexes={}, writer_config_defaults={:?})",
|
||||
fmt_maintained(maintained_indexes),
|
||||
writer_config_defaults,
|
||||
),
|
||||
@@ -365,9 +365,9 @@ impl MemWalWriteSpec {
|
||||
#[getter]
|
||||
pub fn spec_type(&self) -> &'static str {
|
||||
match &self.inner {
|
||||
lancedb::table::MemWalWriteSpec::Bucket { .. } => "bucket",
|
||||
lancedb::table::MemWalWriteSpec::Identity { .. } => "identity",
|
||||
lancedb::table::MemWalWriteSpec::Unsharded { .. } => "unsharded",
|
||||
lancedb::table::RTEWriteSpec::Bucket { .. } => "bucket",
|
||||
lancedb::table::RTEWriteSpec::Identity { .. } => "identity",
|
||||
lancedb::table::RTEWriteSpec::Unsharded { .. } => "unsharded",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -375,9 +375,9 @@ impl MemWalWriteSpec {
|
||||
#[getter]
|
||||
pub fn column(&self) -> Option<String> {
|
||||
match &self.inner {
|
||||
lancedb::table::MemWalWriteSpec::Bucket { column, .. }
|
||||
| lancedb::table::MemWalWriteSpec::Identity { column, .. } => Some(column.clone()),
|
||||
lancedb::table::MemWalWriteSpec::Unsharded { .. } => None,
|
||||
lancedb::table::RTEWriteSpec::Bucket { column, .. }
|
||||
| lancedb::table::RTEWriteSpec::Identity { column, .. } => Some(column.clone()),
|
||||
lancedb::table::RTEWriteSpec::Unsharded { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -385,12 +385,12 @@ impl MemWalWriteSpec {
|
||||
#[getter]
|
||||
pub fn num_buckets(&self) -> Option<u32> {
|
||||
match &self.inner {
|
||||
lancedb::table::MemWalWriteSpec::Bucket { num_buckets, .. } => Some(*num_buckets),
|
||||
lancedb::table::RTEWriteSpec::Bucket { num_buckets, .. } => Some(*num_buckets),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Indexes the MemWAL keeps up to date, or `None` for every supported one.
|
||||
/// Indexes the RTE keeps up to date, or `None` for every supported one.
|
||||
#[getter]
|
||||
pub fn maintained_indexes(&self) -> Option<Vec<String>> {
|
||||
self.inner.maintained_indexes().map(<[String]>::to_vec)
|
||||
@@ -403,14 +403,14 @@ impl MemWalWriteSpec {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<MemWalWriteSpec> for lancedb::table::MemWalWriteSpec {
|
||||
fn from(spec: MemWalWriteSpec) -> Self {
|
||||
impl From<RTEWriteSpec> for lancedb::table::RTEWriteSpec {
|
||||
fn from(spec: RTEWriteSpec) -> Self {
|
||||
spec.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl From<lancedb::table::MemWalWriteSpec> for MemWalWriteSpec {
|
||||
fn from(inner: lancedb::table::MemWalWriteSpec) -> Self {
|
||||
impl From<lancedb::table::RTEWriteSpec> for RTEWriteSpec {
|
||||
fn from(inner: lancedb::table::RTEWriteSpec) -> Self {
|
||||
Self { inner }
|
||||
}
|
||||
}
|
||||
@@ -1636,8 +1636,8 @@ impl Table {
|
||||
if let Some(use_index) = parameters.use_index {
|
||||
builder.use_index(use_index);
|
||||
}
|
||||
if let Some(use_memwal) = parameters.use_memwal {
|
||||
builder.use_memwal(use_memwal);
|
||||
if let Some(use_rte) = parameters.use_rte {
|
||||
builder.use_rte(use_rte);
|
||||
}
|
||||
if let Some(validate_single_shard) = parameters.validate_single_shard {
|
||||
builder.validate_single_shard(validate_single_shard);
|
||||
@@ -1662,29 +1662,29 @@ impl Table {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn enable_memwal<'a>(
|
||||
pub fn enable_rte<'a>(
|
||||
self_: PyRef<'a, Self>,
|
||||
spec: MemWalWriteSpec,
|
||||
spec: RTEWriteSpec,
|
||||
) -> PyResult<Bound<'a, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
let native_spec = lancedb::table::MemWalWriteSpec::from(spec);
|
||||
let native_spec = lancedb::table::RTEWriteSpec::from(spec);
|
||||
future_into_py(self_.py(), async move {
|
||||
inner.enable_memwal(native_spec).await.infer_error()
|
||||
inner.enable_rte(native_spec).await.infer_error()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn disable_memwal(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
pub fn disable_rte(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
inner.disable_memwal().await.infer_error()
|
||||
inner.disable_rte().await.infer_error()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get_memwal_spec(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
pub fn get_rte_spec(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let spec = inner.get_memwal_spec().await.infer_error()?;
|
||||
Ok(spec.map(MemWalWriteSpec::from))
|
||||
let spec = inner.get_rte_spec().await.infer_error()?;
|
||||
Ok(spec.map(RTEWriteSpec::from))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1703,54 +1703,55 @@ impl Table {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Converge the table's MemWAL write path into its base table.
|
||||
/// Converge the table's RTE write path into its base table.
|
||||
///
|
||||
/// Best-effort: with writes flowing, new rows may land after the last
|
||||
/// pass. Errors if the table stops making progress.
|
||||
pub fn checkpoint_memwal(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
pub fn checkpoint_rte(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
inner.checkpoint_memwal().await.infer_error()
|
||||
inner.checkpoint_rte().await.infer_error()
|
||||
})
|
||||
}
|
||||
|
||||
/// Freeze every table shard's active memtable into an SSTable.
|
||||
pub fn flush_memwal(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
pub fn flush_rte(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
inner.flush_memwal().await.infer_error()
|
||||
})
|
||||
future_into_py(
|
||||
self_.py(),
|
||||
async move { inner.flush_rte().await.infer_error() },
|
||||
)
|
||||
}
|
||||
|
||||
/// Trigger a background SSTable compaction pass per table shard. Returns once the
|
||||
/// passes are dispatched, not once they finish — watch `get_memwal_stats`.
|
||||
pub fn compact_memwal(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
/// passes are dispatched, not once they finish — watch `get_rte_stats`.
|
||||
pub fn compact_rte(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
inner.compact_memwal().await.infer_error()
|
||||
inner.compact_rte().await.infer_error()
|
||||
})
|
||||
}
|
||||
|
||||
/// Live MemWAL state, or `None` when the MemWAL write path is not enabled.
|
||||
/// Live RTE state, or `None` when the RTE write path is not enabled.
|
||||
#[pyo3(signature = (include_sstable_rows=false))]
|
||||
pub fn get_memwal_stats(
|
||||
pub fn get_rte_stats(
|
||||
self_: PyRef<'_, Self>,
|
||||
include_sstable_rows: bool,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let stats = inner
|
||||
.get_memwal_stats(include_sstable_rows)
|
||||
.get_rte_stats(include_sstable_rows)
|
||||
.await
|
||||
.infer_error()?;
|
||||
Python::attach(|py| stats.map(|s| memwal_stats_to_py(py, &s)).transpose())
|
||||
Python::attach(|py| stats.map(|s| rte_stats_to_py(py, &s)).transpose())
|
||||
})
|
||||
}
|
||||
|
||||
pub fn close_memwal_writers(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
pub fn close_rte_writers(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
inner.close_memwal_writers().await.infer_error()
|
||||
inner.close_rte_writers().await.infer_error()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2082,7 +2083,7 @@ pub struct MergeInsertParams {
|
||||
when_not_matched_by_source_condition_expr: Option<PyExpr>,
|
||||
timeout: Option<std::time::Duration>,
|
||||
use_index: Option<bool>,
|
||||
use_memwal: Option<bool>,
|
||||
use_rte: Option<bool>,
|
||||
validate_single_shard: Option<bool>,
|
||||
}
|
||||
|
||||
|
||||
@@ -540,7 +540,7 @@ impl ListingDatabase {
|
||||
// pairs survive (or none existed in the first place), so an empty
|
||||
// string here must be treated the same as "no query" — otherwise
|
||||
// every table URI ends up with a trailing `?`, which makes downstream
|
||||
// sub-paths (e.g. MemWAL gen paths) re-parse as path=<base table> +
|
||||
// sub-paths (e.g. RTE gen paths) re-parse as path=<base table> +
|
||||
// query=<sub-path>, causing Lance to find the base table dataset
|
||||
// when looking up the sub-path.
|
||||
let query_string = url.query().filter(|q| !q.is_empty()).map(|s| s.to_string());
|
||||
@@ -3104,7 +3104,7 @@ mod tests {
|
||||
///
|
||||
/// Earlier, `query_pairs_mut().clear()` left the URL with
|
||||
/// `query=Some("")`, which then propagated as a trailing `?` on
|
||||
/// every table URI. Sub-path lookups against that URI (e.g. MemWAL
|
||||
/// every table URI. Sub-path lookups against that URI (e.g. RTE
|
||||
/// `<table_uri>/_mem_wal/<shard>/<rand>_gen_<n>`) re-parsed as
|
||||
/// `path=<base table>` + `query=/_mem_wal/...`, causing
|
||||
/// `Dataset::write` to find the base table dataset and falsely
|
||||
@@ -3178,7 +3178,7 @@ mod tests {
|
||||
/// `url::Url::parse` and the `query_pairs_mut()` path) must not
|
||||
/// append a trailing `?` to per-table URIs when the input URI has
|
||||
/// no query string. Sub-path lookups against such a URI (e.g.
|
||||
/// MemWAL `<table_uri>/_mem_wal/<shard>/<rand>_gen_<n>`) re-parse
|
||||
/// RTE `<table_uri>/_mem_wal/<shard>/<rand>_gen_<n>`) re-parse
|
||||
/// as `path=<base table>` + `query=/_mem_wal/...`, causing
|
||||
/// `Dataset::write` to find the base table dataset and falsely
|
||||
/// report `Dataset already exists`.
|
||||
|
||||
@@ -263,17 +263,17 @@ impl PermutationBuilder {
|
||||
}
|
||||
|
||||
// Unflushed rows have no row id, so a permutation cannot address them.
|
||||
match self.base_table.base_table().get_memwal_spec().await {
|
||||
match self.base_table.base_table().get_rte_spec().await {
|
||||
Ok(Some(_)) => {
|
||||
return Err(Error::NotSupported {
|
||||
message: "the data loader does not support tables with a MemWAL write \
|
||||
message: "the data loader does not support tables with an RTE write \
|
||||
spec: rows that have not been flushed to the base table \
|
||||
have no row id, so a permutation cannot reference them"
|
||||
.to_string(),
|
||||
});
|
||||
}
|
||||
Ok(None) => {}
|
||||
// No MemWAL write path means no spec.
|
||||
// No RTE write path means no spec.
|
||||
Err(Error::NotSupported { .. }) => {}
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
@@ -502,9 +502,9 @@ mod tests {
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
"/v1/table/remote_base/get_memwal_spec/" => http::Response::builder()
|
||||
"/v1/table/remote_base/get_rte_spec/" => http::Response::builder()
|
||||
.status(200)
|
||||
.body(br#"{"memwal_spec":null}"#.to_vec())
|
||||
.body(br#"{"rte_spec":null}"#.to_vec())
|
||||
.unwrap(),
|
||||
"/v1/table/remote_base/count_rows/" => {
|
||||
let body = body.unwrap();
|
||||
@@ -750,12 +750,12 @@ mod tests {
|
||||
/// permutation cannot reference them. Reading the base table alone would drop
|
||||
/// them from training without saying so, so the table is refused instead.
|
||||
#[tokio::test]
|
||||
async fn test_permutation_rejects_memwal_spec() {
|
||||
use crate::table::MemWalWriteSpec;
|
||||
async fn test_permutation_rejects_rte_spec() {
|
||||
use crate::table::RTEWriteSpec;
|
||||
use arrow_array::{Int32Array, RecordBatchIterator};
|
||||
use arrow_schema::{DataType, Field, Schema};
|
||||
|
||||
// MemWAL needs a real dataset directory and a non-nullable primary key.
|
||||
// RTE needs a real dataset directory and a non-nullable primary key.
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let db = connect(temp_dir.path().to_str().unwrap())
|
||||
.execute()
|
||||
@@ -778,14 +778,11 @@ mod tests {
|
||||
.unwrap();
|
||||
|
||||
table.set_unenforced_primary_key(["idx"]).await.unwrap();
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded())
|
||||
.await
|
||||
.unwrap();
|
||||
table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap();
|
||||
|
||||
let err = PermutationBuilder::new(table).build().await.unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("MemWAL write spec"),
|
||||
err.to_string().contains("RTE write spec"),
|
||||
"expected the pre-check to refuse the table, got: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -167,7 +167,7 @@
|
||||
//! # }
|
||||
//! ```
|
||||
|
||||
// The MemWAL read path (`table::query::lsm`) deepens the `create_plan` future's
|
||||
// The RTE read path (`table::query::lsm`) deepens the `create_plan` future's
|
||||
// type graph enough to overflow the default trait-recursion limit while evaluating
|
||||
// auto-traits (`Send`) through the Linux io_uring build's moka cache. Raise it.
|
||||
#![recursion_limit = "256"]
|
||||
|
||||
@@ -288,15 +288,13 @@ fn refresh_conflict_filter(dataset: &Dataset) -> Result<KeyExistenceFilter> {
|
||||
Ok(filter.build())
|
||||
}
|
||||
|
||||
/// Reject MemWAL/MemWAL state because an ordinary dataset scan cannot see its
|
||||
/// Reject RTE/RTE state because an ordinary dataset scan cannot see its
|
||||
/// un-compacted tiers.
|
||||
pub(crate) async fn ensure_no_mem_wal(dataset: &Dataset, role: &str, name: &str) -> Result<()> {
|
||||
let retained = !dataset.list_mem_wal_latest_shard_ids().await?.is_empty();
|
||||
if retained || dataset.mem_wal_index_details().await?.is_some() {
|
||||
return Err(Error::NotSupported {
|
||||
message: format!(
|
||||
"{role} '{name}' has a MemWAL write spec or retained un-compacted rows"
|
||||
),
|
||||
message: format!("{role} '{name}' has an RTE write spec or retained un-compacted rows"),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
|
||||
+19
-19
@@ -544,25 +544,25 @@ pub trait QueryBase {
|
||||
/// This allows ordering query results by one or more columns in either ascending or descending order.
|
||||
fn order_by(self, ordering: Option<Vec<ColumnOrdering>>) -> Self;
|
||||
|
||||
/// Control MemWAL read routing for this query.
|
||||
/// Control RTE read routing for this query.
|
||||
///
|
||||
/// By default (unset), when the table carries a MemWAL write spec (see
|
||||
/// [`crate::Table::enable_memwal`]), reads are routed through the LSM
|
||||
/// By default (unset), when the table carries an RTE write spec (see
|
||||
/// [`crate::Table::enable_rte`]), reads are routed through the LSM
|
||||
/// scanner so they also return data written via the `merge_insert` LSM path
|
||||
/// that has not yet been compacted into the base table (active/frozen
|
||||
/// memtables and SSTables); a table without a spec reads the base
|
||||
/// table.
|
||||
///
|
||||
/// - `use_memwal(true)` forces MemWAL routing and errors if the table has no
|
||||
/// MemWAL write spec.
|
||||
/// - `use_memwal(false)` bypasses the MemWAL and reads the base table only,
|
||||
/// - `use_rte(true)` forces RTE routing and errors if the table has no
|
||||
/// RTE write spec.
|
||||
/// - `use_rte(false)` bypasses the RTE and reads the base table only,
|
||||
/// even when a spec is present.
|
||||
///
|
||||
/// Note: the LSM scanner does not support every query shape (e.g. reranking,
|
||||
/// hybrid search, `order_by`). On a MemWAL table those shapes error unless
|
||||
/// `use_memwal(false)` is set, because a base-only read would silently
|
||||
/// exclude un-compacted MemWAL data.
|
||||
fn use_memwal(self, enable: bool) -> Self;
|
||||
/// hybrid search, `order_by`). On an RTE table those shapes error unless
|
||||
/// `use_rte(false)` is set, because a base-only read would silently
|
||||
/// exclude un-compacted RTE data.
|
||||
fn use_rte(self, enable: bool) -> Self;
|
||||
}
|
||||
|
||||
pub trait HasQuery {
|
||||
@@ -634,8 +634,8 @@ impl<T: HasQuery> QueryBase for T {
|
||||
self
|
||||
}
|
||||
|
||||
fn use_memwal(mut self, enable: bool) -> Self {
|
||||
self.mut_query().use_memwal = Some(enable);
|
||||
fn use_rte(mut self, enable: bool) -> Self {
|
||||
self.mut_query().use_rte = Some(enable);
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -898,19 +898,19 @@ pub struct QueryRequest {
|
||||
/// This allows ordering query results by one or more columns in either ascending or descending order.
|
||||
pub order_by: Option<Vec<ColumnOrdering>>,
|
||||
|
||||
/// Controls MemWAL read routing. When unset (the default), a query against a
|
||||
/// table that carries a MemWAL write spec (see
|
||||
/// [`crate::Table::enable_memwal`]) is routed through the LSM scanner so
|
||||
/// Controls RTE read routing. When unset (the default), a query against a
|
||||
/// table that carries an RTE write spec (see
|
||||
/// [`crate::Table::enable_rte`]) is routed through the LSM scanner so
|
||||
/// it also sees data written via the `merge_insert` LSM path that has not yet
|
||||
/// been compacted into the base table — the active and frozen in-memory
|
||||
/// memtables and the SSTables, deduplicated by primary key
|
||||
/// against the base table (newest generation wins); a table without a spec
|
||||
/// reads the base table.
|
||||
///
|
||||
/// - `Some(true)` forces MemWAL routing and errors if the table has no MemWAL
|
||||
/// - `Some(true)` forces RTE routing and errors if the table has no RTE
|
||||
/// write spec.
|
||||
/// - `Some(false)` reads only the base table, bypassing the MemWAL.
|
||||
pub use_memwal: Option<bool>,
|
||||
/// - `Some(false)` reads only the base table, bypassing the RTE.
|
||||
pub use_rte: Option<bool>,
|
||||
}
|
||||
|
||||
impl Default for QueryRequest {
|
||||
@@ -930,7 +930,7 @@ impl Default for QueryRequest {
|
||||
norm: None,
|
||||
disable_scoring_autoprojection: false,
|
||||
order_by: None,
|
||||
use_memwal: None,
|
||||
use_rte: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
//! WAL-PK-FUSION: hybrid search's primary-key fallback for MemWAL tables.
|
||||
//! WAL-PK-FUSION: hybrid search's primary-key fallback for RTE tables.
|
||||
//!
|
||||
//! Hybrid search joins its vector and full-text legs on `_rowid`, which a
|
||||
//! MemWAL table cannot supply: the fresh tier has no stable row id, so the
|
||||
//! RTE table cannot supply: the fresh tier has no stable row id, so the
|
||||
//! server rejects `with_row_id` before it plans. When that happens the legs are
|
||||
//! joined on a surrogate `_rowid` built from the table's primary key instead.
|
||||
//!
|
||||
//! This is a stopgap until MemWAL supports `_rowid`, and everything it needs
|
||||
//! This is a stopgap until RTE supports `_rowid`, and everything it needs
|
||||
//! lives here so it can be removed in one pass:
|
||||
//!
|
||||
//! 1. Delete this file and its `mod wal_fusion;` line in `query.rs`.
|
||||
@@ -31,44 +31,44 @@ use lance_core::utils::parse::str_is_truthy;
|
||||
use super::{Select, VectorQuery};
|
||||
use crate::error::{Error, Result};
|
||||
|
||||
/// The part of the MemWAL `with_row_id` refusal that identifies it.
|
||||
/// The part of the RTE `with_row_id` refusal that identifies it.
|
||||
///
|
||||
/// Both layers raise this same sentence verbatim — sophon's
|
||||
/// `LSM_WITH_ROW_ID_UNSUPPORTED` says so in as many words, and the OSS LSM
|
||||
/// scanner builds it from the same words — so this substring survives either
|
||||
/// path and the wrapping each adds. It is a coupling to a message rather than
|
||||
/// a code, because the refusal arrives as a generic 400; if the server ever
|
||||
/// rewords it the fallback stops firing and hybrid on a MemWAL table goes back
|
||||
/// rewords it the fallback stops firing and hybrid on an RTE table goes back
|
||||
/// to erroring visibly, which is loud rather than silently wrong.
|
||||
const WAL_ROW_ID_REFUSAL: &str = "does not support with_row_id";
|
||||
|
||||
/// Whether `error` is the server declining `_rowid` because the table is
|
||||
/// MemWAL-backed, as opposed to any other failure the query might hit.
|
||||
/// RTE-backed, as opposed to any other failure the query might hit.
|
||||
fn is_wal_row_id_refusal(error: &Error) -> bool {
|
||||
error.to_string().contains(WAL_ROW_ID_REFUSAL)
|
||||
}
|
||||
|
||||
/// Why a hybrid query on a MemWAL table cannot hand back `_rowid`, raised
|
||||
/// Why a hybrid query on an RTE table cannot hand back `_rowid`, raised
|
||||
/// whether the refusal was anticipated or came back from the server.
|
||||
fn wal_row_id_unsupported() -> Error {
|
||||
Error::NotSupported {
|
||||
message: "hybrid search on a MemWAL table cannot return _rowid: the fresh tier has no \
|
||||
message: "hybrid search on an RTE table cannot return _rowid: the fresh tier has no \
|
||||
stable row id, and the ids the fusion joins on are synthesized from the \
|
||||
primary key. Set use_memwal(false) to read the base table only (results will \
|
||||
exclude un-compacted MemWAL data)"
|
||||
primary key. Set use_rte(false) to read the base table only (results will \
|
||||
exclude un-compacted RTE data)"
|
||||
.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a hybrid query, joining its legs on the primary key instead of `_rowid`
|
||||
/// when the table is MemWAL-backed.
|
||||
/// when the table is RTE-backed.
|
||||
///
|
||||
/// `run(None)` must join the legs on `_rowid`; `run(Some(fusion))` must build
|
||||
/// them with `fusion` instead.
|
||||
///
|
||||
/// `_rowid` is asked for first and the primary key used only when the server
|
||||
/// refuses, rather than paying a round trip up front to find out. Only a
|
||||
/// MemWAL table refuses, so probing would tax every table to learn something
|
||||
/// RTE table refuses, so probing would tax every table to learn something
|
||||
/// almost none of them need — and the refusal has to be handled regardless,
|
||||
/// since a write spec installed elsewhere can arrive between any two queries.
|
||||
/// The refusal costs nothing server-side: it is raised before the query is
|
||||
@@ -80,7 +80,7 @@ where
|
||||
{
|
||||
// A previous query on this table was already refused, so skip straight to
|
||||
// the key.
|
||||
if query.request.base.use_memwal != Some(false) && query.parent.hybrid_pk_fusion_learned() {
|
||||
if query.request.base.use_rte != Some(false) && query.parent.hybrid_pk_fusion_learned() {
|
||||
return run(Some(PkFusion::resolve(query).await?)).await;
|
||||
}
|
||||
match run(None).await {
|
||||
@@ -130,7 +130,7 @@ impl PkFusionMemory {
|
||||
}
|
||||
}
|
||||
|
||||
/// How the legs of a hybrid query on a MemWAL table are joined: on a surrogate
|
||||
/// How the legs of a hybrid query on an RTE table are joined: on a surrogate
|
||||
/// `_rowid` derived client-side from the primary key.
|
||||
pub(super) struct PkFusion {
|
||||
columns: Vec<String>,
|
||||
@@ -152,7 +152,7 @@ impl PkFusion {
|
||||
Ok(Self { columns, injected })
|
||||
}
|
||||
|
||||
/// Make a leg return the key columns, in place of the `_rowid` a MemWAL
|
||||
/// Make a leg return the key columns, in place of the `_rowid` an RTE
|
||||
/// table would refuse.
|
||||
pub(super) fn prepare_leg(&self, select: &mut Select) {
|
||||
inject_pk_columns(select, &self.columns);
|
||||
@@ -266,7 +266,7 @@ fn pk_columns(schema: &arrow_schema::Schema) -> Vec<String> {
|
||||
/// Replace each batch's join column with a dense surrogate derived from
|
||||
/// `pk_columns`, in place and in the order given.
|
||||
///
|
||||
/// The fusion joins its two legs on [`ROW_ID`], which a MemWAL table cannot
|
||||
/// The fusion joins its two legs on [`ROW_ID`], which an RTE table cannot
|
||||
/// supply — the fresh tier has no stable row id. It only ever compares the
|
||||
/// column for equality, though (`merge_results` dedups, the rerankers group and
|
||||
/// the score restore looks up), so any injective mapping of the primary key
|
||||
@@ -280,7 +280,7 @@ fn pk_columns(schema: &arrow_schema::Schema) -> Vec<String> {
|
||||
fn stamp_surrogate_row_ids(batches: &mut [RecordBatch], pk_columns: &[String]) -> Result<()> {
|
||||
if pk_columns.is_empty() {
|
||||
return Err(Error::InvalidInput {
|
||||
message: "hybrid search on a MemWAL table needs an unenforced primary key to \
|
||||
message: "hybrid search on an RTE table needs an unenforced primary key to \
|
||||
deduplicate on, and this table declares none"
|
||||
.to_string(),
|
||||
});
|
||||
|
||||
+124
-125
@@ -30,15 +30,15 @@ use crate::table::BranchDiff;
|
||||
use crate::table::CherryPickResult;
|
||||
use crate::table::DeleteResult;
|
||||
use crate::table::DropColumnsResult;
|
||||
use crate::table::MemWalStats;
|
||||
use crate::table::MemWalWriteSpec;
|
||||
use crate::table::MergeResult;
|
||||
use crate::table::RTEStats;
|
||||
use crate::table::RTEWriteSpec;
|
||||
use crate::table::Tags;
|
||||
use crate::table::UpdateResult;
|
||||
use crate::table::memwal_stats::GetMemWalStatsResponse;
|
||||
use crate::table::merge::MergeFilter;
|
||||
use crate::table::primary_key;
|
||||
use crate::table::query::create_multi_vector_plan;
|
||||
use crate::table::rte_stats::GetRTEStatsResponse;
|
||||
use crate::table::write_progress::FinishOnDrop;
|
||||
use crate::table::{
|
||||
AlterColumnsResult, FieldMetadataUpdate, RefreshColumnResult, UpdateFieldMetadataResult,
|
||||
@@ -1020,10 +1020,10 @@ impl<S: HttpSend> RemoteTable<S> {
|
||||
) -> Result<()> {
|
||||
params.check_filter()?;
|
||||
body["prefilter"] = params.prefilter.into();
|
||||
// Only forward use_memwal when explicitly set; a server that predates it
|
||||
// Only forward use_rte when explicitly set; a server that predates it
|
||||
// ignores the field and routes as it would by default.
|
||||
if let Some(use_memwal) = params.use_memwal {
|
||||
body["use_memwal"] = serde_json::Value::Bool(use_memwal);
|
||||
if let Some(use_rte) = params.use_rte {
|
||||
body["use_rte"] = serde_json::Value::Bool(use_rte);
|
||||
}
|
||||
if let Some(offset) = params.offset {
|
||||
body["offset"] = serde_json::Value::Number(serde_json::Number::from(offset));
|
||||
@@ -3236,43 +3236,42 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn flush_memwal(&self) -> Result<()> {
|
||||
async fn flush_rte(&self) -> Result<()> {
|
||||
let request = self
|
||||
.client
|
||||
.post(&format!("/v1/table/{}/flush_memwal/", self.identifier));
|
||||
.post(&format!("/v1/table/{}/flush_rte/", self.identifier));
|
||||
self.send_lsm_route(request).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn compact_memwal(&self) -> Result<()> {
|
||||
async fn compact_rte(&self) -> Result<()> {
|
||||
let request = self
|
||||
.client
|
||||
.post(&format!("/v1/table/{}/compact_memwal/", self.identifier));
|
||||
.post(&format!("/v1/table/{}/compact_rte/", self.identifier));
|
||||
self.send_lsm_route(request).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn get_memwal_stats(&self, include_sstable_rows: bool) -> Result<Option<MemWalStats>> {
|
||||
// Read-semantics POST, like `get_memwal_spec`.
|
||||
async fn get_rte_stats(&self, include_sstable_rows: bool) -> Result<Option<RTEStats>> {
|
||||
// Read-semantics POST, like `get_rte_spec`.
|
||||
let request = self
|
||||
.client
|
||||
.post(&format!("/v1/table/{}/get_memwal_stats/", self.identifier))
|
||||
.post(&format!("/v1/table/{}/get_rte_stats/", self.identifier))
|
||||
.json(&serde_json::json!({
|
||||
"include_sstable_rows": include_sstable_rows,
|
||||
}));
|
||||
let (request_id, response) = self.send_lsm_route(request).await?;
|
||||
let body = response.text().await.err_to_http(request_id.clone())?;
|
||||
let parsed: GetMemWalStatsResponse =
|
||||
serde_json::from_str(&body).map_err(|e| Error::Http {
|
||||
source: format!("Failed to parse get_memwal_stats response: {e}").into(),
|
||||
request_id,
|
||||
status_code: None,
|
||||
})?;
|
||||
// `null` — and only — when the table has no MemWAL write path.
|
||||
Ok(parsed.memwal_stats)
|
||||
let parsed: GetRTEStatsResponse = serde_json::from_str(&body).map_err(|e| Error::Http {
|
||||
source: format!("Failed to parse get_rte_stats response: {e}").into(),
|
||||
request_id,
|
||||
status_code: None,
|
||||
})?;
|
||||
// `null` — and only — when the table has no RTE write path.
|
||||
Ok(parsed.rte_stats)
|
||||
}
|
||||
|
||||
async fn enable_memwal(&self, spec: MemWalWriteSpec) -> Result<()> {
|
||||
async fn enable_rte(&self, spec: RTEWriteSpec) -> Result<()> {
|
||||
self.check_mutable().await?;
|
||||
|
||||
// Map the spec onto the server's request DTO. `sharding` is internally
|
||||
@@ -3280,7 +3279,7 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
// `maintained_indexes` asks the server to resolve every maintainable
|
||||
// index at HEAD; a list is verbatim, an empty one meaning none.
|
||||
let sharding = match &spec {
|
||||
MemWalWriteSpec::Bucket {
|
||||
RTEWriteSpec::Bucket {
|
||||
column,
|
||||
num_buckets,
|
||||
..
|
||||
@@ -3289,11 +3288,11 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
"column": column,
|
||||
"num_buckets": num_buckets,
|
||||
}),
|
||||
MemWalWriteSpec::Identity { column, .. } => serde_json::json!({
|
||||
RTEWriteSpec::Identity { column, .. } => serde_json::json!({
|
||||
"mode": "identity",
|
||||
"column": column,
|
||||
}),
|
||||
MemWalWriteSpec::Unsharded { .. } => serde_json::json!({ "mode": "unsharded" }),
|
||||
RTEWriteSpec::Unsharded { .. } => serde_json::json!({ "mode": "unsharded" }),
|
||||
};
|
||||
let body = serde_json::json!({
|
||||
"sharding": sharding,
|
||||
@@ -3303,40 +3302,40 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
|
||||
let request = self
|
||||
.client
|
||||
.post(&format!("/v1/table/{}/enable_memwal/", self.identifier))
|
||||
.post(&format!("/v1/table/{}/enable_rte/", self.identifier))
|
||||
.json(&body);
|
||||
let (request_id, response) = self.send(request, true).await?;
|
||||
self.check_table_response(&request_id, response).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn disable_memwal(&self) -> Result<()> {
|
||||
async fn disable_rte(&self) -> Result<()> {
|
||||
self.check_mutable().await?;
|
||||
let request = self
|
||||
.client
|
||||
.post(&format!("/v1/table/{}/disable_memwal/", self.identifier));
|
||||
.post(&format!("/v1/table/{}/disable_rte/", self.identifier));
|
||||
let (request_id, response) = self.send(request, true).await?;
|
||||
self.check_table_response(&request_id, response).await?;
|
||||
self.wal_pk_fusion.forget(); // WAL-PK-FUSION: delete.
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn get_memwal_spec(&self) -> Result<Option<MemWalWriteSpec>> {
|
||||
async fn get_rte_spec(&self) -> Result<Option<RTEWriteSpec>> {
|
||||
// Read counterpart to set/unset, resolved server-side against HEAD. The
|
||||
// server reads the spec from the `__lance_mem_wal` system index (shard
|
||||
// column mapped from its Lance field id against the current schema) and
|
||||
// re-encodes it into the same sophon-owned shape the set endpoint
|
||||
// accepts — no lance/lancedb types cross the wire. `memwal_spec` is
|
||||
// null when the MemWAL write path is not enabled for the table.
|
||||
// accepts — no lance/lancedb types cross the wire. `rte_spec` is
|
||||
// null when the RTE write path is not enabled for the table.
|
||||
let request = self
|
||||
.client
|
||||
.post(&format!("/v1/table/{}/get_memwal_spec/", self.identifier));
|
||||
.post(&format!("/v1/table/{}/get_rte_spec/", self.identifier));
|
||||
let (request_id, response) = self.send(request, true).await?;
|
||||
let response = self.check_table_response(&request_id, response).await?;
|
||||
let body = response.text().await.err_to_http(request_id.clone())?;
|
||||
|
||||
// Mirror of sophon's `Sharding` (internally tagged on `mode`) and
|
||||
// `MemWalWriteSpecBody` / `GetMemWalSpecResponse`.
|
||||
// `RTEWriteSpecBody` / `GetRTESpecResponse`.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "mode", rename_all = "snake_case")]
|
||||
enum Sharding {
|
||||
@@ -3345,7 +3344,7 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
Identity { column: String },
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct MemWalWriteSpecBody {
|
||||
struct RTEWriteSpecBody {
|
||||
sharding: Sharding,
|
||||
/// `null` selects every index the table has; `[]` selects none.
|
||||
#[serde(default)]
|
||||
@@ -3354,19 +3353,18 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
writer_config_defaults: std::collections::HashMap<String, String>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct GetMemWalSpecResponse {
|
||||
memwal_spec: Option<MemWalWriteSpecBody>,
|
||||
struct GetRTESpecResponse {
|
||||
rte_spec: Option<RTEWriteSpecBody>,
|
||||
}
|
||||
|
||||
let parsed: GetMemWalSpecResponse =
|
||||
serde_json::from_str(&body).map_err(|e| Error::Http {
|
||||
source: format!("Failed to parse get_memwal_spec response: {}", e).into(),
|
||||
request_id,
|
||||
status_code: None,
|
||||
})?;
|
||||
let parsed: GetRTESpecResponse = serde_json::from_str(&body).map_err(|e| Error::Http {
|
||||
source: format!("Failed to parse get_rte_spec response: {}", e).into(),
|
||||
request_id,
|
||||
status_code: None,
|
||||
})?;
|
||||
|
||||
let Some(body) = parsed.memwal_spec else {
|
||||
// The MemWAL write path is not enabled for this table.
|
||||
let Some(body) = parsed.rte_spec else {
|
||||
// The RTE write path is not enabled for this table.
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
@@ -3374,9 +3372,9 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
Sharding::Bucket {
|
||||
column,
|
||||
num_buckets,
|
||||
} => MemWalWriteSpec::bucket(column, num_buckets),
|
||||
Sharding::Identity { column } => MemWalWriteSpec::identity(column),
|
||||
Sharding::Unsharded => MemWalWriteSpec::unsharded(),
|
||||
} => RTEWriteSpec::bucket(column, num_buckets),
|
||||
Sharding::Identity { column } => RTEWriteSpec::identity(column),
|
||||
Sharding::Unsharded => RTEWriteSpec::unsharded(),
|
||||
}
|
||||
.with_maintained_indexes(body.maintained_indexes)
|
||||
.with_writer_config_defaults(body.writer_config_defaults);
|
||||
@@ -3979,10 +3977,10 @@ pub struct MergeInsertRequest {
|
||||
// (the default is true)
|
||||
#[serde(skip_serializing_if = "is_true")]
|
||||
use_index: bool,
|
||||
// Only serialize use_memwal when explicitly set (Some); a server that predates
|
||||
// Only serialize use_rte when explicitly set (Some); a server that predates
|
||||
// it ignores the field and routes as it would by default.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
use_memwal: Option<bool>,
|
||||
use_rte: Option<bool>,
|
||||
}
|
||||
|
||||
impl MergeInsertRequest {
|
||||
@@ -4040,7 +4038,7 @@ impl TryFrom<MergeInsertBuilder> for MergeInsertRequest {
|
||||
when_not_matched_by_source_delete_filt,
|
||||
// Only serialize use_index when it's false for backwards compatibility
|
||||
use_index: value.use_index,
|
||||
use_memwal: value.use_memwal,
|
||||
use_rte: value.use_rte,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -10296,10 +10294,10 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_enable_memwal_unsharded() {
|
||||
async fn test_enable_rte_unsharded() {
|
||||
let table = Table::new_with_handler("my_table", |request| {
|
||||
assert_eq!(request.method(), "POST");
|
||||
assert_eq!(request.url().path(), "/v1/table/my_table/enable_memwal/");
|
||||
assert_eq!(request.url().path(), "/v1/table/my_table/enable_rte/");
|
||||
let body = request.body().unwrap().as_bytes().unwrap();
|
||||
let body: serde_json::Value = serde_json::from_slice(body).unwrap();
|
||||
assert_eq!(body["sharding"], serde_json::json!({ "mode": "unsharded" }));
|
||||
@@ -10313,17 +10311,17 @@ mod tests {
|
||||
.body(r#"{"maintained_indexes":["id_idx"]}"#)
|
||||
.unwrap()
|
||||
});
|
||||
let spec = crate::table::MemWalWriteSpec::unsharded()
|
||||
let spec = crate::table::RTEWriteSpec::unsharded()
|
||||
.with_maintained_indexes(vec!["id_idx".to_string()])
|
||||
.with_writer_config_defaults([("max_memtable_rows", "1000")]);
|
||||
table.enable_memwal(spec).await.unwrap();
|
||||
table.enable_rte(spec).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_enable_memwal_bucket() {
|
||||
async fn test_enable_rte_bucket() {
|
||||
let table = Table::new_with_handler("my_table", |request| {
|
||||
assert_eq!(request.method(), "POST");
|
||||
assert_eq!(request.url().path(), "/v1/table/my_table/enable_memwal/");
|
||||
assert_eq!(request.url().path(), "/v1/table/my_table/enable_rte/");
|
||||
let body = request.body().unwrap().as_bytes().unwrap();
|
||||
let body: serde_json::Value = serde_json::from_slice(body).unwrap();
|
||||
assert_eq!(
|
||||
@@ -10335,14 +10333,14 @@ mod tests {
|
||||
http::Response::builder().status(200).body("{}").unwrap()
|
||||
});
|
||||
table
|
||||
.enable_memwal(crate::table::MemWalWriteSpec::bucket("id", 16))
|
||||
.enable_rte(crate::table::RTEWriteSpec::bucket("id", 16))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// `[]` (none) must stay distinguishable on the wire from null (all).
|
||||
#[tokio::test]
|
||||
async fn test_enable_memwal_no_maintained_indexes() {
|
||||
async fn test_enable_rte_no_maintained_indexes() {
|
||||
let table = Table::new_with_handler("my_table", |request| {
|
||||
let body = request.body().unwrap().as_bytes().unwrap();
|
||||
let body: serde_json::Value = serde_json::from_slice(body).unwrap();
|
||||
@@ -10350,18 +10348,18 @@ mod tests {
|
||||
http::Response::builder().status(200).body("{}").unwrap()
|
||||
});
|
||||
table
|
||||
.enable_memwal(
|
||||
crate::table::MemWalWriteSpec::bucket("id", 16).with_maintained_indexes(Vec::new()),
|
||||
.enable_rte(
|
||||
crate::table::RTEWriteSpec::bucket("id", 16).with_maintained_indexes(Vec::new()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_enable_memwal_identity() {
|
||||
async fn test_enable_rte_identity() {
|
||||
let table = Table::new_with_handler("my_table", |request| {
|
||||
assert_eq!(request.method(), "POST");
|
||||
assert_eq!(request.url().path(), "/v1/table/my_table/enable_memwal/");
|
||||
assert_eq!(request.url().path(), "/v1/table/my_table/enable_rte/");
|
||||
let body = request.body().unwrap().as_bytes().unwrap();
|
||||
let body: serde_json::Value = serde_json::from_slice(body).unwrap();
|
||||
assert_eq!(
|
||||
@@ -10371,32 +10369,32 @@ mod tests {
|
||||
http::Response::builder().status(200).body("{}").unwrap()
|
||||
});
|
||||
table
|
||||
.enable_memwal(crate::table::MemWalWriteSpec::identity("tenant"))
|
||||
.enable_rte(crate::table::RTEWriteSpec::identity("tenant"))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_disable_memwal() {
|
||||
async fn test_disable_rte() {
|
||||
let table = Table::new_with_handler("my_table", |request| {
|
||||
assert_eq!(request.method(), "POST");
|
||||
assert_eq!(request.url().path(), "/v1/table/my_table/disable_memwal/");
|
||||
assert_eq!(request.url().path(), "/v1/table/my_table/disable_rte/");
|
||||
http::Response::builder().status(200).body("{}").unwrap()
|
||||
});
|
||||
table.disable_memwal().await.unwrap();
|
||||
table.disable_rte().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_get_memwal_spec() {
|
||||
async fn test_get_rte_spec() {
|
||||
let table = Table::new_with_handler("my_table", |request| {
|
||||
assert_eq!(request.method(), "POST");
|
||||
assert_eq!(request.url().path(), "/v1/table/my_table/get_memwal_spec/");
|
||||
assert_eq!(request.url().path(), "/v1/table/my_table/get_rte_spec/");
|
||||
|
||||
// The server resolves the spec and re-encodes it into the same
|
||||
// sophon-owned shape the set endpoint accepts (`Sharding` internally
|
||||
// tagged on `mode`, wrapped in `memwal_spec`).
|
||||
// tagged on `mode`, wrapped in `rte_spec`).
|
||||
let response = serde_json::json!({
|
||||
"memwal_spec": {
|
||||
"rte_spec": {
|
||||
"sharding": { "mode": "bucket", "column": "id", "num_buckets": 4 },
|
||||
"maintained_indexes": ["id_idx"],
|
||||
"writer_config_defaults": { "durable_write": "false" },
|
||||
@@ -10409,12 +10407,12 @@ mod tests {
|
||||
});
|
||||
|
||||
let spec = table
|
||||
.get_memwal_spec()
|
||||
.get_rte_spec()
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("a spec should be reported");
|
||||
match spec {
|
||||
crate::table::MemWalWriteSpec::Bucket {
|
||||
crate::table::RTEWriteSpec::Bucket {
|
||||
column,
|
||||
num_buckets,
|
||||
maintained_indexes,
|
||||
@@ -10441,13 +10439,13 @@ mod tests {
|
||||
#[case::no_index(serde_json::json!([]), Some(vec![]))]
|
||||
#[case::named(serde_json::json!(["id_idx"]), Some(vec!["id_idx".to_string()]))]
|
||||
#[tokio::test]
|
||||
async fn test_get_memwal_spec_round_trips_the_selection(
|
||||
async fn test_get_rte_spec_round_trips_the_selection(
|
||||
#[case] reported: serde_json::Value,
|
||||
#[case] expected: Option<Vec<String>>,
|
||||
) {
|
||||
let table = Table::new_with_handler("my_table", move |_| {
|
||||
let response = serde_json::json!({
|
||||
"memwal_spec": {
|
||||
"rte_spec": {
|
||||
"sharding": { "mode": "unsharded" },
|
||||
"maintained_indexes": reported,
|
||||
"writer_config_defaults": {},
|
||||
@@ -10460,7 +10458,7 @@ mod tests {
|
||||
});
|
||||
|
||||
let spec = table
|
||||
.get_memwal_spec()
|
||||
.get_rte_spec()
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("a spec should be reported");
|
||||
@@ -10472,23 +10470,23 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_get_memwal_spec_absent() {
|
||||
async fn test_get_rte_spec_absent() {
|
||||
let table = Table::new_with_handler("my_table", |request| {
|
||||
assert_eq!(request.url().path(), "/v1/table/my_table/get_memwal_spec/");
|
||||
// Null spec → the MemWAL write path is not enabled.
|
||||
let response = serde_json::json!({ "memwal_spec": null });
|
||||
assert_eq!(request.url().path(), "/v1/table/my_table/get_rte_spec/");
|
||||
// Null spec → the RTE write path is not enabled.
|
||||
let response = serde_json::json!({ "rte_spec": null });
|
||||
http::Response::builder()
|
||||
.status(200)
|
||||
.body(response.to_string())
|
||||
.unwrap()
|
||||
});
|
||||
assert!(table.get_memwal_spec().await.unwrap().is_none());
|
||||
assert!(table.get_rte_spec().await.unwrap().is_none());
|
||||
}
|
||||
|
||||
/// Build a `get_memwal_stats` body for one table shard holding `sstables`.
|
||||
/// Build a `get_rte_stats` body for one table shard holding `sstables`.
|
||||
fn stats_body(sstables: &[u64], compacting: bool) -> String {
|
||||
serde_json::json!({
|
||||
"memwal_stats": {
|
||||
"rte_stats": {
|
||||
"table_shards": [{
|
||||
"shard_id": "b0",
|
||||
"status": "Active",
|
||||
@@ -10508,7 +10506,7 @@ mod tests {
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// `flush_memwal` / `compact_memwal` answer 202 with no body at all.
|
||||
/// `flush_rte` / `compact_rte` answer 202 with no body at all.
|
||||
fn accepted() -> http::Response<String> {
|
||||
http::Response::builder()
|
||||
.status(202)
|
||||
@@ -10529,18 +10527,18 @@ mod tests {
|
||||
let seen = compacts.clone();
|
||||
let table = Table::new_with_handler("my_table", move |request| {
|
||||
let path = request.url().path().to_string();
|
||||
if path.contains("compact_memwal") {
|
||||
if path.contains("compact_rte") {
|
||||
seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
panic!("an already-converged table must issue no compact calls");
|
||||
}
|
||||
if path.contains("flush_memwal") {
|
||||
if path.contains("flush_rte") {
|
||||
return accepted();
|
||||
}
|
||||
assert_eq!(path, "/v1/table/my_table/get_memwal_stats/");
|
||||
assert_eq!(path, "/v1/table/my_table/get_rte_stats/");
|
||||
ok_json(stats_body(&[], false))
|
||||
});
|
||||
|
||||
table.checkpoint_memwal().await.unwrap();
|
||||
table.checkpoint_rte().await.unwrap();
|
||||
assert_eq!(compacts.load(std::sync::atomic::Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
@@ -10552,10 +10550,10 @@ mod tests {
|
||||
let seen = compacts.clone();
|
||||
let table = Table::new_with_handler("my_table", move |request| {
|
||||
let path = request.url().path().to_string();
|
||||
if path.contains("flush_memwal") {
|
||||
if path.contains("flush_rte") {
|
||||
return accepted();
|
||||
}
|
||||
if path.contains("compact_memwal") {
|
||||
if path.contains("compact_rte") {
|
||||
seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
return accepted();
|
||||
}
|
||||
@@ -10565,7 +10563,7 @@ mod tests {
|
||||
ok_json(stats_body(&left, false))
|
||||
});
|
||||
|
||||
table.checkpoint_memwal().await.unwrap();
|
||||
table.checkpoint_rte().await.unwrap();
|
||||
assert_eq!(
|
||||
compacts.load(std::sync::atomic::Ordering::SeqCst),
|
||||
3,
|
||||
@@ -10582,10 +10580,10 @@ mod tests {
|
||||
let seen = compacts.clone();
|
||||
let table = Table::new_with_handler("my_table", move |request| {
|
||||
let path = request.url().path().to_string();
|
||||
if path.contains("flush_memwal") {
|
||||
if path.contains("flush_rte") {
|
||||
return accepted();
|
||||
}
|
||||
if path.contains("compact_memwal") {
|
||||
if path.contains("compact_rte") {
|
||||
seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
return accepted();
|
||||
}
|
||||
@@ -10599,7 +10597,7 @@ mod tests {
|
||||
ok_json(body)
|
||||
});
|
||||
|
||||
table.checkpoint_memwal().await.unwrap();
|
||||
table.checkpoint_rte().await.unwrap();
|
||||
assert_eq!(
|
||||
compacts.load(std::sync::atomic::Ordering::SeqCst),
|
||||
1,
|
||||
@@ -10616,10 +10614,10 @@ mod tests {
|
||||
let seen = compacts.clone();
|
||||
let table = Table::new_with_handler("my_table", move |request| {
|
||||
let path = request.url().path().to_string();
|
||||
if path.contains("flush_memwal") {
|
||||
if path.contains("flush_rte") {
|
||||
return accepted();
|
||||
}
|
||||
if path.contains("compact_memwal") {
|
||||
if path.contains("compact_rte") {
|
||||
// First two triggers: every table shard already latched.
|
||||
if seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2 {
|
||||
return http::Response::builder()
|
||||
@@ -10641,7 +10639,7 @@ mod tests {
|
||||
});
|
||||
|
||||
table
|
||||
.checkpoint_memwal()
|
||||
.checkpoint_rte()
|
||||
.await
|
||||
.expect("contention must not abort the checkpoint");
|
||||
assert_eq!(
|
||||
@@ -10661,7 +10659,7 @@ mod tests {
|
||||
let seen = polls.clone();
|
||||
let table = Table::new_with_handler("my_table", move |request| {
|
||||
let path = request.url().path().to_string();
|
||||
if path.contains("flush_memwal") || path.contains("compact_memwal") {
|
||||
if path.contains("flush_rte") || path.contains("compact_rte") {
|
||||
return accepted();
|
||||
}
|
||||
// The opening read lands; the next two polls are latched out.
|
||||
@@ -10676,7 +10674,7 @@ mod tests {
|
||||
});
|
||||
|
||||
table
|
||||
.checkpoint_memwal()
|
||||
.checkpoint_rte()
|
||||
.await
|
||||
.expect("a contended poll must be retried, not surfaced");
|
||||
assert_eq!(
|
||||
@@ -10696,7 +10694,7 @@ mod tests {
|
||||
let seen = flushes.clone();
|
||||
let table = Table::new_with_handler("my_table", move |request| {
|
||||
let path = request.url().path().to_string();
|
||||
if path.contains("flush_memwal") {
|
||||
if path.contains("flush_rte") {
|
||||
if seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 5 {
|
||||
return http::Response::builder()
|
||||
.status(429)
|
||||
@@ -10705,14 +10703,14 @@ mod tests {
|
||||
}
|
||||
return accepted();
|
||||
}
|
||||
if path.contains("compact_memwal") {
|
||||
if path.contains("compact_rte") {
|
||||
return accepted();
|
||||
}
|
||||
ok_json(stats_body(&[], false))
|
||||
});
|
||||
|
||||
table
|
||||
.checkpoint_memwal()
|
||||
.checkpoint_rte()
|
||||
.await
|
||||
.expect("contention must not be reported as a lost claim");
|
||||
assert_eq!(
|
||||
@@ -10737,7 +10735,7 @@ mod tests {
|
||||
.unwrap()
|
||||
});
|
||||
|
||||
let err = table.checkpoint_memwal().await.unwrap_err();
|
||||
let err = table.checkpoint_rte().await.unwrap_err();
|
||||
assert!(
|
||||
matches!(&err, Error::Http { status_code: Some(s), .. } if s.as_u16() == 429),
|
||||
"the fault that spent the budget must be the one reported: {err:?}"
|
||||
@@ -10767,7 +10765,7 @@ mod tests {
|
||||
.unwrap()
|
||||
});
|
||||
|
||||
let err = table.checkpoint_memwal().await.unwrap_err();
|
||||
let err = table.checkpoint_rte().await.unwrap_err();
|
||||
let message = err.to_string();
|
||||
assert!(
|
||||
matches!(&err, Error::Http { status_code: Some(s), .. } if s.as_u16() == 503),
|
||||
@@ -10795,7 +10793,7 @@ mod tests {
|
||||
let seen = polls.clone();
|
||||
let table = Table::new_with_handler("my_table", move |request| {
|
||||
let path = request.url().path().to_string();
|
||||
if path.contains("flush_memwal") || path.contains("compact_memwal") {
|
||||
if path.contains("flush_rte") || path.contains("compact_rte") {
|
||||
return accepted();
|
||||
}
|
||||
// Flat for far longer than any bound this loop ever had, with
|
||||
@@ -10805,7 +10803,7 @@ mod tests {
|
||||
});
|
||||
|
||||
table
|
||||
.checkpoint_memwal()
|
||||
.checkpoint_rte()
|
||||
.await
|
||||
.expect("a stall is the server being slow, not the client's call to make");
|
||||
assert!(
|
||||
@@ -10825,10 +10823,10 @@ mod tests {
|
||||
let seen_compacts = compacts.clone();
|
||||
let table = Table::new_with_handler("my_table", move |request| {
|
||||
let path = request.url().path().to_string();
|
||||
if path.contains("flush_memwal") {
|
||||
if path.contains("flush_rte") {
|
||||
return accepted();
|
||||
}
|
||||
if path.contains("compact_memwal") {
|
||||
if path.contains("compact_rte") {
|
||||
seen_compacts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
return accepted();
|
||||
}
|
||||
@@ -10842,7 +10840,7 @@ mod tests {
|
||||
});
|
||||
|
||||
table
|
||||
.checkpoint_memwal()
|
||||
.checkpoint_rte()
|
||||
.await
|
||||
.expect("a running pass is progress, not a stall");
|
||||
assert_eq!(
|
||||
@@ -10856,9 +10854,9 @@ mod tests {
|
||||
/// defaulting to a zero it did not measure. `include_sstable_rows`
|
||||
/// rides in the body and is off unless asked for.
|
||||
#[tokio::test]
|
||||
async fn test_get_memwal_stats_round_trip() {
|
||||
async fn test_get_rte_stats_round_trip() {
|
||||
let table = Table::new_with_handler("my_table", |request| {
|
||||
assert_eq!(request.url().path(), "/v1/table/my_table/get_memwal_stats/");
|
||||
assert_eq!(request.url().path(), "/v1/table/my_table/get_rte_stats/");
|
||||
let body = request.body().unwrap().as_bytes().unwrap();
|
||||
let body: serde_json::Value = serde_json::from_slice(body).unwrap();
|
||||
assert_eq!(
|
||||
@@ -10866,7 +10864,7 @@ mod tests {
|
||||
"the flag must reach the server, not be silently dropped"
|
||||
);
|
||||
let response = serde_json::json!({
|
||||
"memwal_stats": {
|
||||
"rte_stats": {
|
||||
"table_shards": [{
|
||||
"shard_id": "b0",
|
||||
"status": "Active",
|
||||
@@ -10891,7 +10889,7 @@ mod tests {
|
||||
});
|
||||
|
||||
let stats = table
|
||||
.get_memwal_stats(true)
|
||||
.get_rte_stats(true)
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("a WAL-backed table reports Some");
|
||||
@@ -10923,7 +10921,7 @@ mod tests {
|
||||
.unwrap()
|
||||
});
|
||||
|
||||
let err = table.checkpoint_memwal().await.unwrap_err();
|
||||
let err = table.checkpoint_rte().await.unwrap_err();
|
||||
assert!(
|
||||
matches!(err, Error::TableNotFound { .. }),
|
||||
"a missing table must say so: {err:?}"
|
||||
@@ -10944,12 +10942,12 @@ mod tests {
|
||||
let table = Table::new_with_handler("my_table", move |request| {
|
||||
let path = request.url().path().to_string();
|
||||
let n = seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
if path.contains("flush_memwal") {
|
||||
if path.contains("flush_rte") {
|
||||
// First flush lands; the claim is then lost, and the
|
||||
// re-issued flush succeeds.
|
||||
return accepted();
|
||||
}
|
||||
if path.contains("compact_memwal") {
|
||||
if path.contains("compact_rte") {
|
||||
if n < 4 {
|
||||
return http::Response::builder()
|
||||
.status(421)
|
||||
@@ -10962,20 +10960,20 @@ mod tests {
|
||||
});
|
||||
|
||||
table
|
||||
.checkpoint_memwal()
|
||||
.checkpoint_rte()
|
||||
.await
|
||||
.expect("a lost claim must be recovered by re-flushing, not surfaced");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_get_memwal_stats_absent_when_wal_off() {
|
||||
async fn test_get_rte_stats_absent_when_wal_off() {
|
||||
let table = Table::new_with_handler("my_table", |_request| {
|
||||
http::Response::builder()
|
||||
.status(200)
|
||||
.body(serde_json::json!({ "memwal_stats": null }).to_string())
|
||||
.body(serde_json::json!({ "rte_stats": null }).to_string())
|
||||
.unwrap()
|
||||
});
|
||||
assert!(table.get_memwal_stats(false).await.unwrap().is_none());
|
||||
assert!(table.get_rte_stats(false).await.unwrap().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -15006,9 +15004,10 @@ mod tests {
|
||||
|
||||
// WAL-PK-FUSION: delete everything from here to the end of `mod tests`.
|
||||
|
||||
/// Verbatim from sophon's `LSM_WITH_ROW_ID_UNSUPPORTED`; the fallback keys
|
||||
/// off this sentence, so a test that paraphrased it would prove nothing.
|
||||
const WAL_ROW_ID_REFUSAL_BODY: &str = r#"{"code":13,"error":"Bad request: the MemWAL LSM scanner does not support with_row_id (the LSM scanner exposes _rowaddr, not a stable _rowid); set use_memwal(false) to read the base table only (results will exclude un-compacted MemWAL data)"}"#;
|
||||
/// Verbatim from sophon's `wal_unsupported(WITH_ROW_ID_UNSUPPORTED)`; the
|
||||
/// fallback keys off this sentence, so a test that paraphrased it would prove
|
||||
/// nothing.
|
||||
const WAL_ROW_ID_REFUSAL_BODY: &str = r#"{"code":13,"error":"Bad request: WAL unsupported: the MemWAL fresh tier does not support with_row_id: it has no stable _rowid; set use_rte(false) to read the base table only (results will exclude un-compacted RTE data)"}"#;
|
||||
|
||||
use lance::dataset::ROW_ID;
|
||||
|
||||
@@ -15052,7 +15051,7 @@ mod tests {
|
||||
RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).unwrap()
|
||||
}
|
||||
|
||||
/// A server that refuses `_rowid` the way a MemWAL table does, recording
|
||||
/// A server that refuses `_rowid` the way an RTE table does, recording
|
||||
/// every query body so a test can see which key each attempt asked for.
|
||||
fn wal_refusing_table(bodies: Arc<std::sync::Mutex<Vec<serde_json::Value>>>) -> Table {
|
||||
Table::new_with_handler("my_table", move |request| match request.url().path() {
|
||||
@@ -15093,7 +15092,7 @@ mod tests {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// The optimistic path: ask for `_rowid`, and when a MemWAL table refuses,
|
||||
/// The optimistic path: ask for `_rowid`, and when an RTE table refuses,
|
||||
/// fall back to the primary key rather than failing.
|
||||
#[tokio::test]
|
||||
async fn test_hybrid_falls_back_to_the_primary_key_when_row_id_is_refused() {
|
||||
@@ -15267,7 +15266,7 @@ mod tests {
|
||||
// Translated, not passed through: the caller gets the reason and the
|
||||
// way out, which a bare 400 does not carry.
|
||||
assert!(matches!(err, Error::NotSupported { .. }), "{err:?}");
|
||||
assert!(err.to_string().contains("use_memwal(false)"), "{err}");
|
||||
assert!(err.to_string().contains("use_rte(false)"), "{err}");
|
||||
assert!(
|
||||
bodies
|
||||
.lock()
|
||||
|
||||
@@ -716,8 +716,8 @@ impl<S: HttpSend> RemoteTable<S> {
|
||||
)),
|
||||
select: Select::columns(&[column]),
|
||||
with_row_id: true,
|
||||
// Row ids name base-table rows, and the MemWAL scanner has no stable `_rowid`.
|
||||
use_memwal: Some(false),
|
||||
// Row ids name base-table rows, and the RTE scanner has no stable `_rowid`.
|
||||
use_rte: Some(false),
|
||||
..Default::default()
|
||||
});
|
||||
let body = self
|
||||
@@ -1153,7 +1153,7 @@ mod tests {
|
||||
.unwrap();
|
||||
assert_eq!(body["columns"], serde_json::json!(["image"]));
|
||||
assert_eq!(body["with_row_id"], serde_json::json!(true));
|
||||
assert_eq!(body["use_memwal"], serde_json::json!(false));
|
||||
assert_eq!(body["use_rte"], serde_json::json!(false));
|
||||
let requested = filter_row_ids(body["filter"].as_str().unwrap());
|
||||
captured.lock().unwrap().push(TakeMockRequest::Query {
|
||||
row_ids: requested.clone(),
|
||||
|
||||
@@ -1497,7 +1497,7 @@ mod tests {
|
||||
when_not_matched_by_source_delete: false,
|
||||
when_not_matched_by_source_delete_filt: None,
|
||||
use_index: true,
|
||||
use_memwal: None,
|
||||
use_rte: None,
|
||||
};
|
||||
|
||||
let input: Arc<dyn ExecutionPlan> = Arc::new(ErroringExec::new());
|
||||
|
||||
+157
-170
@@ -80,12 +80,12 @@ pub mod datafusion;
|
||||
pub(crate) mod dataset;
|
||||
pub mod delete;
|
||||
pub mod freshness;
|
||||
pub mod memwal_stats;
|
||||
pub mod merge;
|
||||
pub mod optimize;
|
||||
pub(crate) mod primary_key;
|
||||
pub mod query;
|
||||
pub mod refresh;
|
||||
pub mod rte_stats;
|
||||
pub mod schema_evolution;
|
||||
pub mod update;
|
||||
pub mod write_progress;
|
||||
@@ -107,9 +107,9 @@ use futures::future::join_all;
|
||||
pub use lance::dataset::refs::{BranchContents, Ref, TagContents, Tags as LanceTags};
|
||||
pub use lance::dataset::scanner::DatasetRecordBatchStream;
|
||||
pub use lance_index::optimize::OptimizeOptions;
|
||||
pub use memwal_stats::{MemWalStats, MemtableStats, SsTableStats, TableShardStats};
|
||||
pub use optimize::{CompactionOptions, OptimizeAction, OptimizeStats};
|
||||
pub use refresh::RefreshColumnResult;
|
||||
pub use rte_stats::{MemtableStats, RTEStats, SsTableStats, TableShardStats};
|
||||
pub use schema_evolution::{
|
||||
AddColumnsResult, AlterColumnsResult, DropColumnsResult, FieldMetadataUpdate,
|
||||
UpdateFieldMetadataResult,
|
||||
@@ -324,23 +324,23 @@ pub trait Tags: Send + Sync {
|
||||
|
||||
pub use self::merge::MergeResult;
|
||||
|
||||
/// Specification selecting Lance's MemWAL LSM-style write path for
|
||||
/// `merge_insert`.
|
||||
/// Specification enabling the realtime engine (RTE), which routes
|
||||
/// `merge_insert` through Lance's MemWAL LSM-style write path.
|
||||
///
|
||||
/// Construct via [`MemWalWriteSpec::bucket`], [`MemWalWriteSpec::identity`], or
|
||||
/// [`MemWalWriteSpec::unsharded`], then optionally chain
|
||||
/// [`MemWalWriteSpec::with_maintained_indexes`] (indexes the MemWAL keeps up to
|
||||
/// date) and [`MemWalWriteSpec::with_writer_config_defaults`] (default
|
||||
/// Construct via [`RTEWriteSpec::bucket`], [`RTEWriteSpec::identity`], or
|
||||
/// [`RTEWriteSpec::unsharded`], then optionally chain
|
||||
/// [`RTEWriteSpec::with_maintained_indexes`] (indexes the RTE keeps up to
|
||||
/// date) and [`RTEWriteSpec::with_writer_config_defaults`] (default
|
||||
/// `ShardWriter` configuration recorded in the MemWAL index).
|
||||
///
|
||||
/// A fresh spec maintains every index on the table, including ones created
|
||||
/// after it is installed.
|
||||
///
|
||||
/// Install a spec with [`Table::enable_memwal`] and remove it with
|
||||
/// [`Table::disable_memwal`]. The actual `merge_insert` dispatch
|
||||
/// onto the MemWAL writer is a follow-up.
|
||||
/// Install a spec with [`Table::enable_rte`] and remove it with
|
||||
/// [`Table::disable_rte`]. The actual `merge_insert` dispatch
|
||||
/// onto the RTE writer is a follow-up.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum MemWalWriteSpec {
|
||||
pub enum RTEWriteSpec {
|
||||
/// Hash-bucket sharding by a scalar column.
|
||||
///
|
||||
/// `column` must be a non-nested column with a supported scalar type.
|
||||
@@ -350,7 +350,7 @@ pub enum MemWalWriteSpec {
|
||||
Bucket {
|
||||
column: String,
|
||||
num_buckets: u32,
|
||||
/// Indexes the MemWAL maintains in-memory as rows are appended.
|
||||
/// Indexes the RTE maintains in-memory as rows are appended.
|
||||
///
|
||||
/// `None` means every index the table has, including ones created
|
||||
/// later. `Some([])` maintains nothing.
|
||||
@@ -364,7 +364,7 @@ pub enum MemWalWriteSpec {
|
||||
/// distinct value of `column` becomes its own shard.
|
||||
Identity {
|
||||
column: String,
|
||||
/// Indexes the MemWAL maintains in-memory as rows are appended.
|
||||
/// Indexes the RTE maintains in-memory as rows are appended.
|
||||
///
|
||||
/// `None` means every index the table has, including ones created
|
||||
/// later. `Some([])` maintains nothing.
|
||||
@@ -372,9 +372,9 @@ pub enum MemWalWriteSpec {
|
||||
/// Default `ShardWriter` configuration recorded in the MemWAL index.
|
||||
writer_config_defaults: HashMap<String, String>,
|
||||
},
|
||||
/// No sharding — every `merge_insert` call writes to a single MemWAL shard.
|
||||
/// No sharding — every `merge_insert` call writes to a single RTE shard.
|
||||
Unsharded {
|
||||
/// Indexes the MemWAL maintains in-memory as rows are appended.
|
||||
/// Indexes the RTE maintains in-memory as rows are appended.
|
||||
///
|
||||
/// `None` means every index the table has, including ones created
|
||||
/// later. `Some([])` maintains nothing.
|
||||
@@ -384,7 +384,7 @@ pub enum MemWalWriteSpec {
|
||||
},
|
||||
}
|
||||
|
||||
impl MemWalWriteSpec {
|
||||
impl RTEWriteSpec {
|
||||
/// Construct a hash-bucket sharding spec maintaining every index on the table.
|
||||
pub fn bucket(column: impl Into<String>, num_buckets: u32) -> Self {
|
||||
Self::Bucket {
|
||||
@@ -400,7 +400,7 @@ impl MemWalWriteSpec {
|
||||
///
|
||||
/// `column` must be a deterministic function of the unenforced primary
|
||||
/// key: every row with a given primary key must always produce the same
|
||||
/// `column` value. MemWAL dedups upserts by primary key but tracks
|
||||
/// `column` value. RTE dedups upserts by primary key but tracks
|
||||
/// SSTables per shard, so if the same key is written with two
|
||||
/// different `column` values its versions land in different shards and a
|
||||
/// stale value can win. Typically `column` is the primary key itself, or
|
||||
@@ -421,23 +421,23 @@ impl MemWalWriteSpec {
|
||||
}
|
||||
}
|
||||
|
||||
/// Set which indexes the MemWAL maintains.
|
||||
/// Set which indexes the RTE maintains.
|
||||
///
|
||||
/// `None` (the default) is every index on the table, re-read as the table
|
||||
/// changes, so an index created later is maintained too; one of a kind the
|
||||
/// MemWAL cannot mirror is skipped rather than failing the table. A list is
|
||||
/// RTE cannot mirror is skipped rather than failing the table. A list is
|
||||
/// verbatim: each name must already exist and be maintainable, and an empty
|
||||
/// list maintains nothing. The maintainable kinds are Lance's built-ins plus
|
||||
/// any added with [`NativeTable::set_mem_index_registry`].
|
||||
///
|
||||
/// ```
|
||||
/// # use lancedb::table::MemWalWriteSpec;
|
||||
/// # use lancedb::table::RTEWriteSpec;
|
||||
/// // Every index the table has, now and later:
|
||||
/// MemWalWriteSpec::unsharded().with_maintained_indexes(None);
|
||||
/// RTEWriteSpec::unsharded().with_maintained_indexes(None);
|
||||
/// // Exactly these:
|
||||
/// MemWalWriteSpec::unsharded().with_maintained_indexes(vec!["id_idx".to_string()]);
|
||||
/// RTEWriteSpec::unsharded().with_maintained_indexes(vec!["id_idx".to_string()]);
|
||||
/// // None at all:
|
||||
/// MemWalWriteSpec::unsharded().with_maintained_indexes(Vec::new());
|
||||
/// RTEWriteSpec::unsharded().with_maintained_indexes(Vec::new());
|
||||
/// ```
|
||||
pub fn with_maintained_indexes(mut self, indexes: impl Into<Option<Vec<String>>>) -> Self {
|
||||
let indexes = indexes.into();
|
||||
@@ -455,7 +455,7 @@ impl MemWalWriteSpec {
|
||||
self
|
||||
}
|
||||
|
||||
/// Replace the default `ShardWriter` configuration recorded in the MemWAL
|
||||
/// Replace the default `ShardWriter` configuration recorded in the RTE
|
||||
/// index, so every writer starts from the same defaults. Keys are
|
||||
/// `ShardWriter` config field names (`Duration` knobs use a `_ms` suffix);
|
||||
/// values are their string encodings.
|
||||
@@ -486,7 +486,7 @@ impl MemWalWriteSpec {
|
||||
self
|
||||
}
|
||||
|
||||
/// Borrow the list of index names this spec asks MemWAL to maintain, or
|
||||
/// Borrow the list of index names this spec asks RTE to maintain, or
|
||||
/// `None` when it asks for every index on the table.
|
||||
pub fn maintained_indexes(&self) -> Option<&[String]> {
|
||||
match self {
|
||||
@@ -674,37 +674,37 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync {
|
||||
message: "set_unenforced_primary_key is not supported on this table type".into(),
|
||||
})
|
||||
}
|
||||
/// Install an [`MemWalWriteSpec`] on this table.
|
||||
/// Install an [`RTEWriteSpec`] on this table.
|
||||
///
|
||||
/// The spec selects Lance's MemWAL LSM-style write path for future
|
||||
/// `merge_insert` calls.
|
||||
///
|
||||
/// The default implementation returns `NotSupported`. Implementations
|
||||
/// that support the MemWAL write path must override this.
|
||||
async fn enable_memwal(&self, _spec: MemWalWriteSpec) -> Result<()> {
|
||||
/// that support the RTE write path must override this.
|
||||
async fn enable_rte(&self, _spec: RTEWriteSpec) -> Result<()> {
|
||||
Err(Error::NotSupported {
|
||||
message: "enable_memwal is not supported on this table type".into(),
|
||||
message: "enable_rte is not supported on this table type".into(),
|
||||
})
|
||||
}
|
||||
/// Remove the [`MemWalWriteSpec`] from this table.
|
||||
/// Remove the [`RTEWriteSpec`] from this table.
|
||||
///
|
||||
/// This is a no-op if no spec is currently set.
|
||||
///
|
||||
/// The default implementation returns `NotSupported`. Implementations
|
||||
/// that support the MemWAL write path must override this.
|
||||
async fn disable_memwal(&self) -> Result<()> {
|
||||
/// that support the RTE write path must override this.
|
||||
async fn disable_rte(&self) -> Result<()> {
|
||||
Err(Error::NotSupported {
|
||||
message: "disable_memwal is not supported on this table type".into(),
|
||||
message: "disable_rte is not supported on this table type".into(),
|
||||
})
|
||||
}
|
||||
/// Read the [`MemWalWriteSpec`] currently installed on this table, returning
|
||||
/// `None` when the MemWAL write path is not enabled.
|
||||
/// Read the [`RTEWriteSpec`] currently installed on this table, returning
|
||||
/// `None` when the RTE write path is not enabled.
|
||||
///
|
||||
/// The default implementation returns `NotSupported`. Implementations that
|
||||
/// support the MemWAL write path must override this.
|
||||
async fn get_memwal_spec(&self) -> Result<Option<MemWalWriteSpec>> {
|
||||
/// support the RTE write path must override this.
|
||||
async fn get_rte_spec(&self) -> Result<Option<RTEWriteSpec>> {
|
||||
Err(Error::NotSupported {
|
||||
message: "get_memwal_spec is not supported on this table type".into(),
|
||||
message: "get_rte_spec is not supported on this table type".into(),
|
||||
})
|
||||
}
|
||||
/// Whether a hybrid query on this table has already been told it cannot
|
||||
@@ -713,7 +713,7 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync {
|
||||
/// WAL-PK-FUSION: delete this and `note_hybrid_pk_fusion`.
|
||||
///
|
||||
/// Learned, never probed: hybrid optimistically asks for `_rowid` and only
|
||||
/// a MemWAL table refuses, so paying a round trip up front would tax every
|
||||
/// an RTE table refuses, so paying a round trip up front would tax every
|
||||
/// table to discover something almost none of them need. Synchronous and
|
||||
/// free by construction — an implementation may only answer from what a
|
||||
/// previous query already learned.
|
||||
@@ -735,33 +735,33 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync {
|
||||
/// Freeze every table shard's active memtable into an SSTable.
|
||||
///
|
||||
/// The default implementation returns `NotSupported`.
|
||||
async fn flush_memwal(&self) -> Result<()> {
|
||||
async fn flush_rte(&self) -> Result<()> {
|
||||
Err(Error::NotSupported {
|
||||
message: "flush_memwal is not supported on this table type".into(),
|
||||
message: "flush_rte is not supported on this table type".into(),
|
||||
})
|
||||
}
|
||||
/// Trigger a background SSTable compaction pass per table shard.
|
||||
///
|
||||
/// The default implementation returns `NotSupported`.
|
||||
async fn compact_memwal(&self) -> Result<()> {
|
||||
async fn compact_rte(&self) -> Result<()> {
|
||||
Err(Error::NotSupported {
|
||||
message: "compact_memwal is not supported on this table type".into(),
|
||||
message: "compact_rte is not supported on this table type".into(),
|
||||
})
|
||||
}
|
||||
/// Read live MemWAL state, or `None` when the MemWAL write path is not
|
||||
/// Read live RTE state, or `None` when the RTE write path is not
|
||||
/// enabled for this table.
|
||||
///
|
||||
/// The default implementation returns `NotSupported`.
|
||||
async fn get_memwal_stats(&self, _include_sstable_rows: bool) -> Result<Option<MemWalStats>> {
|
||||
async fn get_rte_stats(&self, _include_sstable_rows: bool) -> Result<Option<RTEStats>> {
|
||||
Err(Error::NotSupported {
|
||||
message: "get_memwal_stats is not supported on this table type".into(),
|
||||
message: "get_rte_stats is not supported on this table type".into(),
|
||||
})
|
||||
}
|
||||
/// Drain and close any cached MemWAL shard writers for this table.
|
||||
/// Drain and close any cached RTE shard writers for this table.
|
||||
///
|
||||
/// The default implementation is a no-op; table types that maintain
|
||||
/// MemWAL shard writers override it.
|
||||
async fn close_memwal_writers(&self) -> Result<()> {
|
||||
/// RTE shard writers override it.
|
||||
async fn close_rte_writers(&self) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
/// Names of the blob v2 columns in this table, in declaration order.
|
||||
@@ -2008,53 +2008,53 @@ impl Table {
|
||||
self.inner.set_unenforced_primary_key(&borrowed).await
|
||||
}
|
||||
|
||||
/// Install an [`MemWalWriteSpec`] on this table, selecting Lance's MemWAL
|
||||
/// Install an [`RTEWriteSpec`] on this table, selecting Lance's MemWAL
|
||||
/// LSM-style write path for future `merge_insert` calls.
|
||||
///
|
||||
/// [`MemWalWriteSpec`] chooses one of three sharding strategies:
|
||||
/// [`RTEWriteSpec`] chooses one of three sharding strategies:
|
||||
///
|
||||
/// - [`MemWalWriteSpec::bucket`] — hash-bucket writes by a scalar column.
|
||||
/// - [`MemWalWriteSpec::identity`] — shard by the raw value of a scalar column.
|
||||
/// - [`MemWalWriteSpec::unsharded`] — route every write to a single shard.
|
||||
/// - [`RTEWriteSpec::bucket`] — hash-bucket writes by a scalar column.
|
||||
/// - [`RTEWriteSpec::identity`] — shard by the raw value of a scalar column.
|
||||
/// - [`RTEWriteSpec::unsharded`] — route every write to a single shard.
|
||||
///
|
||||
/// Every spec requires the table to declare an unenforced primary key
|
||||
/// ([`Table::set_unenforced_primary_key`]); otherwise this fails.
|
||||
///
|
||||
/// A table carries one spec: this fails while one is installed, since the
|
||||
/// SSTables already written were homed under it.
|
||||
/// [`Table::disable_memwal`] removes one.
|
||||
/// [`Table::disable_rte`] removes one.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// # use lancedb::table::{MemWalWriteSpec, Table};
|
||||
/// # use lancedb::table::{RTEWriteSpec, Table};
|
||||
/// # async fn example(table: &Table) -> Result<(), Box<dyn std::error::Error>> {
|
||||
/// table
|
||||
/// .enable_memwal(
|
||||
/// MemWalWriteSpec::bucket("id", 16).with_maintained_indexes(vec!["id_idx".to_string()]),
|
||||
/// .enable_rte(
|
||||
/// RTEWriteSpec::bucket("id", 16).with_maintained_indexes(vec!["id_idx".to_string()]),
|
||||
/// )
|
||||
/// .await?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub async fn enable_memwal(&self, spec: MemWalWriteSpec) -> Result<()> {
|
||||
self.inner.enable_memwal(spec).await
|
||||
pub async fn enable_rte(&self, spec: RTEWriteSpec) -> Result<()> {
|
||||
self.inner.enable_rte(spec).await
|
||||
}
|
||||
|
||||
/// Remove the [`MemWalWriteSpec`] from this table, reverting to the standard
|
||||
/// Remove the [`RTEWriteSpec`] from this table, reverting to the standard
|
||||
/// `merge_insert` write path.
|
||||
///
|
||||
/// Errors if no spec is currently set.
|
||||
pub async fn disable_memwal(&self) -> Result<()> {
|
||||
self.inner.disable_memwal().await
|
||||
pub async fn disable_rte(&self) -> Result<()> {
|
||||
self.inner.disable_rte().await
|
||||
}
|
||||
|
||||
/// Read the [`MemWalWriteSpec`] currently installed on this table.
|
||||
/// Read the [`RTEWriteSpec`] currently installed on this table.
|
||||
///
|
||||
/// `Ok(None)` means the MemWAL write path is not enabled at all — no spec has
|
||||
/// been set, or one was removed with [`Table::disable_memwal`]. That
|
||||
/// `Ok(None)` means the RTE write path is not enabled at all — no spec has
|
||||
/// been set, or one was removed with [`Table::disable_rte`]. That
|
||||
/// is a different answer from a spec whose
|
||||
/// [`MemWalWriteSpec::maintained_indexes`] is `None`, which is an installed
|
||||
/// [`RTEWriteSpec::maintained_indexes`] is `None`, which is an installed
|
||||
/// spec selecting indexes automatically.
|
||||
///
|
||||
/// The spec read back is the one that was installed, selection included:
|
||||
@@ -2067,21 +2067,21 @@ impl Table {
|
||||
/// ```
|
||||
/// # use lancedb::table::Table;
|
||||
/// # async fn example(table: &Table) -> Result<(), Box<dyn std::error::Error>> {
|
||||
/// if let Some(spec) = table.get_memwal_spec().await? {
|
||||
/// println!("MemWAL write path enabled: {:?}", spec);
|
||||
/// if let Some(spec) = table.get_rte_spec().await? {
|
||||
/// println!("RTE write path enabled: {:?}", spec);
|
||||
/// }
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub async fn get_memwal_spec(&self) -> Result<Option<MemWalWriteSpec>> {
|
||||
self.inner.get_memwal_spec().await
|
||||
pub async fn get_rte_spec(&self) -> Result<Option<RTEWriteSpec>> {
|
||||
self.inner.get_rte_spec().await
|
||||
}
|
||||
|
||||
/// Converge this table's MemWAL write path into its base table.
|
||||
/// Converge this table's RTE write path into its base table.
|
||||
///
|
||||
/// One `flush` to freeze every memtable into an SSTable, then compaction triggers
|
||||
/// until every generation that existed at that moment has reached base.
|
||||
/// The loop runs client-side, reading progress from `get_memwal_stats`, so
|
||||
/// The loop runs client-side, reading progress from `get_rte_stats`, so
|
||||
/// there is no held socket and nothing to reconcile if you drop this
|
||||
/// future partway through.
|
||||
///
|
||||
@@ -2104,14 +2104,14 @@ impl Table {
|
||||
/// ```no_run
|
||||
/// # use lancedb::Table;
|
||||
/// # async fn example(table: &Table) -> Result<(), Box<dyn std::error::Error>> {
|
||||
/// let before = table.get_memwal_stats(false).await?;
|
||||
/// table.checkpoint_memwal().await?;
|
||||
/// let after = table.get_memwal_stats(false).await?;
|
||||
/// let before = table.get_rte_stats(false).await?;
|
||||
/// table.checkpoint_rte().await?;
|
||||
/// let after = table.get_rte_stats(false).await?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub async fn checkpoint_memwal(&self) -> Result<()> {
|
||||
checkpoint::checkpoint_memwal(self).await
|
||||
pub async fn checkpoint_rte(&self) -> Result<()> {
|
||||
checkpoint::checkpoint_rte(self).await
|
||||
}
|
||||
|
||||
/// Freeze every table shard's active memtable into an SSTable without touching the
|
||||
@@ -2121,8 +2121,8 @@ impl Table {
|
||||
/// a lower per-query cost. On a node that has not claimed this table it
|
||||
/// claims it and replays the WAL log first — reporting "nothing to flush"
|
||||
/// without replaying would lie about durable data.
|
||||
pub async fn flush_memwal(&self) -> Result<()> {
|
||||
self.inner.flush_memwal().await
|
||||
pub async fn flush_rte(&self) -> Result<()> {
|
||||
self.inner.flush_rte().await
|
||||
}
|
||||
|
||||
/// Run one bounded SSTable compaction pass per table shard, reporting what
|
||||
@@ -2130,11 +2130,11 @@ impl Table {
|
||||
///
|
||||
/// One pass, not convergence: that bounds each request's cost and gives a
|
||||
/// caller driving its own cadence a progress signal per round trip.
|
||||
pub async fn compact_memwal(&self) -> Result<()> {
|
||||
self.inner.compact_memwal().await
|
||||
pub async fn compact_rte(&self) -> Result<()> {
|
||||
self.inner.compact_rte().await
|
||||
}
|
||||
|
||||
/// Read live per-table-shard MemWAL state.
|
||||
/// Read live per-table-shard RTE state.
|
||||
///
|
||||
/// Answers "how far behind is my fresh tier", "which table shard is hot", and
|
||||
/// "why is my fresh-tier vector search brute-force". Mutates no table
|
||||
@@ -2143,30 +2143,27 @@ impl Table {
|
||||
///
|
||||
/// `include_sstable_rows` reports a row count per SSTable. Off by
|
||||
/// default: each count opens an uncached Lance dataset, and
|
||||
/// `checkpoint_memwal` polls this needing only generation numbers.
|
||||
/// `checkpoint_rte` polls this needing only generation numbers.
|
||||
///
|
||||
/// `Ok(None)` only when the MemWAL write path is not enabled, matching
|
||||
/// [`Table::get_memwal_spec`]. Stats is fresh-tier only, so with the
|
||||
/// `Ok(None)` only when the RTE write path is not enabled, matching
|
||||
/// [`Table::get_rte_spec`]. Stats is fresh-tier only, so with the
|
||||
/// WAL off there is no manifest to report and a struct of zeros would
|
||||
/// read as measurements.
|
||||
///
|
||||
/// Do not build a checkpoint's termination on this: the completion
|
||||
/// predicate lives in the `flush` and `compact` responses.
|
||||
pub async fn get_memwal_stats(
|
||||
&self,
|
||||
include_sstable_rows: bool,
|
||||
) -> Result<Option<MemWalStats>> {
|
||||
self.inner.get_memwal_stats(include_sstable_rows).await
|
||||
pub async fn get_rte_stats(&self, include_sstable_rows: bool) -> Result<Option<RTEStats>> {
|
||||
self.inner.get_rte_stats(include_sstable_rows).await
|
||||
}
|
||||
|
||||
/// Drain and close any cached MemWAL shard writers held for this table.
|
||||
/// Drain and close any cached RTE shard writers held for this table.
|
||||
///
|
||||
/// When an [`MemWalWriteSpec`] is installed, `merge_insert` opens MemWAL shard
|
||||
/// When an [`RTEWriteSpec`] is installed, `merge_insert` opens RTE shard
|
||||
/// writers and caches them for reuse across calls. This closes them,
|
||||
/// flushing pending data; writers reopen lazily on the next `merge_insert`.
|
||||
/// It is a no-op when no writers are cached.
|
||||
pub async fn close_memwal_writers(&self) -> Result<()> {
|
||||
self.inner.close_memwal_writers().await
|
||||
pub async fn close_rte_writers(&self) -> Result<()> {
|
||||
self.inner.close_rte_writers().await
|
||||
}
|
||||
|
||||
/// Retrieve the version of the table
|
||||
@@ -2784,8 +2781,8 @@ impl NativeTable {
|
||||
}
|
||||
|
||||
/// Maintain the memtable index kinds in `registry` when this table writes
|
||||
/// through its [`MemWalWriteSpec`], and accept them when
|
||||
/// [`MemWalWriteSpec::with_maintained_indexes`] names one.
|
||||
/// through its [`RTEWriteSpec`], and accept them when
|
||||
/// [`RTEWriteSpec::with_maintained_indexes`] names one.
|
||||
///
|
||||
/// The registry belongs to this handle, its clones and its branch handles,
|
||||
/// and is not stored with the table: a handle opened separately starts from
|
||||
@@ -2796,7 +2793,7 @@ impl NativeTable {
|
||||
/// ```
|
||||
/// # use std::sync::Arc;
|
||||
/// # use lancedb::Table;
|
||||
/// # use lancedb::table::{MemWalWriteSpec, MemIndexRegistry, mem_index::MemIndexPlugin};
|
||||
/// # use lancedb::table::{RTEWriteSpec, MemIndexRegistry, mem_index::MemIndexPlugin};
|
||||
/// # async fn example(
|
||||
/// # table: &Table,
|
||||
/// # plugin: Arc<dyn MemIndexPlugin>,
|
||||
@@ -2805,8 +2802,8 @@ impl NativeTable {
|
||||
/// if let Some(native) = table.as_native() {
|
||||
/// native.set_mem_index_registry(registry);
|
||||
/// }
|
||||
/// let spec = MemWalWriteSpec::unsharded().with_maintained_indexes(vec!["region_bitmap".to_string()]);
|
||||
/// table.enable_memwal(spec).await?;
|
||||
/// let spec = RTEWriteSpec::unsharded().with_maintained_indexes(vec!["region_bitmap".to_string()]);
|
||||
/// table.enable_rte(spec).await?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
@@ -3699,20 +3696,20 @@ impl BaseTable for NativeTable {
|
||||
primary_key::set_unenforced_primary_key(self, columns).await
|
||||
}
|
||||
|
||||
async fn enable_memwal(&self, spec: MemWalWriteSpec) -> Result<()> {
|
||||
merge::lsm::enable_memwal(self, spec).await
|
||||
async fn enable_rte(&self, spec: RTEWriteSpec) -> Result<()> {
|
||||
merge::lsm::enable_rte(self, spec).await
|
||||
}
|
||||
|
||||
async fn disable_memwal(&self) -> Result<()> {
|
||||
merge::lsm::disable_memwal(self).await
|
||||
async fn disable_rte(&self) -> Result<()> {
|
||||
merge::lsm::disable_rte(self).await
|
||||
}
|
||||
|
||||
async fn get_memwal_spec(&self) -> Result<Option<MemWalWriteSpec>> {
|
||||
merge::lsm::get_memwal_spec(self).await
|
||||
async fn get_rte_spec(&self) -> Result<Option<RTEWriteSpec>> {
|
||||
merge::lsm::get_rte_spec(self).await
|
||||
}
|
||||
|
||||
async fn close_memwal_writers(&self) -> Result<()> {
|
||||
merge::lsm::close_memwal_writers(self).await
|
||||
async fn close_rte_writers(&self) -> Result<()> {
|
||||
merge::lsm::close_rte_writers(self).await
|
||||
}
|
||||
|
||||
async fn blob_columns(&self) -> Result<Vec<String>> {
|
||||
@@ -5518,7 +5515,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_enable_memwal() {
|
||||
async fn test_enable_rte() {
|
||||
use arrow_array::StringArray;
|
||||
use lance::dataset::mem_wal::DatasetMemWalExt;
|
||||
|
||||
@@ -5551,15 +5548,15 @@ mod tests {
|
||||
// Reject num_buckets out of range.
|
||||
for bad in [0u32, 1025] {
|
||||
let err = table
|
||||
.enable_memwal(MemWalWriteSpec::bucket("id", bad))
|
||||
.enable_rte(RTEWriteSpec::bucket("id", bad))
|
||||
.await
|
||||
.expect_err("should reject");
|
||||
assert!(matches!(err, Error::InvalidInput { .. }), "got {:?}", err);
|
||||
}
|
||||
|
||||
// Happy path: install spec; verify MemWAL details record it.
|
||||
// Happy path: install spec; verify RTE details record it.
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::bucket("id", 4))
|
||||
.enable_rte(RTEWriteSpec::bucket("id", 4))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -5585,7 +5582,7 @@ mod tests {
|
||||
|
||||
// Mutation rejected.
|
||||
let err = table
|
||||
.enable_memwal(MemWalWriteSpec::bucket("id", 8))
|
||||
.enable_rte(RTEWriteSpec::bucket("id", 8))
|
||||
.await
|
||||
.expect_err("mutation should be rejected");
|
||||
assert!(matches!(err, Error::InvalidInput { .. }), "got {:?}", err);
|
||||
@@ -5594,7 +5591,7 @@ mod tests {
|
||||
/// A spec is refused on a table without an unenforced primary key, for every
|
||||
/// sharding mode, and a refused spec leaves nothing installed.
|
||||
#[tokio::test]
|
||||
async fn test_enable_memwal_requires_primary_key() {
|
||||
async fn test_enable_rte_requires_primary_key() {
|
||||
use lance::dataset::mem_wal::DatasetMemWalExt;
|
||||
|
||||
let tmp_dir = tempdir().unwrap();
|
||||
@@ -5621,11 +5618,11 @@ mod tests {
|
||||
};
|
||||
|
||||
for spec in [
|
||||
MemWalWriteSpec::unsharded(),
|
||||
MemWalWriteSpec::bucket("id", 4),
|
||||
MemWalWriteSpec::identity("id"),
|
||||
RTEWriteSpec::unsharded(),
|
||||
RTEWriteSpec::bucket("id", 4),
|
||||
RTEWriteSpec::identity("id"),
|
||||
] {
|
||||
let err = table.enable_memwal(spec).await.unwrap_err();
|
||||
let err = table.enable_rte(spec).await.unwrap_err();
|
||||
assert!(
|
||||
matches!(&err, Error::InvalidInput { message } if message.contains("primary key")),
|
||||
"got {err:?}"
|
||||
@@ -5634,15 +5631,12 @@ mod tests {
|
||||
}
|
||||
|
||||
table.set_unenforced_primary_key(["id"]).await.unwrap();
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded())
|
||||
.await
|
||||
.unwrap();
|
||||
table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap();
|
||||
assert!(installed(&table).await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_enable_memwal_unsharded() {
|
||||
async fn test_enable_rte_unsharded() {
|
||||
use lance::dataset::mem_wal::DatasetMemWalExt;
|
||||
|
||||
let tmp_dir = tempdir().unwrap();
|
||||
@@ -5664,10 +5658,7 @@ mod tests {
|
||||
let table = conn.create_table("t", reader).execute().await.unwrap();
|
||||
table.set_unenforced_primary_key(["id"]).await.unwrap();
|
||||
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded())
|
||||
.await
|
||||
.unwrap();
|
||||
table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap();
|
||||
|
||||
let dataset = table.as_native().unwrap().dataset.get().await.unwrap();
|
||||
let details = dataset
|
||||
@@ -5683,7 +5674,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_enable_memwal_identity() {
|
||||
async fn test_enable_rte_identity() {
|
||||
use lance::dataset::mem_wal::DatasetMemWalExt;
|
||||
|
||||
let tmp_dir = tempdir().unwrap();
|
||||
@@ -5712,8 +5703,8 @@ mod tests {
|
||||
table.set_unenforced_primary_key(["id"]).await.unwrap();
|
||||
|
||||
table
|
||||
.enable_memwal(
|
||||
MemWalWriteSpec::identity("region")
|
||||
.enable_rte(
|
||||
RTEWriteSpec::identity("region")
|
||||
.with_writer_config_defaults([("durable_write", "false")]),
|
||||
)
|
||||
.await
|
||||
@@ -5741,7 +5732,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_disable_memwal() {
|
||||
async fn test_disable_rte() {
|
||||
use lance::dataset::mem_wal::DatasetMemWalExt;
|
||||
|
||||
let tmp_dir = tempdir().unwrap();
|
||||
@@ -5764,11 +5755,11 @@ mod tests {
|
||||
table.set_unenforced_primary_key(["id"]).await.unwrap();
|
||||
|
||||
// unset errors when no spec is set.
|
||||
table.disable_memwal().await.unwrap_err();
|
||||
table.disable_rte().await.unwrap_err();
|
||||
|
||||
// Install a spec, then unset it.
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::bucket("id", 4))
|
||||
.enable_rte(RTEWriteSpec::bucket("id", 4))
|
||||
.await
|
||||
.unwrap();
|
||||
{
|
||||
@@ -5776,16 +5767,16 @@ mod tests {
|
||||
assert!(dataset.mem_wal_index_details().await.unwrap().is_some());
|
||||
}
|
||||
|
||||
table.disable_memwal().await.unwrap();
|
||||
table.disable_rte().await.unwrap();
|
||||
{
|
||||
let dataset = table.as_native().unwrap().dataset.get().await.unwrap();
|
||||
assert!(dataset.mem_wal_index_details().await.unwrap().is_none());
|
||||
}
|
||||
|
||||
// A second unset errors; a fresh spec can still be installed afterwards.
|
||||
table.disable_memwal().await.unwrap_err();
|
||||
table.disable_rte().await.unwrap_err();
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::bucket("id", 8))
|
||||
.enable_rte(RTEWriteSpec::bucket("id", 8))
|
||||
.await
|
||||
.unwrap();
|
||||
{
|
||||
@@ -5795,7 +5786,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_get_memwal_spec() {
|
||||
async fn test_get_rte_spec() {
|
||||
let tmp_dir = tempdir().unwrap();
|
||||
let uri = tmp_dir.path().to_str().unwrap();
|
||||
|
||||
@@ -5822,7 +5813,7 @@ mod tests {
|
||||
table.set_unenforced_primary_key(["id"]).await.unwrap();
|
||||
|
||||
// No spec installed yet.
|
||||
assert_eq!(table.get_memwal_spec().await.unwrap(), None);
|
||||
assert_eq!(table.get_rte_spec().await.unwrap(), None);
|
||||
|
||||
// A real scalar index is needed to name it as a maintained index.
|
||||
table
|
||||
@@ -5834,35 +5825,35 @@ mod tests {
|
||||
|
||||
// Bucket spec round-trips exactly, including the routing column (recovered
|
||||
// from its field id), maintained indexes, and writer config defaults.
|
||||
let spec = MemWalWriteSpec::bucket("id", 4)
|
||||
let spec = RTEWriteSpec::bucket("id", 4)
|
||||
.with_maintained_indexes(vec![idx_name.clone()])
|
||||
.with_writer_config_defaults([("durable_write", "false")]);
|
||||
table.enable_memwal(spec.clone()).await.unwrap();
|
||||
assert_eq!(table.get_memwal_spec().await.unwrap(), Some(spec));
|
||||
table.enable_rte(spec.clone()).await.unwrap();
|
||||
assert_eq!(table.get_rte_spec().await.unwrap(), Some(spec));
|
||||
|
||||
// After unset, no spec is reported.
|
||||
table.disable_memwal().await.unwrap();
|
||||
assert_eq!(table.get_memwal_spec().await.unwrap(), None);
|
||||
table.disable_rte().await.unwrap();
|
||||
assert_eq!(table.get_rte_spec().await.unwrap(), None);
|
||||
|
||||
// Identity sharding round-trips (column recovered from the schema).
|
||||
// A spec left at its default round-trips as the default: what is stored
|
||||
// is the intent to maintain everything, not the set it resolves to now.
|
||||
let spec = MemWalWriteSpec::identity("region");
|
||||
table.enable_memwal(spec.clone()).await.unwrap();
|
||||
assert_eq!(table.get_memwal_spec().await.unwrap(), Some(spec));
|
||||
table.disable_memwal().await.unwrap();
|
||||
let spec = RTEWriteSpec::identity("region");
|
||||
table.enable_rte(spec.clone()).await.unwrap();
|
||||
assert_eq!(table.get_rte_spec().await.unwrap(), Some(spec));
|
||||
table.disable_rte().await.unwrap();
|
||||
|
||||
// Unsharded round-trips (no routing column).
|
||||
let spec = MemWalWriteSpec::unsharded();
|
||||
table.enable_memwal(spec.clone()).await.unwrap();
|
||||
assert_eq!(table.get_memwal_spec().await.unwrap(), Some(spec));
|
||||
let spec = RTEWriteSpec::unsharded();
|
||||
table.enable_rte(spec.clone()).await.unwrap();
|
||||
assert_eq!(table.get_rte_spec().await.unwrap(), Some(spec));
|
||||
}
|
||||
|
||||
/// The maintained set defaults to every index on the table. A named index
|
||||
/// the memtable cannot build fails the install, because the caller asked
|
||||
/// for it; an unnamed one is skipped, because it arrived by existing.
|
||||
#[tokio::test]
|
||||
async fn test_enable_memwal_infers_maintained_indexes() {
|
||||
async fn test_enable_rte_infers_maintained_indexes() {
|
||||
let tmp_dir = tempdir().unwrap();
|
||||
let uri = tmp_dir.path().to_str().unwrap();
|
||||
|
||||
@@ -5903,9 +5894,8 @@ mod tests {
|
||||
|
||||
// Explicitly naming the bitmap index fails before anything commits.
|
||||
let err = table
|
||||
.enable_memwal(
|
||||
MemWalWriteSpec::unsharded()
|
||||
.with_maintained_indexes(vec!["tag_bitmap".to_string()]),
|
||||
.enable_rte(
|
||||
RTEWriteSpec::unsharded().with_maintained_indexes(vec!["tag_bitmap".to_string()]),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
@@ -5913,18 +5903,15 @@ mod tests {
|
||||
matches!(err, Error::InvalidInput { ref message } if message.contains("tag_bitmap")),
|
||||
"expected the bitmap index to be rejected, got {err:?}"
|
||||
);
|
||||
assert_eq!(table.get_memwal_spec().await.unwrap(), None);
|
||||
assert_eq!(table.get_rte_spec().await.unwrap(), None);
|
||||
|
||||
// The default names nothing, so the bitmap is skipped rather than
|
||||
// refusing the table: it is maintained by existing, not by being asked
|
||||
// for. The intent is what is stored, not the set it resolves to today.
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded())
|
||||
.await
|
||||
.unwrap();
|
||||
table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap();
|
||||
assert_eq!(
|
||||
table
|
||||
.get_memwal_spec()
|
||||
.get_rte_spec()
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
@@ -5935,16 +5922,16 @@ mod tests {
|
||||
|
||||
// Narrowing to a named subset: unset first, since an installed spec
|
||||
// cannot be set over.
|
||||
table.disable_memwal().await.unwrap();
|
||||
table.disable_rte().await.unwrap();
|
||||
table
|
||||
.enable_memwal(
|
||||
MemWalWriteSpec::unsharded().with_maintained_indexes(vec!["id_btree".to_string()]),
|
||||
.enable_rte(
|
||||
RTEWriteSpec::unsharded().with_maintained_indexes(vec!["id_btree".to_string()]),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
table
|
||||
.get_memwal_spec()
|
||||
.get_rte_spec()
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
@@ -5953,14 +5940,14 @@ mod tests {
|
||||
);
|
||||
|
||||
// Opting out entirely is distinct from the default.
|
||||
table.disable_memwal().await.unwrap();
|
||||
table.disable_rte().await.unwrap();
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded().with_maintained_indexes(Vec::new()))
|
||||
.enable_rte(RTEWriteSpec::unsharded().with_maintained_indexes(Vec::new()))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
table
|
||||
.get_memwal_spec()
|
||||
.get_rte_spec()
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
@@ -5971,7 +5958,7 @@ mod tests {
|
||||
// An installed spec is never set over, whatever the new one asks for,
|
||||
// and the refused call leaves it alone.
|
||||
let err = table
|
||||
.enable_memwal(MemWalWriteSpec::bucket("id", 4))
|
||||
.enable_rte(RTEWriteSpec::bucket("id", 4))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
@@ -5981,7 +5968,7 @@ mod tests {
|
||||
);
|
||||
assert_eq!(
|
||||
table
|
||||
.get_memwal_spec()
|
||||
.get_rte_spec()
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
//! Converging a table's MemWAL write path into its base table.
|
||||
//! Converging a table's RTE write path into its base table.
|
||||
//!
|
||||
//! `checkpoint_memwal` freezes once, then triggers compaction and watches
|
||||
//! `checkpoint_rte` freezes once, then triggers compaction and watches
|
||||
//! generation numbers until the SSTables that existed at the start are gone.
|
||||
//!
|
||||
//! The loop runs in the client, not the server: `compact_memwal` dispatches a
|
||||
//! The loop runs in the client, not the server: `compact_rte` dispatches a
|
||||
//! pass and returns, so nothing holds a socket and a client can vanish
|
||||
//! mid-operation with nothing to reconcile. Completion is read from
|
||||
//! generation numbers in the shard manifest — durable state, unlike a count
|
||||
@@ -68,7 +68,7 @@ fn is_lost_claim(e: &Error) -> bool {
|
||||
status_of(e) == Some(421)
|
||||
}
|
||||
|
||||
/// Interval between `get_memwal_stats` polls. One interval is roughly one
|
||||
/// Interval between `get_rte_stats` polls. One interval is roughly one
|
||||
/// compaction pass, the granularity at which the answer can change.
|
||||
///
|
||||
/// Fixed rather than configurable, matching `wait_for_index`. It costs
|
||||
@@ -149,15 +149,15 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// Drive [`Table::checkpoint_memwal`]: freeze once, fix the target watermark
|
||||
/// Drive [`Table::checkpoint_rte`]: freeze once, fix the target watermark
|
||||
/// from the resulting SSTables, then trigger and poll until they drain.
|
||||
pub(crate) async fn checkpoint_memwal(table: &Table) -> Result<()> {
|
||||
pub(crate) async fn checkpoint_rte(table: &Table) -> Result<()> {
|
||||
for reissue in 0..=MAX_REISSUES {
|
||||
// The freeze turns everything written before this call into an
|
||||
// SSTable, so the watermark has to be read after it. Idempotent:
|
||||
// freezing an empty memtable is a no-op, so a re-issue does not churn
|
||||
// empty SSTables.
|
||||
match issue(|| table.flush_memwal()).await? {
|
||||
match issue(|| table.flush_rte()).await? {
|
||||
Attempt::Ok(()) => {}
|
||||
Attempt::ReissueFromFlush => {
|
||||
backoff(reissue).await;
|
||||
@@ -165,7 +165,7 @@ pub(crate) async fn checkpoint_memwal(table: &Table) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
let stats = match issue(|| table.get_memwal_stats(false)).await? {
|
||||
let stats = match issue(|| table.get_rte_stats(false)).await? {
|
||||
Attempt::Ok(stats) => stats,
|
||||
Attempt::ReissueFromFlush => {
|
||||
backoff(reissue).await;
|
||||
@@ -173,7 +173,7 @@ pub(crate) async fn checkpoint_memwal(table: &Table) -> Result<()> {
|
||||
}
|
||||
};
|
||||
let Some(stats) = stats else {
|
||||
// Not WAL-backed; `flush_memwal` would have errored first but for a race.
|
||||
// Not WAL-backed; `flush_rte` would have errored first but for a race.
|
||||
return Ok(());
|
||||
};
|
||||
let targets: HashMap<String, u64> = stats
|
||||
@@ -194,7 +194,7 @@ pub(crate) async fn checkpoint_memwal(table: &Table) -> Result<()> {
|
||||
}
|
||||
}
|
||||
Err(Error::Runtime {
|
||||
message: "checkpoint_memwal: the owning node kept losing its claim; \
|
||||
message: "checkpoint_rte: the owning node kept losing its claim; \
|
||||
re-issued from flush the maximum number of times"
|
||||
.into(),
|
||||
})
|
||||
@@ -213,7 +213,7 @@ async fn drain_to_targets(
|
||||
targets: &HashMap<String, u64>,
|
||||
) -> Result<CheckpointOutcome> {
|
||||
loop {
|
||||
let stats = match issue(|| table.get_memwal_stats(false)).await? {
|
||||
let stats = match issue(|| table.get_rte_stats(false)).await? {
|
||||
Attempt::Ok(stats) => stats,
|
||||
Attempt::ReissueFromFlush => return Ok(CheckpointOutcome::ReissueFromFlush),
|
||||
};
|
||||
@@ -241,7 +241,7 @@ async fn drain_to_targets(
|
||||
}
|
||||
|
||||
if !all_compacting {
|
||||
match table.compact_memwal().await {
|
||||
match table.compact_rte().await {
|
||||
Ok(()) => {}
|
||||
Err(e) if is_lost_claim(&e) => return Ok(CheckpointOutcome::ReissueFromFlush),
|
||||
Err(e) if !is_retryable(&e) => return Err(e),
|
||||
|
||||
@@ -2197,7 +2197,7 @@ pub(crate) fn plan(schema: SchemaRef, columns: &[(String, String)]) -> Result<Ve
|
||||
/// every declaration. For callers that stage declarations behind other work
|
||||
/// and need those rejections before any of it lands.
|
||||
///
|
||||
/// Only the schema is consulted. Declaring also refuses a table with a MemWAL
|
||||
/// Only the schema is consulted. Declaring also refuses a table with an RTE
|
||||
/// write spec or retained SSTables; that is table state, checked at commit.
|
||||
///
|
||||
/// ```
|
||||
@@ -3025,7 +3025,7 @@ mod tests {
|
||||
/// The gate's reproducer: the reciprocal of the declare-under-spec check.
|
||||
#[tokio::test]
|
||||
async fn test_installing_an_lsm_spec_over_computed_columns_is_refused() {
|
||||
use crate::table::MemWalWriteSpec;
|
||||
use crate::table::RTEWriteSpec;
|
||||
|
||||
let tmp_dir = tempfile::tempdir().unwrap();
|
||||
let conn = connect(tmp_dir.path().to_str().unwrap())
|
||||
@@ -3053,14 +3053,14 @@ mod tests {
|
||||
.unwrap();
|
||||
|
||||
let err = table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded())
|
||||
.enable_rte(RTEWriteSpec::unsharded())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(&err, Error::NotSupported { message } if message.contains("computed")),
|
||||
"{err:?}"
|
||||
);
|
||||
assert!(table.get_memwal_spec().await.unwrap().is_none());
|
||||
assert!(table.get_rte_spec().await.unwrap().is_none());
|
||||
}
|
||||
|
||||
/// The gate's reproducer: declaration metadata is admitted only through
|
||||
@@ -3233,10 +3233,10 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Stale handles must not commit the computed/MemWAL state in either order.
|
||||
/// Stale handles must not commit the computed/RTE state in either order.
|
||||
#[tokio::test]
|
||||
async fn test_stale_handles_cannot_mix_computed_and_lsm() {
|
||||
use crate::table::MemWalWriteSpec;
|
||||
use crate::table::RTEWriteSpec;
|
||||
|
||||
let tmp_dir = tempfile::tempdir().unwrap();
|
||||
let uri = tmp_dir.path().to_str().unwrap();
|
||||
@@ -3260,7 +3260,7 @@ mod tests {
|
||||
.await
|
||||
.unwrap();
|
||||
let err = stale
|
||||
.enable_memwal(MemWalWriteSpec::unsharded())
|
||||
.enable_rte(RTEWriteSpec::unsharded())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, Error::NotSupported { .. }), "install won");
|
||||
@@ -3274,10 +3274,7 @@ mod tests {
|
||||
let table = conn.create_table("mix2", batch).execute().await.unwrap();
|
||||
table.set_unenforced_primary_key(["x"]).await.unwrap();
|
||||
let stale = conn.open_table("mix2").execute().await.unwrap();
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded())
|
||||
.await
|
||||
.unwrap();
|
||||
table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap();
|
||||
let err = add_computed(&stale, &[("doubled".into(), "x * 2".into())])
|
||||
.await
|
||||
.unwrap_err();
|
||||
@@ -3289,7 +3286,7 @@ mod tests {
|
||||
/// flag is the durable marker; declaration refuses on it.
|
||||
#[tokio::test]
|
||||
async fn test_unset_with_retained_lsm_rows_cannot_admit_a_declaration() {
|
||||
use crate::table::MemWalWriteSpec;
|
||||
use crate::table::RTEWriteSpec;
|
||||
use arrow_array::{Int64Array, RecordBatchIterator};
|
||||
|
||||
let tmp_dir = tempfile::tempdir().unwrap();
|
||||
@@ -3315,21 +3312,18 @@ mod tests {
|
||||
.await
|
||||
.unwrap();
|
||||
table.set_unenforced_primary_key(["id"]).await.unwrap();
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded())
|
||||
.await
|
||||
.unwrap();
|
||||
table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap();
|
||||
|
||||
let mut merge = table.merge_insert(&["id"]);
|
||||
merge
|
||||
.when_matched_update_all(None)
|
||||
.when_not_matched_insert_all()
|
||||
.use_memwal(true);
|
||||
.use_rte(true);
|
||||
merge
|
||||
.execute(Box::new(RecordBatchIterator::new(vec![Ok(batch)], schema)))
|
||||
.await
|
||||
.unwrap();
|
||||
table.disable_memwal().await.unwrap();
|
||||
table.disable_rte().await.unwrap();
|
||||
|
||||
let err = add_computed(&table, &[("doubled".into(), "value * 2".into())])
|
||||
.await
|
||||
|
||||
@@ -166,7 +166,7 @@ pub struct BaseTableAdapter {
|
||||
table: Arc<dyn BaseTable>,
|
||||
schema: Arc<ArrowSchema>,
|
||||
fts_query: Option<FullTextSearchQuery>,
|
||||
use_memwal: Option<bool>,
|
||||
use_rte: Option<bool>,
|
||||
}
|
||||
|
||||
impl BaseTableAdapter {
|
||||
@@ -182,13 +182,13 @@ impl BaseTableAdapter {
|
||||
table,
|
||||
schema: Arc::new(schema),
|
||||
fts_query: None,
|
||||
use_memwal: None,
|
||||
use_rte: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Set the MemWAL read routing of every scan; see [`QueryRequest::use_memwal`].
|
||||
pub fn with_use_memwal(mut self, use_memwal: Option<bool>) -> Self {
|
||||
self.use_memwal = use_memwal;
|
||||
/// Set the RTE read routing of every scan; see [`QueryRequest::use_rte`].
|
||||
pub fn with_use_rte(mut self, use_rte: Option<bool>) -> Self {
|
||||
self.use_rte = use_rte;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -204,7 +204,7 @@ impl BaseTableAdapter {
|
||||
table: self.table.clone(),
|
||||
schema,
|
||||
fts_query: Some(fts_query),
|
||||
use_memwal: self.use_memwal,
|
||||
use_rte: self.use_rte,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -232,7 +232,7 @@ impl TableProvider for BaseTableAdapter {
|
||||
let mut query = QueryRequest {
|
||||
full_text_search: self.fts_query.clone(),
|
||||
disable_scoring_autoprojection: disable_scoring,
|
||||
use_memwal: self.use_memwal,
|
||||
use_rte: self.use_rte,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ use crate::{Error, error::Result, utils::background_cache::BackgroundCache};
|
||||
pub struct DatasetConsistencyWrapper {
|
||||
state: Arc<Mutex<DatasetState>>,
|
||||
consistency: ConsistencyMode,
|
||||
/// The single MemWAL `ShardWriter` for this dataset, co-located so it is
|
||||
/// The single RTE `ShardWriter` for this dataset, co-located so it is
|
||||
/// cached for the session and shares the dataset's lifecycle. A dataset
|
||||
/// writes to one shard at a time. Shared by `Arc` across clones.
|
||||
shard_writer: Arc<ShardWriterCache>,
|
||||
@@ -33,7 +33,7 @@ struct DatasetState {
|
||||
/// `None` = tracking latest.
|
||||
pinned_version: Option<u64>,
|
||||
/// Whether the pin is an internal query snapshot rather than user-visible
|
||||
/// time travel. Query snapshots remain read-only but preserve MemWAL read
|
||||
/// time travel. Query snapshots remain read-only but preserve RTE read
|
||||
/// semantics.
|
||||
query_snapshot: bool,
|
||||
}
|
||||
@@ -99,7 +99,7 @@ impl DatasetConsistencyWrapper {
|
||||
}
|
||||
|
||||
/// Create an independent read-only wrapper pinned to the current dataset
|
||||
/// while retaining this wrapper's live MemWAL read context.
|
||||
/// while retaining this wrapper's live RTE read context.
|
||||
pub async fn new_query_snapshot(&self) -> Result<Self> {
|
||||
// Apply the configured consistency policy before taking the snapshot.
|
||||
// The returned dataset is intentionally discarded: a checkout may race
|
||||
@@ -109,7 +109,7 @@ impl DatasetConsistencyWrapper {
|
||||
|
||||
let (dataset, query_snapshot) = {
|
||||
let state = self.state.lock()?;
|
||||
// Preserve user time travel so the MemWAL safety guard still sees
|
||||
// Preserve user time travel so the RTE safety guard still sees
|
||||
// it. Latest and already-internal snapshots remain internal pins.
|
||||
(
|
||||
state.dataset.clone(),
|
||||
@@ -128,7 +128,7 @@ impl DatasetConsistencyWrapper {
|
||||
})
|
||||
}
|
||||
|
||||
/// The MemWAL `ShardWriter` cache co-located with this dataset.
|
||||
/// The RTE `ShardWriter` cache co-located with this dataset.
|
||||
pub(crate) fn shard_writer(&self) -> &Arc<ShardWriterCache> {
|
||||
&self.shard_writer
|
||||
}
|
||||
|
||||
+76
-115
@@ -47,7 +47,7 @@ pub struct MergeResult {
|
||||
/// Total number of rows written.
|
||||
///
|
||||
/// On the standard `merge_insert` path this equals
|
||||
/// `num_inserted_rows + num_updated_rows`. On the MemWAL write path the
|
||||
/// `num_inserted_rows + num_updated_rows`. On the RTE write path the
|
||||
/// insert/update breakdown is not known until compaction; in that mode
|
||||
/// `num_inserted_rows`, `num_updated_rows`, `num_deleted_rows`, `version`
|
||||
/// and `num_attempts` are all `0` and this field holds the total number of
|
||||
@@ -76,7 +76,7 @@ pub struct MergeInsertBuilder {
|
||||
pub(crate) when_not_matched_by_source_delete_filt: Option<MergeFilter>,
|
||||
pub(crate) timeout: Option<Duration>,
|
||||
pub(crate) use_index: bool,
|
||||
pub(crate) use_memwal: Option<bool>,
|
||||
pub(crate) use_rte: Option<bool>,
|
||||
pub(crate) validate_single_shard: bool,
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ impl MergeInsertBuilder {
|
||||
when_not_matched_by_source_delete_filt: None,
|
||||
timeout: None,
|
||||
use_index: true,
|
||||
use_memwal: None,
|
||||
use_rte: None,
|
||||
validate_single_shard: true,
|
||||
}
|
||||
}
|
||||
@@ -190,30 +190,30 @@ impl MergeInsertBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Control MemWAL routing for this `merge_insert`.
|
||||
/// Control RTE routing for this `merge_insert`.
|
||||
///
|
||||
/// By default (unset), a `merge_insert` on a table with an
|
||||
/// [`MemWalWriteSpec`](super::MemWalWriteSpec) installed is routed through Lance's
|
||||
/// MemWAL shard writer; a table without one uses the standard path.
|
||||
/// [`RTEWriteSpec`](super::RTEWriteSpec) installed is routed through Lance's
|
||||
/// RTE shard writer; a table without one uses the standard path.
|
||||
///
|
||||
/// - `use_memwal(true)` forces MemWAL routing and errors if the table has no
|
||||
/// MemWAL write spec.
|
||||
/// - `use_memwal(false)` forces the standard write path even when a spec is set.
|
||||
pub fn use_memwal(&mut self, enable: bool) -> &mut Self {
|
||||
self.use_memwal = Some(enable);
|
||||
/// - `use_rte(true)` forces RTE routing and errors if the table has no
|
||||
/// RTE write spec.
|
||||
/// - `use_rte(false)` forces the standard write path even when a spec is set.
|
||||
pub fn use_rte(&mut self, enable: bool) -> &mut Self {
|
||||
self.use_rte = Some(enable);
|
||||
self
|
||||
}
|
||||
|
||||
/// Controls how an LSM `merge_insert` checks that its input targets a
|
||||
/// single shard.
|
||||
///
|
||||
/// When a table has a MemWAL write spec, every row in a `merge_insert` call
|
||||
/// When a table has an RTE write spec, every row in a `merge_insert` call
|
||||
/// must route to the same shard. When `true` (the default), every row is
|
||||
/// inspected to verify this. When `false`, only the first row is inspected
|
||||
/// and the shard it routes to is used for the whole input — a faster path
|
||||
/// for callers that have already pre-sharded their input.
|
||||
///
|
||||
/// Has no effect on tables without a MemWAL write spec.
|
||||
/// Has no effect on tables without an RTE write spec.
|
||||
pub fn validate_single_shard(&mut self, validate_single_shard: bool) -> &mut Self {
|
||||
self.validate_single_shard = validate_single_shard;
|
||||
self
|
||||
@@ -903,7 +903,7 @@ mod lsm_tests {
|
||||
|
||||
use crate::connect;
|
||||
use crate::error::Error;
|
||||
use crate::table::{MemWalWriteSpec, Table};
|
||||
use crate::table::{RTEWriteSpec, Table};
|
||||
|
||||
/// A reader of `[id: Int64, value: Int64]` rows; `value` is `0..n`.
|
||||
fn id_value_reader(ids: Vec<i64>) -> Box<dyn RecordBatchReader + Send> {
|
||||
@@ -987,7 +987,7 @@ mod lsm_tests {
|
||||
let table = id_value_table(&dir).await;
|
||||
// num_buckets = 1: every row routes to the single bucket.
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::bucket("id", 1))
|
||||
.enable_rte(RTEWriteSpec::bucket("id", 1))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -1001,7 +1001,7 @@ mod lsm_tests {
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// LSM path: rows go to the MemWAL, the breakdown is unknown until
|
||||
// LSM path: rows go to the RTE, the breakdown is unknown until
|
||||
// compaction, so only `num_rows` is populated.
|
||||
assert_eq!(result.num_rows, 3);
|
||||
assert_eq!(result.version, 0);
|
||||
@@ -1013,10 +1013,7 @@ mod lsm_tests {
|
||||
async fn lsm_merge_insert_unsharded() {
|
||||
let dir = tempdir().unwrap();
|
||||
let table = id_value_table(&dir).await;
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded())
|
||||
.await
|
||||
.unwrap();
|
||||
table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap();
|
||||
|
||||
let mut builder = table.merge_insert(&["id"]);
|
||||
builder
|
||||
@@ -1043,7 +1040,7 @@ mod lsm_tests {
|
||||
.unwrap();
|
||||
table.set_unenforced_primary_key(["id"]).await.unwrap();
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::identity("region"))
|
||||
.enable_rte(RTEWriteSpec::identity("region"))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -1060,18 +1057,18 @@ mod lsm_tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn lsm_merge_insert_use_memwal_false_falls_back() {
|
||||
async fn lsm_merge_insert_use_rte_false_falls_back() {
|
||||
let dir = tempdir().unwrap();
|
||||
let table = id_value_table(&dir).await;
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::bucket("id", 1))
|
||||
.enable_rte(RTEWriteSpec::bucket("id", 1))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// use_memwal(false) opts out: the standard path runs and commits even though
|
||||
// use_rte(false) opts out: the standard path runs and commits even though
|
||||
// a spec is installed.
|
||||
let mut builder = table.merge_insert(&["id"]);
|
||||
builder.when_not_matched_insert_all().use_memwal(false);
|
||||
builder.when_not_matched_insert_all().use_rte(false);
|
||||
let result = builder
|
||||
.execute(id_value_reader(vec![3, 4, 5]))
|
||||
.await
|
||||
@@ -1082,17 +1079,17 @@ mod lsm_tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn lsm_merge_insert_use_memwal_true_without_spec_errors() {
|
||||
async fn lsm_merge_insert_use_rte_true_without_spec_errors() {
|
||||
let dir = tempdir().unwrap();
|
||||
let table = id_value_table(&dir).await;
|
||||
|
||||
// use_memwal(true) demands MemWAL routing; without a write spec it errors
|
||||
// use_rte(true) demands RTE routing; without a write spec it errors
|
||||
// rather than silently falling back to the standard path.
|
||||
let mut builder = table.merge_insert(&["id"]);
|
||||
builder
|
||||
.when_matched_update_all(None)
|
||||
.when_not_matched_insert_all()
|
||||
.use_memwal(true);
|
||||
.use_rte(true);
|
||||
let err = builder
|
||||
.execute(id_value_reader(vec![3, 4, 5]))
|
||||
.await
|
||||
@@ -1105,7 +1102,7 @@ mod lsm_tests {
|
||||
let dir = tempdir().unwrap();
|
||||
let table = id_value_table(&dir).await;
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::bucket("id", 1))
|
||||
.enable_rte(RTEWriteSpec::bucket("id", 1))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -1122,7 +1119,7 @@ mod lsm_tests {
|
||||
let dir = tempdir().unwrap();
|
||||
let table = id_value_table(&dir).await;
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::bucket("id", 1))
|
||||
.enable_rte(RTEWriteSpec::bucket("id", 1))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -1138,7 +1135,7 @@ mod lsm_tests {
|
||||
let dir = tempdir().unwrap();
|
||||
let table = id_value_table(&dir).await;
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::bucket("id", 1))
|
||||
.enable_rte(RTEWriteSpec::bucket("id", 1))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -1148,7 +1145,7 @@ mod lsm_tests {
|
||||
.when_not_matched_insert_all();
|
||||
builder.execute(id_value_reader(vec![7, 8])).await.unwrap();
|
||||
|
||||
table.close_memwal_writers().await.unwrap();
|
||||
table.close_rte_writers().await.unwrap();
|
||||
|
||||
// The writer reopens lazily on the next merge_insert.
|
||||
let mut builder = table.merge_insert(&[]);
|
||||
@@ -1173,7 +1170,7 @@ mod lsm_tests {
|
||||
.unwrap();
|
||||
table.set_unenforced_primary_key(["id"]).await.unwrap();
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::identity("region"))
|
||||
.enable_rte(RTEWriteSpec::identity("region"))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -1210,10 +1207,10 @@ mod lsm_tests {
|
||||
#[tokio::test]
|
||||
async fn lsm_merge_insert_no_spec_uses_standard_path() {
|
||||
let dir = tempdir().unwrap();
|
||||
// id_value_table sets a primary key but no MemWAL write spec.
|
||||
// id_value_table sets a primary key but no RTE write spec.
|
||||
let table = id_value_table(&dir).await;
|
||||
|
||||
// Without a spec, a default merge_insert (use_memwal unset) simply uses
|
||||
// Without a spec, a default merge_insert (use_rte unset) simply uses
|
||||
// the standard path and commits — no opt-out required, no error.
|
||||
let mut builder = table.merge_insert(&["id"]);
|
||||
builder
|
||||
@@ -1241,7 +1238,7 @@ mod lsm_tests {
|
||||
.unwrap();
|
||||
table.set_unenforced_primary_key(["id"]).await.unwrap();
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::identity("region"))
|
||||
.enable_rte(RTEWriteSpec::identity("region"))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -1267,7 +1264,7 @@ mod lsm_tests {
|
||||
assert!(matches!(err, Error::InvalidInput { .. }), "got {err:?}");
|
||||
|
||||
// After closing the writer, a different shard can be written.
|
||||
table.close_memwal_writers().await.unwrap();
|
||||
table.close_rte_writers().await.unwrap();
|
||||
let mut builder = table.merge_insert(&[]);
|
||||
builder
|
||||
.when_matched_update_all(None)
|
||||
@@ -1279,7 +1276,7 @@ mod lsm_tests {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// MemWAL read path
|
||||
// RTE read path
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
use crate::arrow::SendableRecordBatchStream;
|
||||
@@ -1337,10 +1334,7 @@ mod lsm_tests {
|
||||
async fn lsm_read_sees_active_memtable() {
|
||||
let dir = tempdir().unwrap();
|
||||
let table = id_value_table(&dir).await; // base: ids 1,2,3 (value 0,1,2)
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded())
|
||||
.await
|
||||
.unwrap();
|
||||
table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap();
|
||||
|
||||
// Insert ids 4,5 into the active memtable (not committed to base).
|
||||
lsm_upsert(&table, vec![4, 5]).await;
|
||||
@@ -1353,8 +1347,8 @@ mod lsm_tests {
|
||||
vec![1, 2, 3, 4, 5]
|
||||
);
|
||||
|
||||
// use_memwal(false) bypasses the MemWAL and reads the base table only.
|
||||
let base_only = table.query().use_memwal(false).execute().await.unwrap();
|
||||
// use_rte(false) bypasses the RTE and reads the base table only.
|
||||
let base_only = table.query().use_rte(false).execute().await.unwrap();
|
||||
let rows = collect_id_value(base_only).await;
|
||||
assert_eq!(
|
||||
rows.iter().map(|(id, _)| *id).collect::<Vec<_>>(),
|
||||
@@ -1363,23 +1357,20 @@ mod lsm_tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn base_table_adapter_use_memwal_false_scans_the_base_only() {
|
||||
async fn base_table_adapter_use_rte_false_scans_the_base_only() {
|
||||
use crate::table::datafusion::BaseTableAdapter;
|
||||
use datafusion::prelude::SessionContext;
|
||||
|
||||
let dir = tempdir().unwrap();
|
||||
let table = id_value_table(&dir).await; // base: ids 1,2,3
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded())
|
||||
.await
|
||||
.unwrap();
|
||||
table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap();
|
||||
// Ids 4,5 land in the active memtable, not the base table.
|
||||
lsm_upsert(&table, vec![4, 5]).await;
|
||||
|
||||
let adapter = BaseTableAdapter::try_new(table.base_table().clone())
|
||||
.await
|
||||
.unwrap()
|
||||
.with_use_memwal(Some(false));
|
||||
.with_use_rte(Some(false));
|
||||
let ctx = SessionContext::new();
|
||||
ctx.register_table("base_only", Arc::new(adapter)).unwrap();
|
||||
let batches = ctx
|
||||
@@ -1401,10 +1392,7 @@ mod lsm_tests {
|
||||
async fn query_snapshot_preserves_lsm_read_semantics() {
|
||||
let dir = tempdir().unwrap();
|
||||
let table = id_value_table(&dir).await;
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded())
|
||||
.await
|
||||
.unwrap();
|
||||
table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap();
|
||||
lsm_upsert(&table, vec![4, 5]).await;
|
||||
|
||||
let snapshot = table.query_snapshot().await.unwrap();
|
||||
@@ -1419,10 +1407,7 @@ mod lsm_tests {
|
||||
async fn query_snapshot_preserves_time_travel_lsm_guard() {
|
||||
let dir = tempdir().unwrap();
|
||||
let table = id_value_table(&dir).await;
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded())
|
||||
.await
|
||||
.unwrap();
|
||||
table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap();
|
||||
lsm_upsert(&table, vec![4]).await;
|
||||
|
||||
let version = table.version().await.unwrap();
|
||||
@@ -1439,10 +1424,7 @@ mod lsm_tests {
|
||||
async fn lsm_read_dedup_newest_wins() {
|
||||
let dir = tempdir().unwrap();
|
||||
let table = id_value_table(&dir).await; // base: id 2 -> value 1
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded())
|
||||
.await
|
||||
.unwrap();
|
||||
table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap();
|
||||
|
||||
// Upsert ids 2,3,4 with values 0,1,2. id 2 and 3 shadow the base rows.
|
||||
lsm_upsert(&table, vec![2, 3, 4]).await;
|
||||
@@ -1457,10 +1439,7 @@ mod lsm_tests {
|
||||
async fn lsm_read_point_lookup_filter() {
|
||||
let dir = tempdir().unwrap();
|
||||
let table = id_value_table(&dir).await;
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded())
|
||||
.await
|
||||
.unwrap();
|
||||
table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap();
|
||||
lsm_upsert(&table, vec![2, 3, 4]).await; // id 2 -> value 0 (shadows base)
|
||||
|
||||
let lsm = table.query().only_if("id = 2").execute().await.unwrap();
|
||||
@@ -1473,14 +1452,14 @@ mod lsm_tests {
|
||||
let dir = tempdir().unwrap();
|
||||
let table = id_value_table(&dir).await;
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::bucket("id", 8))
|
||||
.enable_rte(RTEWriteSpec::bucket("id", 8))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Two single-row upserts that route to (likely) different shards; each
|
||||
// closes the writer so the next opens a fresh shard.
|
||||
lsm_upsert(&table, vec![10]).await;
|
||||
table.close_memwal_writers().await.unwrap();
|
||||
table.close_rte_writers().await.unwrap();
|
||||
lsm_upsert(&table, vec![11]).await;
|
||||
|
||||
let lsm = table.query().execute().await.unwrap();
|
||||
@@ -1494,15 +1473,12 @@ mod lsm_tests {
|
||||
async fn lsm_read_after_close_sees_flushed() {
|
||||
let dir = tempdir().unwrap();
|
||||
let table = id_value_table(&dir).await;
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded())
|
||||
.await
|
||||
.unwrap();
|
||||
table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap();
|
||||
lsm_upsert(&table, vec![4, 5]).await;
|
||||
// close flushes the active memtable to an on-disk generation and drops
|
||||
// the cached writer; the read must still see those rows via the shard
|
||||
// manifest snapshot.
|
||||
table.close_memwal_writers().await.unwrap();
|
||||
table.close_rte_writers().await.unwrap();
|
||||
|
||||
let lsm = table.query().execute().await.unwrap();
|
||||
let ids: Vec<i64> = collect_id_value(lsm)
|
||||
@@ -1516,11 +1492,11 @@ mod lsm_tests {
|
||||
#[tokio::test]
|
||||
async fn lsm_read_without_spec_reads_base() {
|
||||
let dir = tempdir().unwrap();
|
||||
let table = id_value_table(&dir).await; // no MemWAL write spec
|
||||
let table = id_value_table(&dir).await; // no RTE write spec
|
||||
|
||||
// With no spec installed there is nothing to route: the default read and
|
||||
// an explicit use_memwal(false) both read the base table without error.
|
||||
for query in [table.query(), table.query().use_memwal(false)] {
|
||||
// an explicit use_rte(false) both read the base table without error.
|
||||
for query in [table.query(), table.query().use_rte(false)] {
|
||||
let rows = collect_id_value(query.execute().await.unwrap()).await;
|
||||
assert_eq!(
|
||||
rows.iter().map(|(id, _)| *id).collect::<Vec<_>>(),
|
||||
@@ -1530,16 +1506,13 @@ mod lsm_tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn lsm_read_unsupported_shape_errors_without_use_memwal_false() {
|
||||
async fn lsm_read_unsupported_shape_errors_without_use_rte_false() {
|
||||
let dir = tempdir().unwrap();
|
||||
let table = id_value_table(&dir).await;
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded())
|
||||
.await
|
||||
.unwrap();
|
||||
table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap();
|
||||
lsm_upsert(&table, vec![4]).await;
|
||||
|
||||
// `with_row_id` is a shape the LSM scanner cannot honor. On a MemWAL
|
||||
// `with_row_id` is a shape the LSM scanner cannot honor. On an RTE
|
||||
// table the default (auto-routed) read hard-errors rather than silently
|
||||
// reading a stale base-only result that would exclude un-compacted row 4.
|
||||
let err = table
|
||||
@@ -1548,15 +1521,15 @@ mod lsm_tests {
|
||||
.execute()
|
||||
.await
|
||||
.err()
|
||||
.expect("unsupported shape on a MemWAL table must error");
|
||||
.expect("unsupported shape on an RTE table must error");
|
||||
assert!(matches!(err, Error::NotSupported { .. }), "got {err:?}");
|
||||
|
||||
// use_memwal(false) is the escape hatch: it reads the base table only.
|
||||
// use_rte(false) is the escape hatch: it reads the base table only.
|
||||
let rows = collect_id_value(
|
||||
table
|
||||
.query()
|
||||
.with_row_id()
|
||||
.use_memwal(false)
|
||||
.use_rte(false)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap(),
|
||||
@@ -1568,7 +1541,7 @@ mod lsm_tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// A table with `id`/`text` and a primary key, ready for a MemWAL write spec.
|
||||
/// A table with `id`/`text` and a primary key, ready for an RTE write spec.
|
||||
async fn lsm_text_table(dir: &tempfile::TempDir) -> crate::Table {
|
||||
let conn = connect(dir.path().to_str().unwrap())
|
||||
.execute()
|
||||
@@ -1583,7 +1556,7 @@ mod lsm_tests {
|
||||
table
|
||||
}
|
||||
|
||||
/// Upsert `rows` through the MemWAL write path.
|
||||
/// Upsert `rows` through the RTE write path.
|
||||
async fn upsert_text(table: &crate::Table, rows: Vec<(i64, &str)>) {
|
||||
let mut builder = table.merge_insert(&[]);
|
||||
builder
|
||||
@@ -1626,10 +1599,7 @@ mod lsm_tests {
|
||||
let dir = tempdir().unwrap();
|
||||
let table = lsm_text_table(&dir).await;
|
||||
// The default set, on a table with no FTS index yet.
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded())
|
||||
.await
|
||||
.unwrap();
|
||||
table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap();
|
||||
|
||||
// Opens the writer, whose MemTable carries no FTS index.
|
||||
upsert_text(&table, vec![(99, "zebra")]).await;
|
||||
@@ -1661,7 +1631,7 @@ mod lsm_tests {
|
||||
|
||||
/// A spec is replaced by unsetting it and setting the new one.
|
||||
///
|
||||
/// `disable_memwal` drains the open writer, so the rows it held
|
||||
/// `disable_rte` drains the open writer, so the rows it held
|
||||
/// survive the replacement, and the writer the next write opens builds its
|
||||
/// MemTables from the new set.
|
||||
#[tokio::test]
|
||||
@@ -1681,25 +1651,23 @@ mod lsm_tests {
|
||||
// Installed maintaining nothing, then written to: the writer opens with
|
||||
// no FTS index.
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded().with_maintained_indexes(Vec::new()))
|
||||
.enable_rte(RTEWriteSpec::unsharded().with_maintained_indexes(Vec::new()))
|
||||
.await
|
||||
.unwrap();
|
||||
upsert_text(&table, vec![(99, "zebra")]).await;
|
||||
|
||||
// Setting over an installed spec is refused; unset, then set.
|
||||
let err = table
|
||||
.enable_memwal(
|
||||
MemWalWriteSpec::unsharded().with_maintained_indexes(vec![fts_index.clone()]),
|
||||
)
|
||||
.enable_rte(RTEWriteSpec::unsharded().with_maintained_indexes(vec![fts_index.clone()]))
|
||||
.await
|
||||
.expect_err("an installed spec cannot be set over");
|
||||
assert!(
|
||||
err.to_string().contains("already set"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
table.disable_memwal().await.unwrap();
|
||||
table.disable_rte().await.unwrap();
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded().with_maintained_indexes(vec![fts_index]))
|
||||
.enable_rte(RTEWriteSpec::unsharded().with_maintained_indexes(vec![fts_index]))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -1739,10 +1707,7 @@ mod lsm_tests {
|
||||
let dir = tempdir().unwrap();
|
||||
let table = lsm_text_table(&dir).await;
|
||||
// No index yet, and the default set: maintain whatever the table has.
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded())
|
||||
.await
|
||||
.unwrap();
|
||||
table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap();
|
||||
|
||||
// Opens the writer, whose MemTable therefore carries no FTS index.
|
||||
upsert_text(&table, vec![(99, "zebra")]).await;
|
||||
@@ -1796,7 +1761,7 @@ mod lsm_tests {
|
||||
.unwrap();
|
||||
let fts_index = table.list_indices().await.unwrap()[0].name.clone();
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded().with_maintained_indexes(vec![fts_index]))
|
||||
.enable_rte(RTEWriteSpec::unsharded().with_maintained_indexes(vec![fts_index]))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -1891,7 +1856,7 @@ mod lsm_tests {
|
||||
}
|
||||
let vec_index = table.list_indices().await.unwrap()[0].name.clone();
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded().with_maintained_indexes(vec![vec_index]))
|
||||
.enable_rte(RTEWriteSpec::unsharded().with_maintained_indexes(vec![vec_index]))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -2163,11 +2128,10 @@ mod lsm_tests {
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
let spec = || {
|
||||
MemWalWriteSpec::unsharded().with_maintained_indexes(vec!["region_bitmap".to_string()])
|
||||
};
|
||||
let spec =
|
||||
|| RTEWriteSpec::unsharded().with_maintained_indexes(vec!["region_bitmap".to_string()]);
|
||||
|
||||
let refused = table.enable_memwal(spec()).await.unwrap_err();
|
||||
let refused = table.enable_rte(spec()).await.unwrap_err();
|
||||
assert!(
|
||||
refused.to_string().contains("region_bitmap")
|
||||
&& refused
|
||||
@@ -2180,7 +2144,7 @@ mod lsm_tests {
|
||||
.with_plugin(Arc::new(BitmapAsBTree))
|
||||
.unwrap();
|
||||
table.as_native().unwrap().set_mem_index_registry(registry);
|
||||
table.enable_memwal(spec()).await.unwrap();
|
||||
table.enable_rte(spec()).await.unwrap();
|
||||
|
||||
// The registry is not stored with the table.
|
||||
let other = conn.open_table("t").execute().await.unwrap();
|
||||
@@ -2238,7 +2202,7 @@ mod lsm_tests {
|
||||
active.index_store.index_names()
|
||||
);
|
||||
|
||||
table.close_memwal_writers().await.unwrap();
|
||||
table.close_rte_writers().await.unwrap();
|
||||
assert_eq!(fresh().await, vec![10, 11]);
|
||||
assert_sstables_answer_through_region_bitmap(&table, vec![10, 11]).await;
|
||||
}
|
||||
@@ -2345,10 +2309,7 @@ mod lsm_tests {
|
||||
.is_some(),
|
||||
"a clone shares the handle's registry"
|
||||
);
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded())
|
||||
.await
|
||||
.unwrap();
|
||||
table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap();
|
||||
|
||||
let upsert = |rows: Vec<(i64, &'static str)>| {
|
||||
let table = table.clone();
|
||||
@@ -2389,7 +2350,7 @@ mod lsm_tests {
|
||||
active.index_store.index_names()
|
||||
);
|
||||
|
||||
table.close_memwal_writers().await.unwrap();
|
||||
table.close_rte_writers().await.unwrap();
|
||||
// Only the SSTable written after the index exists carries it.
|
||||
let sstables = published_sstables(&table).await;
|
||||
let mut carrying = 0;
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
//! MemWAL write path for `merge_insert`.
|
||||
//! RTE write path for `merge_insert`.
|
||||
//!
|
||||
//! [`enable_memwal`] installs an [`MemWalWriteSpec`] on a table by creating
|
||||
//! Lance's MemWAL index; [`disable_memwal`] removes it. Once a spec is
|
||||
//! [`enable_rte`] installs an [`RTEWriteSpec`] on a table by creating
|
||||
//! Lance's MemWAL index; [`disable_rte`] removes it. Once a spec is
|
||||
//! installed, `merge_insert` upsert calls are dispatched through Lance's MemWAL
|
||||
//! `ShardWriter` (LSM-style append) instead of the standard merge path — see
|
||||
//! [`lsm_dispatch_decision`] and [`execute_lsm_merge_insert`].
|
||||
@@ -14,7 +14,7 @@
|
||||
//! unsharded). [`MergeInsertBuilder::validate_single_shard`] controls whether
|
||||
//! every row is checked or only the first. A dataset writes to one shard at a
|
||||
//! time; its writer is cached in the [`ShardWriterCache`] held alongside the
|
||||
//! dataset, and [`close_memwal_writers`] closes it.
|
||||
//! dataset, and [`close_rte_writers`] closes it.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -42,9 +42,9 @@ use uuid::Uuid;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::index::IndexConfig;
|
||||
use crate::table::merge::{MergeInsertBuilder, MergeResult};
|
||||
use crate::table::{BaseTable, MemWalWriteSpec, NativeTable};
|
||||
use crate::table::{BaseTable, NativeTable, RTEWriteSpec};
|
||||
|
||||
/// Spec id of the sole sharding spec installed by [`enable_memwal`].
|
||||
/// Spec id of the sole sharding spec installed by [`enable_rte`].
|
||||
/// Must match Lance's `InitializeMemWalBuilder` (`SHARDING_SPEC_ID`).
|
||||
const SHARDING_SPEC_ID: u32 = 1;
|
||||
|
||||
@@ -63,23 +63,23 @@ const NUM_BUCKETS_PARAM: &str = "num_buckets";
|
||||
const SHARD_NAMESPACE: Uuid = Uuid::from_u128(0x4c53_4d57_5249_5445_5f53_4841_5244_3031);
|
||||
|
||||
// =============================================================================
|
||||
// enable_memwal
|
||||
// enable_rte
|
||||
// =============================================================================
|
||||
|
||||
/// Install an [`MemWalWriteSpec`] on the table.
|
||||
/// Install an [`RTEWriteSpec`] on the table.
|
||||
///
|
||||
/// The bucket / identity / unsharded sharding spec is constructed and validated
|
||||
/// by Lance's
|
||||
/// [`InitializeMemWalBuilder`](lance::dataset::mem_wal::InitializeMemWalBuilder).
|
||||
#[allow(clippy::redundant_pub_crate)]
|
||||
pub(crate) async fn enable_memwal(table: &NativeTable, spec: MemWalWriteSpec) -> Result<()> {
|
||||
pub(crate) async fn enable_rte(table: &NativeTable, spec: RTEWriteSpec) -> Result<()> {
|
||||
table.dataset.ensure_mutable()?;
|
||||
|
||||
{
|
||||
let dataset = table.dataset.get().await?;
|
||||
if dataset.mem_wal_index_details().await?.is_some() {
|
||||
return Err(Error::InvalidInput {
|
||||
message: "enable_memwal: a MemWAL write spec is already set on this \
|
||||
message: "enable_rte: an RTE write spec is already set on this \
|
||||
table and cannot be changed"
|
||||
.into(),
|
||||
});
|
||||
@@ -117,25 +117,25 @@ pub(crate) async fn enable_memwal(table: &NativeTable, spec: MemWalWriteSpec) ->
|
||||
let schema = arrow_schema::Schema::from(dataset.schema());
|
||||
if !crate::table::computed_columns::computed_columns(&schema).is_empty() {
|
||||
return Err(Error::NotSupported {
|
||||
message: "a MemWAL write spec cannot be installed on a table with computed \
|
||||
message: "an RTE write spec cannot be installed on a table with computed \
|
||||
columns: rows in un-compacted tiers are invisible to refresh"
|
||||
.into(),
|
||||
});
|
||||
}
|
||||
if crate::materialized_view::read_definition(&dataset.schema().metadata)?.is_some() {
|
||||
return Err(Error::NotSupported {
|
||||
message: "a MemWAL write spec cannot be installed on a materialized view: \
|
||||
message: "an RTE write spec cannot be installed on a materialized view: \
|
||||
rows in un-compacted tiers are invisible to refresh"
|
||||
.into(),
|
||||
});
|
||||
}
|
||||
// Every MemWAL write and read resolves rows by the unenforced primary key,
|
||||
// Every RTE write and read resolves rows by the unenforced primary key,
|
||||
// so a spec on a table without one leaves the table unwritable through the
|
||||
// MemWAL path. A key cannot be removed once set, and an overwrite or restore
|
||||
// RTE path. A key cannot be removed once set, and an overwrite or restore
|
||||
// of the table conflicts with the commit below.
|
||||
if dataset.schema().unenforced_primary_key().is_empty() {
|
||||
return Err(Error::InvalidInput {
|
||||
message: "a MemWAL write spec requires the table to declare an unenforced \
|
||||
message: "an RTE write spec requires the table to declare an unenforced \
|
||||
primary key; set one with set_unenforced_primary_key first"
|
||||
.into(),
|
||||
});
|
||||
@@ -144,7 +144,7 @@ pub(crate) async fn enable_memwal(table: &NativeTable, spec: MemWalWriteSpec) ->
|
||||
.initialize_mem_wal()
|
||||
.mem_index_registry(table.mem_index_registry());
|
||||
let writer_config_defaults = match spec {
|
||||
MemWalWriteSpec::Bucket {
|
||||
RTEWriteSpec::Bucket {
|
||||
column,
|
||||
num_buckets,
|
||||
writer_config_defaults,
|
||||
@@ -153,7 +153,7 @@ pub(crate) async fn enable_memwal(table: &NativeTable, spec: MemWalWriteSpec) ->
|
||||
builder = builder.bucket_sharding(column, num_buckets);
|
||||
writer_config_defaults
|
||||
}
|
||||
MemWalWriteSpec::Identity {
|
||||
RTEWriteSpec::Identity {
|
||||
column,
|
||||
writer_config_defaults,
|
||||
..
|
||||
@@ -161,7 +161,7 @@ pub(crate) async fn enable_memwal(table: &NativeTable, spec: MemWalWriteSpec) ->
|
||||
builder = builder.identity_sharding(column);
|
||||
writer_config_defaults
|
||||
}
|
||||
MemWalWriteSpec::Unsharded {
|
||||
RTEWriteSpec::Unsharded {
|
||||
writer_config_defaults,
|
||||
..
|
||||
} => {
|
||||
@@ -191,22 +191,22 @@ fn index_name_list(indices: &[IndexConfig]) -> String {
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// disable_memwal
|
||||
// disable_rte
|
||||
// =============================================================================
|
||||
|
||||
/// Remove the [`MemWalWriteSpec`] from the table by dropping the MemWAL index.
|
||||
/// Remove the [`RTEWriteSpec`] from the table by dropping the MemWAL index.
|
||||
///
|
||||
/// Any cached shard writers are drained and closed first. Errors if no spec is
|
||||
/// currently set.
|
||||
#[allow(clippy::redundant_pub_crate)]
|
||||
pub(crate) async fn disable_memwal(table: &NativeTable) -> Result<()> {
|
||||
pub(crate) async fn disable_rte(table: &NativeTable) -> Result<()> {
|
||||
table.dataset.ensure_mutable()?;
|
||||
|
||||
{
|
||||
let dataset = table.dataset.get().await?;
|
||||
if dataset.mem_wal_index_details().await?.is_none() {
|
||||
return Err(Error::InvalidInput {
|
||||
message: "disable_memwal: no MemWAL write spec is set on this table".into(),
|
||||
message: "disable_rte: no RTE write spec is set on this table".into(),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -222,46 +222,46 @@ pub(crate) async fn disable_memwal(table: &NativeTable) -> Result<()> {
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// get_memwal_spec
|
||||
// get_rte_spec
|
||||
// =============================================================================
|
||||
|
||||
/// Read the [`MemWalWriteSpec`] currently installed on the table, if any.
|
||||
/// Read the [`RTEWriteSpec`] currently installed on the table, if any.
|
||||
///
|
||||
/// Reconstructs the spec from the MemWAL index's stored details — the same
|
||||
/// metadata [`enable_memwal`] writes — read directly via
|
||||
/// metadata [`enable_rte`] writes — read directly via
|
||||
/// [`mem_wal_index_details`](DatasetMemWalExt::mem_wal_index_details) (the raw
|
||||
/// manifest record, not the `describe_indices` enrichment path, so it is
|
||||
/// unaffected by system-index filtering there). Returns `Ok(None)` when no
|
||||
/// MemWAL index is installed.
|
||||
#[allow(clippy::redundant_pub_crate)]
|
||||
pub(crate) async fn get_memwal_spec(table: &NativeTable) -> Result<Option<MemWalWriteSpec>> {
|
||||
pub(crate) async fn get_rte_spec(table: &NativeTable) -> Result<Option<RTEWriteSpec>> {
|
||||
let dataset = table.dataset.get().await?;
|
||||
let Some(details) = dataset.mem_wal_index_details().await? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let spec = memwal_spec_from_details(&details, dataset.schema())?;
|
||||
let spec = rte_spec_from_details(&details, dataset.schema())?;
|
||||
Ok(Some(spec))
|
||||
}
|
||||
|
||||
/// Reconstruct the public [`MemWalWriteSpec`] from stored MemWAL index details.
|
||||
/// Reconstruct the public [`RTEWriteSpec`] from stored MemWAL index details.
|
||||
///
|
||||
/// The sharding transform and its parameters recover the mode; the routing
|
||||
/// column is resolved from the sharding field's source id back to its schema
|
||||
/// name (only bucket / identity carry a column). `maintained_indexes` and
|
||||
/// `writer_config_defaults` are copied verbatim, so the result round-trips
|
||||
/// what `enable_memwal` installed.
|
||||
fn memwal_spec_from_details(
|
||||
/// what `enable_rte` installed.
|
||||
fn rte_spec_from_details(
|
||||
details: &MemWalIndexDetails,
|
||||
schema: &LanceSchema,
|
||||
) -> Result<MemWalWriteSpec> {
|
||||
) -> Result<RTEWriteSpec> {
|
||||
let spec = details
|
||||
.sharding_specs
|
||||
.first()
|
||||
.ok_or_else(|| Error::Runtime {
|
||||
message: "get_memwal_spec: MemWAL index has no sharding spec".to_string(),
|
||||
message: "get_rte_spec: MemWAL index has no sharding spec".to_string(),
|
||||
})?;
|
||||
let field = spec.fields.first().ok_or_else(|| Error::Runtime {
|
||||
message: "get_memwal_spec: MemWAL index has an empty sharding spec".to_string(),
|
||||
message: "get_rte_spec: MemWAL index has an empty sharding spec".to_string(),
|
||||
})?;
|
||||
|
||||
let base = match field.transform.as_deref() {
|
||||
@@ -272,16 +272,16 @@ fn memwal_spec_from_details(
|
||||
.and_then(|s| s.parse::<u32>().ok())
|
||||
.filter(|n| *n > 0)
|
||||
.ok_or_else(|| Error::Runtime {
|
||||
message: "get_memwal_spec: MemWAL bucket spec has a missing or invalid num_buckets parameter".to_string(),
|
||||
message: "get_rte_spec: RTE bucket spec has a missing or invalid num_buckets parameter".to_string(),
|
||||
})?;
|
||||
MemWalWriteSpec::bucket(sharding_column(field, schema)?, num_buckets)
|
||||
RTEWriteSpec::bucket(sharding_column(field, schema)?, num_buckets)
|
||||
}
|
||||
Some(IDENTITY_TRANSFORM) => MemWalWriteSpec::identity(sharding_column(field, schema)?),
|
||||
Some(UNSHARDED_TRANSFORM) => MemWalWriteSpec::unsharded(),
|
||||
Some(IDENTITY_TRANSFORM) => RTEWriteSpec::identity(sharding_column(field, schema)?),
|
||||
Some(UNSHARDED_TRANSFORM) => RTEWriteSpec::unsharded(),
|
||||
other => {
|
||||
return Err(Error::Runtime {
|
||||
message: format!(
|
||||
"get_memwal_spec: MemWAL index has an unsupported sharding transform {:?}",
|
||||
"get_rte_spec: MemWAL index has an unsupported sharding transform {:?}",
|
||||
other
|
||||
),
|
||||
});
|
||||
@@ -297,30 +297,30 @@ fn memwal_spec_from_details(
|
||||
|
||||
/// Resolve the single routing column name from a sharding field's source id.
|
||||
///
|
||||
/// `enable_memwal` records the shard column by its Lance field id, so the
|
||||
/// `enable_rte` records the shard column by its Lance field id, so the
|
||||
/// name is recovered by looking that id up in the current schema.
|
||||
fn sharding_column(field: &ShardingField, schema: &LanceSchema) -> Result<String> {
|
||||
let source_id = *field.source_ids.first().ok_or_else(|| Error::Runtime {
|
||||
message: "get_memwal_spec: sharding field has no source column".to_string(),
|
||||
message: "get_rte_spec: sharding field has no source column".to_string(),
|
||||
})?;
|
||||
schema
|
||||
.field_by_id(source_id)
|
||||
.map(|f| f.name.clone())
|
||||
.ok_or_else(|| Error::Runtime {
|
||||
message: format!(
|
||||
"get_memwal_spec: sharding source field id {} not found in schema",
|
||||
"get_rte_spec: sharding source field id {} not found in schema",
|
||||
source_id
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// close_memwal_writers
|
||||
// close_rte_writers
|
||||
// =============================================================================
|
||||
|
||||
/// Drain and close every cached MemWAL shard writer for the table.
|
||||
/// Drain and close every cached RTE shard writer for the table.
|
||||
#[allow(clippy::redundant_pub_crate)]
|
||||
pub(crate) async fn close_memwal_writers(table: &NativeTable) -> Result<()> {
|
||||
pub(crate) async fn close_rte_writers(table: &NativeTable) -> Result<()> {
|
||||
table.dataset.shard_writer().drain_and_close().await
|
||||
}
|
||||
|
||||
@@ -328,13 +328,13 @@ pub(crate) async fn close_memwal_writers(table: &NativeTable) -> Result<()> {
|
||||
// ShardWriter cache
|
||||
// =============================================================================
|
||||
|
||||
/// Per-table cache holding the single open MemWAL `ShardWriter`.
|
||||
/// Per-table cache holding the single open RTE `ShardWriter`.
|
||||
///
|
||||
/// Held by [`DatasetConsistencyWrapper`](crate::table::dataset::DatasetConsistencyWrapper)
|
||||
/// so the writer lives where the dataset lives — cached for the session and
|
||||
/// reused across `merge_insert` calls. A dataset writes to one shard at a
|
||||
/// time; routing a `merge_insert` to a different shard requires closing the
|
||||
/// current writer first via [`close_memwal_writers`]. `ShardWriter::put` takes
|
||||
/// current writer first via [`close_rte_writers`]. `ShardWriter::put` takes
|
||||
/// `&self`, so concurrent puts on the cached writer are safe; `close` consumes
|
||||
/// the writer, so the entry wraps it in `RwLock<Option<ShardWriter>>`.
|
||||
#[derive(Default)]
|
||||
@@ -384,7 +384,7 @@ impl ShardWriterEntry {
|
||||
|
||||
/// The cached writer's latest in-memory manifest (current generation +
|
||||
/// SSTables). `Ok(None)` if the writer was already closed.
|
||||
/// Used by the MemWAL read path to snapshot this shard authoritatively
|
||||
/// Used by the RTE read path to snapshot this shard authoritatively
|
||||
/// without re-reading the on-disk manifest.
|
||||
async fn manifest(&self) -> Result<Option<lance_index::mem_wal::ShardManifest>> {
|
||||
let guard = self.inner.read().await;
|
||||
@@ -444,7 +444,7 @@ impl ShardWriterCache {
|
||||
.await
|
||||
.map_err(|e| Error::Runtime {
|
||||
message: format!(
|
||||
"merge_insert: failed to open MemWAL shard writer for shard {}: {}",
|
||||
"merge_insert: failed to open RTE shard writer for shard {}: {}",
|
||||
shard_id, e
|
||||
),
|
||||
})?;
|
||||
@@ -502,7 +502,7 @@ impl ShardWriterCache {
|
||||
}
|
||||
}
|
||||
|
||||
/// Snapshot the cached writer's shard for the MemWAL read path: its shard id,
|
||||
/// Snapshot the cached writer's shard for the RTE read path: its shard id,
|
||||
/// authoritative in-memory manifest, and active + frozen memtable refs.
|
||||
/// Returns `None` when no writer is currently cached (e.g. nothing has been
|
||||
/// written this session, or the writer was closed).
|
||||
@@ -550,7 +550,7 @@ fn check_shard_match(cached: Uuid, wanted: Uuid) -> Result<()> {
|
||||
}
|
||||
Err(Error::InvalidInput {
|
||||
message: format!(
|
||||
"merge_insert: a shard writer is already open for shard {} but this input routes to shard {}; call close_memwal_writers before writing to a different shard",
|
||||
"merge_insert: a shard writer is already open for shard {} but this input routes to shard {}; call close_rte_writers before writing to a different shard",
|
||||
cached, wanted
|
||||
),
|
||||
})
|
||||
@@ -571,7 +571,7 @@ enum LsmMode {
|
||||
Unsharded,
|
||||
}
|
||||
|
||||
/// Resolved plan for routing a `merge_insert` through the MemWAL write path.
|
||||
/// Resolved plan for routing a `merge_insert` through the RTE write path.
|
||||
#[derive(Debug)]
|
||||
#[allow(clippy::redundant_pub_crate)]
|
||||
pub(crate) struct LsmPlan {
|
||||
@@ -582,13 +582,13 @@ pub(crate) struct LsmPlan {
|
||||
/// Outcome of [`lsm_dispatch_decision`].
|
||||
#[allow(clippy::redundant_pub_crate)]
|
||||
pub(crate) enum LsmDispatch {
|
||||
/// No MemWAL write spec applies; use the standard `merge_insert` path.
|
||||
/// No RTE write spec applies; use the standard `merge_insert` path.
|
||||
Standard,
|
||||
/// Route the `merge_insert` through the MemWAL shard writer.
|
||||
/// Route the `merge_insert` through the RTE shard writer.
|
||||
Lsm(LsmPlan),
|
||||
}
|
||||
|
||||
/// Decide whether a `merge_insert` should be routed through the MemWAL write
|
||||
/// Decide whether a `merge_insert` should be routed through the RTE write
|
||||
/// path, validating the builder against the installed spec.
|
||||
#[allow(clippy::redundant_pub_crate)]
|
||||
pub(crate) async fn lsm_dispatch_decision(
|
||||
@@ -596,18 +596,18 @@ pub(crate) async fn lsm_dispatch_decision(
|
||||
params: &MergeInsertBuilder,
|
||||
) -> Result<LsmDispatch> {
|
||||
// Explicit opt-out: use the standard path regardless of any installed spec.
|
||||
if params.use_memwal == Some(false) {
|
||||
if params.use_rte == Some(false) {
|
||||
return Ok(LsmDispatch::Standard);
|
||||
}
|
||||
|
||||
let dataset = table.dataset.get().await?;
|
||||
let Some(details) = dataset.mem_wal_index_details().await? else {
|
||||
// No write spec installed. `use_memwal(true)` demanded MemWAL routing, so
|
||||
// No write spec installed. `use_rte(true)` demanded RTE routing, so
|
||||
// that is an error; otherwise fall back to the standard path.
|
||||
if params.use_memwal == Some(true) {
|
||||
if params.use_rte == Some(true) {
|
||||
return Err(Error::InvalidInput {
|
||||
message: "use_memwal(true) was set but the table has no MemWAL write spec; \
|
||||
install one with enable_memwal or leave use_memwal unset"
|
||||
message: "use_rte(true) was set but the table has no RTE write spec; \
|
||||
install one with enable_rte or leave use_rte unset"
|
||||
.to_string(),
|
||||
});
|
||||
}
|
||||
@@ -629,7 +629,7 @@ pub(crate) async fn lsm_dispatch_decision(
|
||||
if !params.on.is_empty() && params.on != pk_cols {
|
||||
return Err(Error::InvalidInput {
|
||||
message: format!(
|
||||
"merge_insert: `on` columns {:?} must match the table's unenforced primary key {:?} when a MemWAL write spec is set; pass an empty `on` to default to the primary key",
|
||||
"merge_insert: `on` columns {:?} must match the table's unenforced primary key {:?} when an RTE write spec is set; pass an empty `on` to default to the primary key",
|
||||
params.on, pk_cols
|
||||
),
|
||||
});
|
||||
@@ -637,7 +637,7 @@ pub(crate) async fn lsm_dispatch_decision(
|
||||
|
||||
if !is_upsert_only(params) {
|
||||
return Err(Error::InvalidInput {
|
||||
message: "merge_insert: when a MemWAL write spec is set, only the upsert form (when_matched_update_all without a filter + when_not_matched_insert_all, no by-source delete) is supported; call use_memwal(false) to use the standard merge_insert path".to_string(),
|
||||
message: "merge_insert: when an RTE write spec is set, only the upsert form (when_matched_update_all without a filter + when_not_matched_insert_all, no by-source delete) is supported; call use_rte(false) to use the standard merge_insert path".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -678,7 +678,7 @@ fn resolve_lsm_mode(details: &MemWalIndexDetails) -> Result<LsmMode> {
|
||||
.and_then(|s| s.parse::<u32>().ok())
|
||||
.filter(|n| *n > 0)
|
||||
.ok_or_else(|| Error::Runtime {
|
||||
message: "merge_insert: MemWAL bucket spec has a missing or invalid num_buckets parameter".to_string(),
|
||||
message: "merge_insert: RTE bucket spec has a missing or invalid num_buckets parameter".to_string(),
|
||||
})?;
|
||||
Ok(LsmMode::Bucket { spec })
|
||||
}
|
||||
@@ -697,7 +697,7 @@ fn resolve_lsm_mode(details: &MemWalIndexDetails) -> Result<LsmMode> {
|
||||
// LSM merge_insert execution
|
||||
// =============================================================================
|
||||
|
||||
/// Execute a `merge_insert` through the MemWAL shard writer cache.
|
||||
/// Execute a `merge_insert` through the RTE shard writer cache.
|
||||
///
|
||||
/// The entire input is collected, schema-aligned, and shard-validated before
|
||||
/// anything is written, then issued as a single atomic `ShardWriter::put` — so
|
||||
@@ -716,7 +716,7 @@ pub(crate) async fn execute_lsm_merge_insert(
|
||||
|
||||
// Collect, align and shard-validate the whole input before writing
|
||||
// anything. `ShardWriter::put` is atomic over the batch vector, so any
|
||||
// failure raised here leaves the MemWAL untouched.
|
||||
// failure raised here leaves the RTE untouched.
|
||||
let mut batches: Vec<RecordBatch> = Vec::new();
|
||||
let mut total_rows: u64 = 0;
|
||||
|
||||
@@ -803,7 +803,7 @@ fn resolve_batch_shard(
|
||||
.downcast_ref::<Int32Array>()
|
||||
.ok_or_else(|| Error::Runtime {
|
||||
message: format!(
|
||||
"merge_insert: MemWAL bucket evaluator returned {:?}; expected Int32",
|
||||
"merge_insert: RTE bucket evaluator returned {:?}; expected Int32",
|
||||
values.data_type()
|
||||
),
|
||||
})?;
|
||||
@@ -824,7 +824,7 @@ fn resolve_batch_shard(
|
||||
Ok(bucket_shard_id(u32::try_from(first).map_err(|_| {
|
||||
Error::Runtime {
|
||||
message: format!(
|
||||
"merge_insert: MemWAL bucket evaluator returned negative bucket {}",
|
||||
"merge_insert: RTE bucket evaluator returned negative bucket {}",
|
||||
first
|
||||
),
|
||||
}
|
||||
@@ -856,7 +856,7 @@ fn evaluate_lsm_shard_values(
|
||||
if values.num_columns() != 1 {
|
||||
return Err(Error::Runtime {
|
||||
message: format!(
|
||||
"merge_insert: MemWAL sharding spec evaluated to {} fields; expected exactly one",
|
||||
"merge_insert: RTE sharding spec evaluated to {} fields; expected exactly one",
|
||||
values.num_columns()
|
||||
),
|
||||
});
|
||||
@@ -996,7 +996,7 @@ fn shard_writer_config_from_defaults(defaults: &HashMap<String, String>) -> Shar
|
||||
}
|
||||
|
||||
/// Re-attach the dataset's Arrow schema (including field metadata) to a
|
||||
/// user-supplied input batch. The MemWAL `ShardWriter` checks batch schemas
|
||||
/// user-supplied input batch. The RTE `ShardWriter` checks batch schemas
|
||||
/// against the dataset schema by exact equality, so input readers built
|
||||
/// without the primary-key metadata must be rewrapped before being put.
|
||||
///
|
||||
|
||||
@@ -94,9 +94,9 @@ async fn can_execute_namespace_query(table: &NativeTable, query: &AnyQuery) -> R
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
// A MemWAL write spec means reads auto-route through the LSM scanner in
|
||||
// `create_plan` even when `use_memwal` is unset. The namespace request has no
|
||||
// use_memwal field, so pushing the default query down would silently omit
|
||||
// An RTE write spec means reads auto-route through the LSM scanner in
|
||||
// `create_plan` even when `use_rte` is unset. The namespace request has no
|
||||
// use_rte field, so pushing the default query down would silently omit
|
||||
// un-compacted rows — force local execution whenever a spec is installed.
|
||||
let dataset = table.dataset.get().await?;
|
||||
if dataset.mem_wal_index_details().await?.is_some() {
|
||||
@@ -106,10 +106,10 @@ async fn can_execute_namespace_query(table: &NativeTable, query: &AnyQuery) -> R
|
||||
}
|
||||
|
||||
fn requires_local_namespace_execution(query: &AnyQuery) -> bool {
|
||||
// The namespace QueryTable request cannot represent approx_mode, search_effort or use_memwal.
|
||||
// For use_memwal that is worse than a tuning miss: MemWAL read routing lives only
|
||||
// The namespace QueryTable request cannot represent approx_mode, search_effort or use_rte.
|
||||
// For use_rte that is worse than a tuning miss: RTE read routing lives only
|
||||
// in `create_plan`, so a pushed-down query would return stale base-only data.
|
||||
if query.base().use_memwal.is_some() || query.base().take_offsets.is_some() {
|
||||
if query.base().use_rte.is_some() || query.base().take_offsets.is_some() {
|
||||
return true;
|
||||
}
|
||||
matches!(
|
||||
@@ -167,25 +167,25 @@ pub async fn create_plan(
|
||||
|
||||
let ds_ref = table.dataset.get().await?;
|
||||
|
||||
// MemWAL read routing driven by `use_memwal`:
|
||||
// RTE read routing driven by `use_rte`:
|
||||
// * unset — route through the LSM scanner iff the table carries a write spec
|
||||
// * Some(true) — force MemWAL routing; error if the table has no write spec
|
||||
// * Some(false) — read the base table only, bypassing the MemWAL
|
||||
// * Some(true) — force RTE routing; error if the table has no write spec
|
||||
// * Some(false) — read the base table only, bypassing the RTE
|
||||
// The LSM scanner surfaces in-flight `merge_insert` data (active/frozen
|
||||
// memtables + SSTables); validation and dispatch live in `lsm`.
|
||||
let has_spec = ds_ref.mem_wal_index_details().await?.is_some();
|
||||
let use_memwal = match query.base.use_memwal {
|
||||
let use_rte = match query.base.use_rte {
|
||||
Some(true) if !has_spec => {
|
||||
return Err(Error::InvalidInput {
|
||||
message: "use_memwal(true) was set but the table has no MemWAL write spec; \
|
||||
install one with enable_memwal or leave use_memwal unset"
|
||||
message: "use_rte(true) was set but the table has no RTE write spec; \
|
||||
install one with enable_rte or leave use_rte unset"
|
||||
.to_string(),
|
||||
});
|
||||
}
|
||||
Some(enable) => enable,
|
||||
None => has_spec,
|
||||
};
|
||||
if use_memwal {
|
||||
if use_rte {
|
||||
return lsm::create_lsm_plan(table, ds_ref, query).await;
|
||||
}
|
||||
|
||||
@@ -1195,7 +1195,7 @@ mod tests {
|
||||
|
||||
table.set_unenforced_primary_key(["id"]).await.unwrap();
|
||||
table
|
||||
.enable_memwal(crate::table::MemWalWriteSpec::unsharded())
|
||||
.enable_rte(crate::table::RTEWriteSpec::unsharded())
|
||||
.await
|
||||
.unwrap();
|
||||
let lsm_error = table
|
||||
@@ -1395,7 +1395,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_execute_query_use_memwal_with_namespace_pushdown_runs_locally() {
|
||||
async fn test_execute_query_use_rte_with_namespace_pushdown_runs_locally() {
|
||||
use crate::connect;
|
||||
use crate::table::query::execute_query;
|
||||
use arrow_array::{Int32Array, RecordBatch};
|
||||
@@ -1418,7 +1418,7 @@ mod tests {
|
||||
.unwrap();
|
||||
|
||||
let table = conn
|
||||
.create_table("test_use_memwal_namespace_fallback", batch)
|
||||
.create_table("test_use_rte_namespace_fallback", batch)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -1429,13 +1429,13 @@ mod tests {
|
||||
.pushdown_operations
|
||||
.insert(NamespaceClientPushdownOperation::QueryTable);
|
||||
|
||||
// `use_memwal` set (even to false) must force local execution — the namespace
|
||||
// request has no use_memwal field, so a pushdown would silently ignore it.
|
||||
// `use_rte` set (even to false) must force local execution — the namespace
|
||||
// request has no use_rte field, so a pushdown would silently ignore it.
|
||||
let query_vector = Arc::new(Float32Array::from(vec![0.0, 0.0]));
|
||||
let query = AnyQuery::VectorQuery(VectorQueryRequest {
|
||||
base: QueryRequest {
|
||||
limit: Some(1),
|
||||
use_memwal: Some(false),
|
||||
use_rte: Some(false),
|
||||
..Default::default()
|
||||
},
|
||||
column: Some("vector".to_string()),
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
//! MemWAL read path.
|
||||
//! RTE read path.
|
||||
//!
|
||||
//! When a table has a MemWAL write spec installed (see [`enable_memwal`]),
|
||||
//! When a table has an RTE write spec installed (see [`enable_rte`]),
|
||||
//! reads are routed through Lance's [`LsmScanner`] instead of the plain
|
||||
//! base-table scan unless the query sets
|
||||
//! [`use_memwal(false)`](crate::query::QueryBase::use_memwal). This makes data
|
||||
//! [`use_rte(false)`](crate::query::QueryBase::use_rte). This makes data
|
||||
//! written via the LSM `merge_insert` path — which lives in the active/frozen
|
||||
//! in-memory memtables and the SSTables until an external
|
||||
//! compaction merges it into the base table — visible to queries, deduplicated by
|
||||
@@ -17,10 +17,10 @@
|
||||
//! three run through a single [`LsmScanner`], so a `where` filter is honored as a
|
||||
//! prefilter uniformly — including for vector search, where `LsmScanner` threads
|
||||
//! it into the vector planner's prefilter. Shapes the LSM path cannot honor are
|
||||
//! rejected with [`Error::NotSupported`]; the caller must set `use_memwal(false)` to
|
||||
//! rejected with [`Error::NotSupported`]; the caller must set `use_rte(false)` to
|
||||
//! run those against the base table.
|
||||
//!
|
||||
//! [`enable_memwal`]: crate::Table::enable_memwal
|
||||
//! [`enable_rte`]: crate::Table::enable_rte
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -52,12 +52,12 @@ use crate::utils::default_vector_column;
|
||||
/// widen the per-source fetch to keep result pages filled.
|
||||
const LSM_OVERFETCH_FACTOR: f64 = 2.0;
|
||||
|
||||
/// Build the LSM read plan for a MemWAL-routed query.
|
||||
/// Build the LSM read plan for an RTE-routed query.
|
||||
///
|
||||
/// The caller guarantees `ds_ref` carries a MemWAL write spec (routing is decided
|
||||
/// The caller guarantees `ds_ref` carries an RTE write spec (routing is decided
|
||||
/// in [`create_plan`](super::create_plan)). Errors with [`Error::NotSupported`]
|
||||
/// for query shapes the LSM scanner cannot honor — the caller must set
|
||||
/// `use_memwal(false)` to run those against the base table.
|
||||
/// `use_rte(false)` to run those against the base table.
|
||||
pub(super) async fn create_lsm_plan(
|
||||
table: &NativeTable,
|
||||
ds_ref: Arc<Dataset>,
|
||||
@@ -67,11 +67,11 @@ pub(super) async fn create_lsm_plan(
|
||||
|
||||
// A time-traveled (checked-out) handle pins an older dataset version, but the
|
||||
// WAL manifests and cached writer expose current live state — mixing them would
|
||||
// surface WAL rows written after the requested version. `use_memwal(false)` reads
|
||||
// surface WAL rows written after the requested version. `use_rte(false)` reads
|
||||
// the base table at the pinned version.
|
||||
if table.dataset.time_travel_version().is_some() {
|
||||
return Err(Error::NotSupported {
|
||||
message: "the MemWAL LSM scanner cannot read from a time-traveled dataset version; set use_memwal(false) to read the base table at this version".to_string(),
|
||||
message: "the MemWAL LSM scanner cannot read from a time-traveled dataset version; set use_rte(false) to read the base table at this version".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -80,7 +80,7 @@ pub(super) async fn create_lsm_plan(
|
||||
.mem_wal_index_details()
|
||||
.await?
|
||||
.ok_or_else(|| Error::Runtime {
|
||||
message: "the MemWAL write spec disappeared during read planning".to_string(),
|
||||
message: "the RTE write spec disappeared during read planning".to_string(),
|
||||
})?;
|
||||
|
||||
let pk_columns = pk_columns(&ds_ref)?;
|
||||
@@ -135,12 +135,12 @@ pub(super) async fn create_lsm_plan(
|
||||
restore_projection(plan, &query, &pk_columns)
|
||||
}
|
||||
|
||||
/// Reject query shapes the MemWAL read path does not implement. On a MemWAL table
|
||||
/// Reject query shapes the RTE read path does not implement. On an RTE table
|
||||
/// reads route through the LSM scanner by default, so an unsupported shape is a
|
||||
/// hard error rather than a silent fallback to the base-only scan — which would
|
||||
/// exclude un-compacted MemWAL data. The caller must set `use_memwal(false)` to
|
||||
/// exclude un-compacted RTE data. The caller must set `use_rte(false)` to
|
||||
/// run these against the base table, accepting that the results omit un-compacted
|
||||
/// MemWAL data.
|
||||
/// RTE data.
|
||||
///
|
||||
/// A `where` filter is intentionally *not* rejected: every arm routes through
|
||||
/// [`LsmScanner`], which applies it as a prefilter (see [`base_scanner`]).
|
||||
@@ -148,7 +148,7 @@ fn reject_unsupported(query: &VectorQueryRequest) -> Result<()> {
|
||||
let unsupported = |what: &str| {
|
||||
Err(Error::NotSupported {
|
||||
message: format!(
|
||||
"the MemWAL LSM scanner does not support {what}; set use_memwal(false) to read the base table only (results will exclude un-compacted MemWAL data)"
|
||||
"the MemWAL LSM scanner does not support {what}; set use_rte(false) to read the base table only (results will exclude un-compacted RTE data)"
|
||||
),
|
||||
})
|
||||
};
|
||||
@@ -413,7 +413,7 @@ fn base_scanner(
|
||||
QueryFilter::Datafusion(expr) => scanner.filter_expr(expr.clone()),
|
||||
QueryFilter::Substrait(_) => {
|
||||
return Err(Error::NotSupported {
|
||||
message: "the MemWAL LSM scanner does not support Substrait filters; set use_memwal(false) to read the base table only".to_string(),
|
||||
message: "the MemWAL LSM scanner does not support Substrait filters; set use_rte(false) to read the base table only".to_string(),
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -458,11 +458,11 @@ async fn fts_plan(
|
||||
offset: Option<usize>,
|
||||
) -> Result<Arc<dyn ExecutionPlan>> {
|
||||
// Pre-check for a lancedb-flavored error; `LsmScanner` also validates the
|
||||
// single-column requirement, but without the `use_memwal(false)` guidance.
|
||||
// single-column requirement, but without the `use_rte(false)` guidance.
|
||||
let columns: Vec<String> = fts.columns().into_iter().collect();
|
||||
if columns.len() > 1 {
|
||||
return Err(Error::NotSupported {
|
||||
message: "the MemWAL LSM scanner full-text search supports a single column; set use_memwal(false) to read the base table only".to_string(),
|
||||
message: "the MemWAL LSM scanner full-text search supports a single column; set use_rte(false) to read the base table only".to_string(),
|
||||
});
|
||||
}
|
||||
let column = columns.first().ok_or_else(|| Error::NotSupported {
|
||||
@@ -482,7 +482,7 @@ async fn fts_plan(
|
||||
{
|
||||
return Err(Error::NotSupported {
|
||||
message: format!(
|
||||
"the MemWAL LSM scanner full-text search requires the FTS index on '{column}' to be maintained by the write spec (MemWalWriteSpec::with_maintained_indexes) and carried by every resident MemTable; otherwise un-compacted documents are omitted. set use_memwal(false) to read the base table only"
|
||||
"the MemWAL LSM scanner full-text search requires the FTS index on '{column}' to be maintained by the write spec (RTEWriteSpec::with_maintained_indexes) and carried by every resident MemTable; otherwise un-compacted documents are omitted. set use_rte(false) to read the base table only"
|
||||
),
|
||||
});
|
||||
}
|
||||
@@ -515,7 +515,7 @@ fn resident_memtables_carry(
|
||||
.all(|tables| carries(&tables.active) && tables.frozen.iter().all(&carries))
|
||||
}
|
||||
|
||||
/// Whether an index of `type_url_suffix` covering `column` is in the MemWAL spec's
|
||||
/// Whether an index of `type_url_suffix` covering `column` is in the RTE spec's
|
||||
/// maintained set. Only a maintained index has its catch-up tracked (so exclusion is
|
||||
/// gated correctly) and its in-memory arm kept current; an unmaintained base index
|
||||
/// falls back to the compaction watermark and can drop rows it has not re-indexed.
|
||||
@@ -633,7 +633,7 @@ fn resolve_single_index(
|
||||
if names.len() > 1 {
|
||||
return Err(Error::NotSupported {
|
||||
message: format!(
|
||||
"the MemWAL LSM scanner cannot resolve the {arm} index catch-up watermark for '{column}': it has multiple {arm} indexes; set use_memwal(false) to read the base table only"
|
||||
"the MemWAL LSM scanner cannot resolve the {arm} index catch-up watermark for '{column}': it has multiple {arm} indexes; set use_rte(false) to read the base table only"
|
||||
),
|
||||
});
|
||||
}
|
||||
@@ -682,7 +682,7 @@ fn restore_projection(
|
||||
///
|
||||
/// Note: the base and SSTable arms use `fast_search` (indexed data only), so a
|
||||
/// base-table row not covered by a vector index is invisible here — it surfaces
|
||||
/// only via the memtable or `use_memwal(false)`.
|
||||
/// only via the memtable or `use_rte(false)`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn vector_plan(
|
||||
dataset: &Dataset,
|
||||
@@ -717,7 +717,7 @@ async fn vector_plan(
|
||||
if !index_maintained(dataset, &column, details, "VectorIndexDetails").await? {
|
||||
return Err(Error::NotSupported {
|
||||
message: format!(
|
||||
"the MemWAL LSM scanner requires the vector index on '{column}' to be maintained by the write spec (MemWalWriteSpec::with_maintained_indexes); otherwise compacted rows not yet re-indexed are omitted. set use_memwal(false) to read the base table only"
|
||||
"the MemWAL LSM scanner requires the vector index on '{column}' to be maintained by the write spec (RTEWriteSpec::with_maintained_indexes); otherwise compacted rows not yet re-indexed are omitted. set use_rte(false) to read the base table only"
|
||||
),
|
||||
});
|
||||
}
|
||||
@@ -726,7 +726,7 @@ async fn vector_plan(
|
||||
// clear error rather than failing deep in the planner.
|
||||
if is_binary_vector_column(&arrow_schema, &column) {
|
||||
return Err(Error::NotSupported {
|
||||
message: "the MemWAL LSM scanner does not support binary (uint8) vector search; set use_memwal(false) to read the base table only".to_string(),
|
||||
message: "the MemWAL LSM scanner does not support binary (uint8) vector search; set use_rte(false) to read the base table only".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -813,7 +813,7 @@ mod tests {
|
||||
};
|
||||
assert!(
|
||||
matches!(reject_unsupported(&query), Err(Error::NotSupported { message })
|
||||
if message.contains("search_effort") && message.contains("un-compacted MemWAL"))
|
||||
if message.contains("search_effort") && message.contains("un-compacted RTE"))
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -87,7 +87,7 @@ async fn execute_refresh_column_with_source(
|
||||
column: &str,
|
||||
) -> Result<RefreshExecution> {
|
||||
table.dataset.ensure_mutable()?;
|
||||
ensure_no_memwal_spec(table).await?;
|
||||
ensure_no_rte_spec(table).await?;
|
||||
let dataset = table.dataset.get().await?;
|
||||
|
||||
let expression = declared_expression(&dataset, column)?;
|
||||
@@ -303,7 +303,7 @@ pub(crate) async fn execute_refresh_column_async(
|
||||
// Validate before spawning so bad input is reported by this call rather
|
||||
// than only by the job.
|
||||
table.dataset.ensure_mutable()?;
|
||||
ensure_no_memwal_spec(table).await?;
|
||||
ensure_no_rte_spec(table).await?;
|
||||
let dataset = table.dataset.get().await?;
|
||||
declared_expression(&dataset, column)?;
|
||||
drop(dataset);
|
||||
@@ -323,12 +323,12 @@ pub(crate) async fn execute_refresh_column_async(
|
||||
})))
|
||||
}
|
||||
|
||||
/// Refuse to refresh under a MemWAL write spec.
|
||||
/// Refuse to refresh under an RTE write spec.
|
||||
///
|
||||
/// Refresh enumerates base fragments, and a write spec keeps visible rows in
|
||||
/// un-compacted MemWAL tiers it cannot reach -- success would silently omit
|
||||
/// un-compacted RTE tiers it cannot reach -- success would silently omit
|
||||
/// readable rows.
|
||||
async fn ensure_no_memwal_spec(table: &NativeTable) -> Result<()> {
|
||||
async fn ensure_no_rte_spec(table: &NativeTable) -> Result<()> {
|
||||
use lance::dataset::mem_wal::DatasetMemWalExt;
|
||||
|
||||
// Unset drops the MemWAL index, so the spec alone stops describing a table
|
||||
@@ -341,7 +341,7 @@ async fn ensure_no_memwal_spec(table: &NativeTable) -> Result<()> {
|
||||
.list_mem_wal_latest_shard_ids()
|
||||
.await?
|
||||
.is_empty();
|
||||
if retained_sstables || table.get_memwal_spec().await?.is_some() {
|
||||
if retained_sstables || table.get_rte_spec().await?.is_some() {
|
||||
return Err(Error::NotSupported {
|
||||
message: "refresh_column is not supported on a table with an LSM write \
|
||||
spec: rows in un-compacted tiers are invisible to refresh"
|
||||
@@ -1637,7 +1637,7 @@ mod tests {
|
||||
/// writer left in that state.
|
||||
#[tokio::test]
|
||||
async fn test_refresh_refuses_a_foreign_lsm_state() {
|
||||
use crate::table::MemWalWriteSpec;
|
||||
use crate::table::RTEWriteSpec;
|
||||
|
||||
let tmp_dir = tempfile::tempdir().unwrap();
|
||||
let conn = connect(tmp_dir.path().to_str().unwrap())
|
||||
@@ -1654,10 +1654,7 @@ mod tests {
|
||||
.unwrap();
|
||||
let table = conn.create_table("lsm", batch).execute().await.unwrap();
|
||||
table.set_unenforced_primary_key(["x"]).await.unwrap();
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded())
|
||||
.await
|
||||
.unwrap();
|
||||
table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap();
|
||||
super::super::computed_columns::add_foreign_kind(&table, "doubled", "sql").await;
|
||||
|
||||
let err = table.refresh_column("doubled").await.unwrap_err();
|
||||
@@ -1673,7 +1670,7 @@ mod tests {
|
||||
/// flag still marks retained SSTable rows; refresh refuses on the flag.
|
||||
#[tokio::test]
|
||||
async fn test_refresh_refuses_retained_catchup_state() {
|
||||
use crate::table::MemWalWriteSpec;
|
||||
use crate::table::RTEWriteSpec;
|
||||
|
||||
let tmp_dir = tempfile::tempdir().unwrap();
|
||||
let conn = connect(tmp_dir.path().to_str().unwrap())
|
||||
@@ -1696,15 +1693,12 @@ mod tests {
|
||||
.await
|
||||
.unwrap();
|
||||
table.set_unenforced_primary_key(["x"]).await.unwrap();
|
||||
table
|
||||
.enable_memwal(MemWalWriteSpec::unsharded())
|
||||
.await
|
||||
.unwrap();
|
||||
table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap();
|
||||
let mut merge = table.merge_insert(&["x"]);
|
||||
merge
|
||||
.when_matched_update_all(None)
|
||||
.when_not_matched_insert_all()
|
||||
.use_memwal(true);
|
||||
.use_rte(true);
|
||||
merge
|
||||
.execute(Box::new(arrow_array::RecordBatchIterator::new(
|
||||
vec![Ok(batch)],
|
||||
@@ -1712,7 +1706,7 @@ mod tests {
|
||||
)))
|
||||
.await
|
||||
.unwrap();
|
||||
table.disable_memwal().await.unwrap();
|
||||
table.disable_rte().await.unwrap();
|
||||
super::super::computed_columns::add_foreign_kind(&table, "doubled", "sql").await;
|
||||
|
||||
let err = table.refresh_column("doubled").await.unwrap_err();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
//! Live per-table-shard MemWAL state — the shape [`crate::Table::get_memwal_stats`]
|
||||
//! Live per-table-shard RTE state — the shape [`crate::Table::get_rte_stats`]
|
||||
//! returns and [`super::checkpoint`] polls.
|
||||
//!
|
||||
//! Nothing here is derived: sums and differences (total SSTable bytes, WAL lag)
|
||||
@@ -79,18 +79,18 @@ impl TableShardStats {
|
||||
}
|
||||
}
|
||||
|
||||
/// Live MemWAL state, one entry per table shard.
|
||||
/// Live RTE state, one entry per table shard.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct MemWalStats {
|
||||
pub struct RTEStats {
|
||||
pub table_shards: Vec<TableShardStats>,
|
||||
}
|
||||
|
||||
/// Server-side JSON envelope for `get_memwal_stats`. `memwal_stats` is null when
|
||||
/// the table has no MemWAL write path.
|
||||
/// Server-side JSON envelope for `get_rte_stats`. `rte_stats` is null when
|
||||
/// the table has no RTE write path.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(crate) struct GetMemWalStatsResponse {
|
||||
pub(crate) struct GetRTEStatsResponse {
|
||||
#[serde(default)]
|
||||
pub memwal_stats: Option<MemWalStats>,
|
||||
pub rte_stats: Option<RTEStats>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -131,7 +131,7 @@ pub(crate) async fn execute_declare(
|
||||
) -> Result<AddColumnsResult> {
|
||||
use lance::dataset::mem_wal::DatasetMemWalExt;
|
||||
|
||||
// A MemWAL write spec keeps visible rows in tiers refresh cannot reach;
|
||||
// An RTE write spec keeps visible rows in tiers refresh cannot reach;
|
||||
// checked against latest committed state, not this handle's snapshot.
|
||||
table.checkout_latest().await?;
|
||||
computed_columns::ensure_not_function_bound(
|
||||
@@ -149,7 +149,7 @@ pub(crate) async fn execute_declare(
|
||||
.list_mem_wal_latest_shard_ids()
|
||||
.await?
|
||||
.is_empty();
|
||||
if retained_sstables || table.get_memwal_spec().await?.is_some() {
|
||||
if retained_sstables || table.get_rte_spec().await?.is_some() {
|
||||
return Err(Error::NotSupported {
|
||||
message: "computed columns are not supported on a table with an LSM write \
|
||||
spec: rows in un-compacted tiers are invisible to refresh"
|
||||
|
||||
@@ -1981,8 +1981,8 @@ async fn blob_layout_overwrite_replaces_schema_in_both_directions() -> Result<()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn blob_layout_memwal_merge_normalizes_before_writing() -> Result<()> {
|
||||
use lancedb::{query::Select, table::MemWalWriteSpec};
|
||||
async fn blob_layout_rte_merge_normalizes_before_writing() -> Result<()> {
|
||||
use lancedb::{query::Select, table::RTEWriteSpec};
|
||||
for wide in [false, true] {
|
||||
let tmp = tempdir().unwrap();
|
||||
let db = connect(tmp.path().to_str().unwrap()).execute().await?;
|
||||
@@ -1991,7 +1991,7 @@ async fn blob_layout_memwal_merge_normalizes_before_writing() -> Result<()> {
|
||||
.execute()
|
||||
.await?;
|
||||
table.set_unenforced_primary_key(["id"]).await?;
|
||||
table.enable_memwal(MemWalWriteSpec::unsharded()).await?;
|
||||
table.enable_rte(RTEWriteSpec::unsharded()).await?;
|
||||
let mut merge = table.merge_insert(&["id"]);
|
||||
merge
|
||||
.when_matched_update_all(None)
|
||||
|
||||
Reference in New Issue
Block a user