Elffuss BraidHub

kikocis/lancedb public

feat: add flag to enable faster manifest paths (#1612)

The new V2 manifest path scheme makes discovering the latest version of
a table constant time on object stores, regardless of the number of
versions in the table. See benchmarks in the PR here:
https://github.com/lancedb/lance/pull/2798

Closes #1583
Changesetb6fe4ce120a192d2a1df8dd3f174c25b1192a3e1f28afafc50429ef26b08d956
AuthorWill Jones <willjones127@gmail.com> · 2024-09-09 11:34 -07:00
CommitterGitHub <noreply@github.com> · 2024-09-09 11:34 -07:00
Parentsb28f6356c0da

Browse the files at this changeset

16 files changed

modified Cargo.toml +1 −0
@@ -23,6 +23,7 @@
2323 lance = { "version" = "=0.17.0", "features" = ["dynamodb"] }
2424 lance-index = { "version" = "=0.17.0" }
2525 lance-linalg = { "version" = "=0.17.0" }
26+lance-table = { "version" = "=0.17.0" }
2627 lance-testing = { "version" = "=0.17.0" }
2728 lance-datafusion = { "version" = "=0.17.0" }
2829 lance-encoding = { "version" = "=0.17.0" }
modified nodejs/__test__/connection.test.ts +55 −0
@@ -12,9 +12,11 @@
1212 // See the License for the specific language governing permissions and
1313 // limitations under the License.
1414
15+import { readdirSync } from "fs";
1516 import { Field, Float64, Schema } from "apache-arrow";
1617 import * as tmp from "tmp";
1718 import { Connection, Table, connect } from "../lancedb";
19+import { LocalTable } from "../lancedb/table";
1820
1921 describe("when connecting", () => {
2022 let tmpDir: tmp.DirResult;
@@ -134,4 +136,57 @@
134136 await table.add(data);
135137 await expect(isV2(table)).resolves.toBe(true);
136138 });
139+
140+ it("should be able to create tables with V2 manifest paths", async () => {
141+ const db = await connect(tmpDir.name);
142+ let table = (await db.createEmptyTable(
143+ "test_manifest_paths_v2_empty",
144+ new Schema([new Field("id", new Float64(), true)]),
145+ {
146+ enableV2ManifestPaths: true,
147+ },
148+ )) as LocalTable;
149+ expect(await table.usesV2ManifestPaths()).toBe(true);
150+
151+ let manifestDir =
152+ tmpDir.name + "/test_manifest_paths_v2_empty.lance/_versions";
153+ readdirSync(manifestDir).forEach((file) => {
154+ expect(file).toMatch(/^\d{20}\.manifest$/);
155+ });
156+
157+ table = (await db.createTable("test_manifest_paths_v2", [{ id: 1 }], {
158+ enableV2ManifestPaths: true,
159+ })) as LocalTable;
160+ expect(await table.usesV2ManifestPaths()).toBe(true);
161+ manifestDir = tmpDir.name + "/test_manifest_paths_v2.lance/_versions";
162+ readdirSync(manifestDir).forEach((file) => {
163+ expect(file).toMatch(/^\d{20}\.manifest$/);
164+ });
165+ });
166+
167+ it("should be able to migrate tables to the V2 manifest paths", async () => {
168+ const db = await connect(tmpDir.name);
169+ const table = (await db.createEmptyTable(
170+ "test_manifest_path_migration",
171+ new Schema([new Field("id", new Float64(), true)]),
172+ {
173+ enableV2ManifestPaths: false,
174+ },
175+ )) as LocalTable;
176+
177+ expect(await table.usesV2ManifestPaths()).toBe(false);
178+
179+ const manifestDir =
180+ tmpDir.name + "/test_manifest_path_migration.lance/_versions";
181+ readdirSync(manifestDir).forEach((file) => {
182+ expect(file).toMatch(/^\d\.manifest$/);
183+ });
184+
185+ await table.migrateManifestPathsV2();
186+ expect(await table.usesV2ManifestPaths()).toBe(true);
187+
188+ readdirSync(manifestDir).forEach((file) => {
189+ expect(file).toMatch(/^\d{20}\.manifest$/);
190+ });
191+ });
137192 });
modified nodejs/lancedb/connection.ts +11 −0
@@ -52,6 +52,15 @@
5252 */
5353 dataStorageVersion?: string;
5454
55+ /**
56+ * Use the new V2 manifest paths. These paths provide more efficient
57+ * opening of datasets with many versions on object stores. WARNING:
58+ * turning this on will make the dataset unreadable for older versions
59+ * of LanceDB (prior to 0.10.0). To migrate an existing dataset, instead
60+ * use the {@link LocalTable#migrateManifestPathsV2} method.
61+ */
62+ enableV2ManifestPaths?: boolean;
63+
5564 /**
5665 * If true then data files will be written with the legacy format
5766 *
@@ -270,6 +279,7 @@
270279 mode,
271280 cleanseStorageOptions(options?.storageOptions),
272281 dataStorageVersion,
282+ options?.enableV2ManifestPaths,
273283 );
274284
275285 return new LocalTable(innerTable);
@@ -308,6 +318,7 @@
308318 mode,
309319 cleanseStorageOptions(options?.storageOptions),
310320 dataStorageVersion,
321+ options?.enableV2ManifestPaths,
311322 );
312323 return new LocalTable(innerTable);
313324 }
modified nodejs/lancedb/table.ts +27 −0
@@ -697,4 +697,31 @@
697697 on = Array.isArray(on) ? on : [on];
698698 return new MergeInsertBuilder(this.inner.mergeInsert(on));
699699 }
700+
701+ /**
702+ * Check if the table uses the new manifest path scheme.
703+ *
704+ * This function will return true if the table uses the V2 manifest
705+ * path scheme.
706+ */
707+ async usesV2ManifestPaths(): Promise<boolean> {
708+ return await this.inner.usesV2ManifestPaths();
709+ }
710+
711+ /**
712+ * Migrate the table to use the new manifest path scheme.
713+ *
714+ * This function will rename all V1 manifests to V2 manifest paths.
715+ * These paths provide more efficient opening of datasets with many versions
716+ * on object stores.
717+ *
718+ * This function is idempotent, and can be run multiple times without
719+ * changing the state of the object store.
720+ *
721+ * However, it should not be run while other concurrent operations are happening.
722+ * And it should also run until completion before resuming other operations.
723+ */
724+ async migrateManifestPathsV2(): Promise<void> {
725+ await this.inner.migrateManifestPathsV2();
726+ }
700727 }
modified nodejs/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified nodejs/src/connection.rs +8 −0
@@ -124,6 +124,7 @@
124124 mode: String,
125125 storage_options: Option<HashMap<String, String>>,
126126 data_storage_options: Option<String>,
127+ enable_v2_manifest_paths: Option<bool>,
127128 ) -> napi::Result<Table> {
128129 let batches = ipc_file_to_batches(buf.to_vec())
129130 .map_err(|e| napi::Error::from_reason(format!("Failed to read IPC file: {}", e)))?;
@@ -140,6 +141,9 @@
140141 .map_err(|e| napi::Error::from_reason(format!("{}", e)))?,
141142 );
142143 }
144+ if let Some(enable_v2_manifest_paths) = enable_v2_manifest_paths {
145+ builder = builder.enable_v2_manifest_paths(enable_v2_manifest_paths);
146+ }
143147 let tbl = builder
144148 .execute()
145149 .await
@@ -155,6 +159,7 @@
155159 mode: String,
156160 storage_options: Option<HashMap<String, String>>,
157161 data_storage_options: Option<String>,
162+ enable_v2_manifest_paths: Option<bool>,
158163 ) -> napi::Result<Table> {
159164 let schema = ipc_file_to_schema(schema_buf.to_vec()).map_err(|e| {
160165 napi::Error::from_reason(format!("Failed to marshal schema from JS to Rust: {}", e))
@@ -175,6 +180,9 @@
175180 .map_err(|e| napi::Error::from_reason(format!("{}", e)))?,
176181 );
177182 }
183+ if let Some(enable_v2_manifest_paths) = enable_v2_manifest_paths {
184+ builder = builder.enable_v2_manifest_paths(enable_v2_manifest_paths);
185+ }
178186 let tbl = builder
179187 .execute()
180188 .await
modified nodejs/src/table.rs +20 −0
@@ -347,6 +347,26 @@
347347 let on: Vec<_> = on.iter().map(String::as_str).collect();
348348 Ok(self.inner_ref()?.merge_insert(on.as_slice()).into())
349349 }
350+
351+ #[napi(catch_unwind)]
352+ pub async fn uses_v2_manifest_paths(&self) -> napi::Result<bool> {
353+ self.inner_ref()?
354+ .as_native()
355+ .ok_or_else(|| napi::Error::from_reason("This cannot be run on a remote table"))?
356+ .uses_v2_manifest_paths()
357+ .await
358+ .default_error()
359+ }
360+
361+ #[napi(catch_unwind)]
362+ pub async fn migrate_manifest_paths_v2(&self) -> napi::Result<()> {
363+ self.inner_ref()?
364+ .as_native()
365+ .ok_or_else(|| napi::Error::from_reason("This cannot be run on a remote table"))?
366+ .migrate_manifest_paths_v2()
367+ .await
368+ .default_error()
369+ }
350370 }
351371
352372 #[napi(object)]
modified python/python/lancedb/_lancedb.pyi +2 −0
@@ -25,6 +25,7 @@
2525 data: pa.RecordBatchReader,
2626 storage_options: Optional[Dict[str, str]] = None,
2727 data_storage_version: Optional[str] = None,
28+ enable_v2_manifest_paths: Optional[bool] = None,
2829 ) -> Table: ...
2930 async def create_empty_table(
3031 self,
@@ -33,6 +34,7 @@
3334 schema: pa.Schema,
3435 storage_options: Optional[Dict[str, str]] = None,
3536 data_storage_version: Optional[str] = None,
37+ enable_v2_manifest_paths: Optional[bool] = None,
3638 ) -> Table: ...
3739
3840 class Table:
modified python/python/lancedb/db.py +11 −0
@@ -567,6 +567,7 @@
567567 *,
568568 data_storage_version: Optional[str] = None,
569569 use_legacy_format: Optional[bool] = None,
570+ enable_v2_manifest_paths: Optional[bool] = None,
570571 ) -> AsyncTable:
571572 """Create an [AsyncTable][lancedb.table.AsyncTable] in the database.
572573
@@ -618,6 +619,14 @@
618619 If True, use the legacy format for the table. If False, use the new format.
619620 The default is True while the new format is in beta.
620621 This method is deprecated, use `data_storage_version` instead.
622+ enable_v2_manifest_paths: bool, optional, default False
623+ Use the new V2 manifest paths. These paths provide more efficient
624+ opening of datasets with many versions on object stores. WARNING:
625+ turning this on will make the dataset unreadable for older versions
626+ of LanceDB (prior to 0.13.0). To migrate an existing dataset, instead
627+ use the
628+ [AsyncTable.migrate_manifest_paths_v2][lancedb.table.AsyncTable.migrate_manifest_paths_v2]
629+ method.
621630
622631
623632 Returns
@@ -761,6 +770,7 @@
761770 schema,
762771 storage_options=storage_options,
763772 data_storage_version=data_storage_version,
773+ enable_v2_manifest_paths=enable_v2_manifest_paths,
764774 )
765775 else:
766776 data = data_to_reader(data, schema)
@@ -770,6 +780,7 @@
770780 data,
771781 storage_options=storage_options,
772782 data_storage_version=data_storage_version,
783+ enable_v2_manifest_paths=enable_v2_manifest_paths,
773784 )
774785
775786 return AsyncTable(new_table)
modified python/python/lancedb/table.py +31 −0
@@ -2539,3 +2539,34 @@
25392539 List all indices that have been created with Self::create_index
25402540 """
25412541 return await self._inner.list_indices()
2542+
2543+ async def uses_v2_manifest_paths(self) -> bool:
2544+ """
2545+ Check if the table is using the new v2 manifest paths.
2546+
2547+ Returns
2548+ -------
2549+ bool
2550+ True if the table is using the new v2 manifest paths, False otherwise.
2551+ """
2552+ return await self._inner.uses_v2_manifest_paths()
2553+
2554+ async def migrate_manifest_paths_v2(self):
2555+ """
2556+ Migrate the manifest paths to the new format.
2557+
2558+ This will update the manifest to use the new v2 format for paths.
2559+
2560+ This function is idempotent, and can be run multiple times without
2561+ changing the state of the object store.
2562+
2563+ !!! danger
2564+
2565+ This should not be run while other concurrent operations are happening.
2566+ And it should also run until completion before resuming other operations.
2567+
2568+ You can use
2569+ [AsyncTable.uses_v2_manifest_paths][lancedb.table.AsyncTable.uses_v2_manifest_paths]
2570+ to check if the table is already using the new path style.
2571+ """
2572+ await self._inner.migrate_manifest_paths_v2()
modified python/python/tests/test_db.py +35 −0
@@ -13,6 +13,7 @@
1313
1414 import re
1515 from datetime import timedelta
16+import os
1617
1718 import lancedb
1819 import numpy as np
@@ -413,6 +414,40 @@
413414 # await db.create_table("test", schema=bad_schema, exist_ok=True)
414415
415416
417+@pytest.mark.asyncio
418+async def test_create_table_v2_manifest_paths_async(tmp_path):
419+ db = await lancedb.connect_async(tmp_path)
420+ # Create table in v2 mode with v2 manifest paths enabled
421+ tbl = await db.create_table(
422+ "test_v2_manifest_paths",
423+ data=[{"id": 0}],
424+ use_legacy_format=False,
425+ enable_v2_manifest_paths=True,
426+ )
427+ assert await tbl.uses_v2_manifest_paths()
428+ manifests_dir = tmp_path / "test_v2_manifest_paths.lance" / "_versions"
429+ for manifest in os.listdir(manifests_dir):
430+ assert re.match(r"\d{20}\.manifest", manifest)
431+
432+ # Start a table in V1 mode then migrate
433+ tbl = await db.create_table(
434+ "test_v2_migration",
435+ data=[{"id": 0}],
436+ use_legacy_format=False,
437+ enable_v2_manifest_paths=False,
438+ )
439+ assert not await tbl.uses_v2_manifest_paths()
440+ manifests_dir = tmp_path / "test_v2_migration.lance" / "_versions"
441+ for manifest in os.listdir(manifests_dir):
442+ assert re.match(r"\d\.manifest", manifest)
443+
444+ await tbl.migrate_manifest_paths_v2()
445+ assert await tbl.uses_v2_manifest_paths()
446+
447+ for manifest in os.listdir(manifests_dir):
448+ assert re.match(r"\d{20}\.manifest", manifest)
449+
450+
416451 def test_open_table_sync(tmp_path):
417452 db = lancedb.connect(tmp_path)
418453 db.create_table("test", data=[{"id": 0}])
modified python/src/connection.rs +10 −0
@@ -81,6 +81,7 @@
8181 data: Bound<'_, PyAny>,
8282 storage_options: Option<HashMap<String, String>>,
8383 data_storage_version: Option<String>,
84+ enable_v2_manifest_paths: Option<bool>,
8485 ) -> PyResult<Bound<'a, PyAny>> {
8586 let inner = self_.get_inner()?.clone();
8687
@@ -93,6 +94,10 @@
9394 builder = builder.storage_options(storage_options);
9495 }
9596
97+ if let Some(enable_v2_manifest_paths) = enable_v2_manifest_paths {
98+ builder = builder.enable_v2_manifest_paths(enable_v2_manifest_paths);
99+ }
100+
96101 if let Some(data_storage_version) = data_storage_version.as_ref() {
97102 builder = builder.data_storage_version(
98103 LanceFileVersion::from_str(data_storage_version)
@@ -113,6 +118,7 @@
113118 schema: Bound<'_, PyAny>,
114119 storage_options: Option<HashMap<String, String>>,
115120 data_storage_version: Option<String>,
121+ enable_v2_manifest_paths: Option<bool>,
116122 ) -> PyResult<Bound<'a, PyAny>> {
117123 let inner = self_.get_inner()?.clone();
118124
@@ -126,6 +132,10 @@
126132 builder = builder.storage_options(storage_options);
127133 }
128134
135+ if let Some(enable_v2_manifest_paths) = enable_v2_manifest_paths {
136+ builder = builder.enable_v2_manifest_paths(enable_v2_manifest_paths);
137+ }
138+
129139 if let Some(data_storage_version) = data_storage_version.as_ref() {
130140 builder = builder.data_storage_version(
131141 LanceFileVersion::from_str(data_storage_version)
modified python/src/table.rs +24 −0
@@ -303,4 +303,28 @@
303303 })
304304 })
305305 }
306+
307+ pub fn uses_v2_manifest_paths(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
308+ let inner = self_.inner_ref()?.clone();
309+ future_into_py(self_.py(), async move {
310+ inner
311+ .as_native()
312+ .ok_or_else(|| PyValueError::new_err("This cannot be run on a remote table"))?
313+ .uses_v2_manifest_paths()
314+ .await
315+ .infer_error()
316+ })
317+ }
318+
319+ pub fn migrate_manifest_paths_v2(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
320+ let inner = self_.inner_ref()?.clone();
321+ future_into_py(self_.py(), async move {
322+ inner
323+ .as_native()
324+ .ok_or_else(|| PyValueError::new_err("This cannot be run on a remote table"))?
325+ .migrate_manifest_paths_v2()
326+ .await
327+ .infer_error()
328+ })
329+ }
306330 }
modified rust/lancedb/Cargo.toml +1 −0
@@ -27,6 +27,7 @@
2727 lance = { workspace = true }
2828 lance-datafusion.workspace = true
2929 lance-index = { workspace = true }
30+lance-table = { workspace = true }
3031 lance-linalg = { workspace = true }
3132 lance-testing = { workspace = true }
3233 lance-encoding = { workspace = true }
modified rust/lancedb/src/connection.rs +24 −0
@@ -142,6 +142,7 @@
142142 pub(crate) table_definition: Option<TableDefinition>,
143143 pub(crate) embeddings: Vec<(EmbeddingDefinition, Arc<dyn EmbeddingFunction>)>,
144144 pub(crate) data_storage_version: Option<LanceFileVersion>,
145+ pub(crate) enable_v2_manifest_paths: Option<bool>,
145146 }
146147
147148 // Builder methods that only apply when we have initial data
@@ -156,6 +157,7 @@
156157 table_definition: None,
157158 embeddings: Vec::new(),
158159 data_storage_version: None,
160+ enable_v2_manifest_paths: None,
159161 }
160162 }
161163
@@ -188,6 +190,7 @@
188190 write_options: self.write_options,
189191 embeddings: self.embeddings,
190192 data_storage_version: self.data_storage_version,
193+ enable_v2_manifest_paths: self.enable_v2_manifest_paths,
191194 };
192195 Ok((data, builder))
193196 }
@@ -222,6 +225,7 @@
222225 write_options: WriteOptions::default(),
223226 embeddings: Vec::new(),
224227 data_storage_version: None,
228+ enable_v2_manifest_paths: None,
225229 }
226230 }
227231
@@ -284,6 +288,23 @@
284288 self
285289 }
286290
291+ /// Set whether to use V2 manifest paths for the table. (default: false)
292+ ///
293+ /// These paths provide more efficient opening of tables with many
294+ /// versions on object stores.
295+ ///
296+ /// <div class="warning">Turning this on will make the dataset unreadable
297+ /// for older versions of LanceDB (prior to 0.10.0).</div>
298+ ///
299+ /// To migrate an existing dataset, instead use the
300+ /// [[NativeTable::migrate_manifest_paths_v2]].
301+ ///
302+ /// This has no effect in LanceDB Cloud.
303+ pub fn enable_v2_manifest_paths(mut self, use_v2_manifest_paths: bool) -> Self {
304+ self.enable_v2_manifest_paths = Some(use_v2_manifest_paths);
305+ self
306+ }
307+
287308 /// Set the data storage version.
288309 ///
289310 /// The default is `LanceFileVersion::Legacy`.
@@ -976,7 +997,10 @@
976997 if matches!(&options.mode, CreateTableMode::Overwrite) {
977998 write_params.mode = WriteMode::Overwrite;
978999 }
1000+
9791001 write_params.data_storage_version = options.data_storage_version;
1002+ write_params.enable_v2_manifest_paths =
1003+ options.enable_v2_manifest_paths.unwrap_or_default();
9801004
9811005 match NativeTable::create(
9821006 &table_uri,
modified rust/lancedb/src/table.rs +30 −0
@@ -43,6 +43,7 @@
4343 use lance_index::vector::sq::builder::SQBuildParams;
4444 use lance_index::DatasetIndexExt;
4545 use lance_index::IndexType;
46+use lance_table::io::commit::ManifestNamingScheme;
4647 use log::info;
4748 use serde::{Deserialize, Serialize};
4849 use snafu::whatever;
@@ -1646,6 +1647,35 @@
16461647 Default::default(),
16471648 )?))
16481649 }
1650+
1651+ /// Check whether the table uses V2 manifest paths.
1652+ ///
1653+ /// See [Self::migrate_manifest_paths_v2] and [ManifestNamingScheme] for
1654+ /// more information.
1655+ pub async fn uses_v2_manifest_paths(&self) -> Result<bool> {
1656+ let dataset = self.dataset.get().await?;
1657+ Ok(dataset.manifest_naming_scheme == ManifestNamingScheme::V2)
1658+ }
1659+
1660+ /// Migrate the table to use the new manifest path scheme.
1661+ ///
1662+ /// This function will rename all V1 manifests to V2 manifest paths.
1663+ /// These paths provide more efficient opening of datasets with many versions
1664+ /// on object stores.
1665+ ///
1666+ /// This function is idempotent, and can be run multiple times without
1667+ /// changing the state of the object store.
1668+ ///
1669+ /// However, it should not be run while other concurrent operations are happening.
1670+ /// And it should also run until completion before resuming other operations.
1671+ ///
1672+ /// You can use [Self::uses_v2_manifest_paths] to check if the table is already
1673+ /// using V2 manifest paths.
1674+ pub async fn migrate_manifest_paths_v2(&self) -> Result<()> {
1675+ let mut dataset = self.dataset.get_mut().await?;
1676+ dataset.migrate_manifest_paths_v2().await?;
1677+ Ok(())
1678+ }
16491679 }
16501680
16511681 #[async_trait::async_trait]