mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
refactor(sdk): share Optimize submission and option conversion
This commit is contained in:
@@ -3163,7 +3163,7 @@ class Table(ABC):
|
||||
"""
|
||||
|
||||
def optimize_async(self, **options: Unpack[OptimizeOptions]) -> Job[OptimizeResult]:
|
||||
"""Submit remote compaction and return a durable job after acceptance.
|
||||
"""Submit remote Optimize and return a durable job after acceptance.
|
||||
|
||||
Uses SQL OPTIMIZE with the table handle's branch and namespace. Supports
|
||||
the four per-job settings in
|
||||
@@ -3185,7 +3185,7 @@ class Table(ABC):
|
||||
>>> result = job.wait() # doctest: +SKIP
|
||||
>>> print(result.rows_succeeded) # doctest: +SKIP
|
||||
"""
|
||||
raise NotImplementedError("compaction jobs are only supported on remote tables")
|
||||
raise NotImplementedError("Optimize jobs are only supported on remote tables")
|
||||
|
||||
@abstractmethod
|
||||
def optimize(self, **options: Unpack[OptimizeOptions]) -> OptimizeStats:
|
||||
@@ -9579,7 +9579,7 @@ class AsyncTable:
|
||||
async def optimize_async(
|
||||
self, **options: Unpack[OptimizeOptions]
|
||||
) -> AsyncJob[OptimizeResult]:
|
||||
"""Submit remote compaction; await the returned job for actual results.
|
||||
"""Submit remote Optimize; await the returned job for actual results.
|
||||
|
||||
See [Table.optimize_async][lancedb.table.Table.optimize_async] for options,
|
||||
permissions, completion semantics and compatibility requirements.
|
||||
|
||||
@@ -7543,6 +7543,7 @@ def test_remote_function_registration_transports_max_concurrency():
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("method", ["optimize", "optimize_async"])
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"options,sql_options",
|
||||
@@ -7573,7 +7574,7 @@ def test_remote_function_registration_transports_max_concurrency():
|
||||
],
|
||||
)
|
||||
async def test_remote_optimize_forwards_per_job_data_options(
|
||||
asynchronous, options, sql_options
|
||||
asynchronous, method, options, sql_options
|
||||
):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
@@ -7584,25 +7585,26 @@ async def test_remote_optimize_forwards_per_job_data_options(
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.tickets.append(ticket.ticket)
|
||||
return flight.RecordBatchStream(
|
||||
pa.table({"ok": pa.array([], type=pa.bool_())})
|
||||
)
|
||||
return flight.RecordBatchStream(pa.table({"job_id": ["optimize-job"]}))
|
||||
|
||||
server = AckServer()
|
||||
with _mock_remote_sql_connection(server) as kwargs:
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(**kwargs)
|
||||
table = await db.create_table("test", [{"id": 1}])
|
||||
stats = await table.optimize(**options)
|
||||
stats = await getattr(table, method)(**options)
|
||||
else:
|
||||
table = lancedb.connect(**kwargs).create_table("test", [{"id": 1}])
|
||||
stats = table.optimize(**options)
|
||||
stats = getattr(table, method)(**options)
|
||||
assert len(server.tickets) == 1
|
||||
assert b"OPTIMIZE" in server.tickets[0]
|
||||
assert all(option in server.tickets[0] for option in sql_options)
|
||||
if not sql_options:
|
||||
assert b"WITH (" not in server.tickets[0]
|
||||
assert stats.prune.bytes_removed == 0
|
||||
if method == "optimize":
|
||||
assert stats.prune.bytes_removed == 0
|
||||
else:
|
||||
assert stats.id == "optimize-job"
|
||||
|
||||
|
||||
def test_remote_optimize_does_not_drop_options_after_server_rejection():
|
||||
@@ -7646,9 +7648,7 @@ def test_remote_optimize_skips_prune_and_index():
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.tickets.append(ticket.ticket)
|
||||
return flight.RecordBatchStream(
|
||||
pa.table({"ok": pa.array([], type=pa.bool_())})
|
||||
)
|
||||
return flight.RecordBatchStream(pa.table({"job_id": ["optimize-job"]}))
|
||||
|
||||
server = AckServer()
|
||||
with _mock_remote_table_with_sql(server) as table:
|
||||
@@ -8523,8 +8523,13 @@ async def test_remote_compaction_job_result_and_reopen(asynchronous, outcome):
|
||||
assert b"target_rows_per_fragment = 100" in server.tickets[0]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize("method", ["optimize", "optimize_async"])
|
||||
@pytest.mark.parametrize("ids", [[], [None], [""], ["a", "b"]])
|
||||
def test_remote_compaction_rejects_ambiguous_receipt_without_resubmission(ids):
|
||||
async def test_remote_optimize_rejects_ambiguous_receipt_without_resubmission(
|
||||
asynchronous, method, ids
|
||||
):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
class Server(flight.FlightServerBase):
|
||||
@@ -8540,10 +8545,16 @@ def test_remote_compaction_rejects_ambiguous_receipt_without_resubmission(ids):
|
||||
|
||||
server = Server()
|
||||
with _mock_remote_sql_connection(server) as kwargs:
|
||||
db = lancedb.connect(**kwargs)
|
||||
table = db.create_table("test", [{"id": 1}])
|
||||
with pytest.raises(Exception, match="inspect jobs before retrying"):
|
||||
table.optimize_async()
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(**kwargs)
|
||||
table = await db.create_table("test", [{"id": 1}])
|
||||
with pytest.raises(Exception, match="inspect jobs before retrying"):
|
||||
await getattr(table, method)()
|
||||
else:
|
||||
db = lancedb.connect(**kwargs)
|
||||
table = db.create_table("test", [{"id": 1}])
|
||||
with pytest.raises(Exception, match="inspect jobs before retrying"):
|
||||
getattr(table, method)()
|
||||
assert server.calls == 1
|
||||
|
||||
|
||||
|
||||
+31
-29
@@ -31,7 +31,7 @@ use lancedb::index::scalar::FtsIndexBuilder;
|
||||
use lancedb::table::{
|
||||
AddDataMode, ColumnAlteration, Duration, FieldMetadataUpdate, FtsToken as LanceDbFtsToken,
|
||||
FunctionRefreshPlanningConfig, FunctionRefreshPodResources, FunctionWorkerResourceBudget,
|
||||
IndexRemapMode, NewColumnTransform, OptimizeDataMode, OptimizeOptions, Ref,
|
||||
IndexRemapMode, NewColumnTransform, OptimizeDataMode, OptimizeOptions, OptimizeOverrides, Ref,
|
||||
RefreshColumnOptions, Table as LanceDbTable,
|
||||
};
|
||||
use lancedb::tokenize as lancedb_tokenize;
|
||||
@@ -487,10 +487,27 @@ fn optional_i64_bounded_u64(value: &Bound<'_, PyAny>, name: &str) -> PyResult<Op
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn parse_data_options(options: Option<&Bound<'_, PyDict>>) -> PyResult<OptimizeOptions> {
|
||||
/// Preserve Python field presence while sharing Embedded and Enterprise parsing.
|
||||
#[derive(Default)]
|
||||
struct ParsedOptimizeOptions {
|
||||
options: OptimizeOptions,
|
||||
target_specified: bool,
|
||||
}
|
||||
|
||||
impl ParsedOptimizeOptions {
|
||||
fn into_remote_overrides(self) -> PyResult<OptimizeOverrides> {
|
||||
let mut overrides = OptimizeOverrides::try_from(self.options).infer_error()?;
|
||||
if !self.target_specified {
|
||||
overrides.target_rows_per_fragment = None;
|
||||
}
|
||||
Ok(overrides)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_optimize_options(options: Option<&Bound<'_, PyDict>>) -> PyResult<ParsedOptimizeOptions> {
|
||||
let mut parsed = OptimizeOptions::default();
|
||||
let Some(options) = options else {
|
||||
return Ok(parsed);
|
||||
return Ok(ParsedOptimizeOptions::default());
|
||||
};
|
||||
|
||||
for (key, value) in options.iter() {
|
||||
@@ -551,13 +568,16 @@ fn parse_data_options(options: Option<&Bound<'_, PyDict>>) -> PyResult<OptimizeO
|
||||
}
|
||||
_ => {
|
||||
return Err(PyValueError::new_err(format!(
|
||||
"Invalid compaction option: {key}"
|
||||
"Invalid Optimize option: {key}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(parsed)
|
||||
Ok(ParsedOptimizeOptions {
|
||||
options: parsed,
|
||||
target_specified: options.contains("target_rows_per_fragment")?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Statistics about a compaction operation.
|
||||
@@ -2295,23 +2315,14 @@ impl Table {
|
||||
})
|
||||
}
|
||||
|
||||
/// Submit remote compaction and retain its durable job and actual result.
|
||||
/// Submit remote Optimize and retain its durable job and actual result.
|
||||
#[pyo3(signature = (data_options=None))]
|
||||
pub fn optimize_async<'py>(
|
||||
self_: PyRef<'py, Self>,
|
||||
data_options: Option<&Bound<'py, PyDict>>,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
let target_specified = data_options
|
||||
.map(|options| options.contains("target_rows_per_fragment"))
|
||||
.transpose()?
|
||||
.unwrap_or(false);
|
||||
let options = parse_data_options(data_options)?;
|
||||
let mut overrides =
|
||||
lancedb::table::optimize::OptimizeOverrides::try_from(options).infer_error()?;
|
||||
if !target_specified {
|
||||
overrides.target_rows_per_fragment = None;
|
||||
}
|
||||
let overrides = parse_optimize_options(data_options)?.into_remote_overrides()?;
|
||||
future_into_py(self_.py(), async move {
|
||||
let job = inner.optimize_async(overrides).await.infer_error()?;
|
||||
Ok(crate::job::Job::new_typed(job))
|
||||
@@ -2342,11 +2353,7 @@ impl Table {
|
||||
));
|
||||
}
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
let target_specified = data_options
|
||||
.map(|options| options.contains("target_rows_per_fragment"))
|
||||
.transpose()?
|
||||
.unwrap_or(false);
|
||||
let data_options = parse_data_options(data_options)?;
|
||||
let data_options = parse_optimize_options(data_options)?;
|
||||
let older_than = if let Some(ms) = cleanup_since_ms {
|
||||
if ms > i64::MAX as u64 {
|
||||
return Err(PyValueError::new_err(format!(
|
||||
@@ -2364,22 +2371,17 @@ impl Table {
|
||||
if rewrite_only {
|
||||
inner
|
||||
.optimize(lancedb::table::OptimizeAction::RewriteDataWithOptions {
|
||||
options: data_options,
|
||||
options: data_options.options,
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
} else {
|
||||
inner
|
||||
.optimize_full(data_options, older_than, None, delete_unverified)
|
||||
.optimize_full(data_options.options, older_than, None, delete_unverified)
|
||||
.await
|
||||
}
|
||||
} else {
|
||||
let mut overrides =
|
||||
lancedb::table::optimize::OptimizeOverrides::try_from(data_options)
|
||||
.infer_error()?;
|
||||
if !target_specified {
|
||||
overrides.target_rows_per_fragment = None;
|
||||
}
|
||||
let overrides = data_options.into_remote_overrides()?;
|
||||
if rewrite_only {
|
||||
inner.optimize(overrides).await
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user