mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
feat(sdk): add durable compaction jobs with typed results
This commit is contained in:
@@ -726,6 +726,9 @@ class Table:
|
||||
async def update_field_metadata(
|
||||
self, updates: list[dict[str, Any]]
|
||||
) -> UpdateFieldMetadataResult: ...
|
||||
async def compact_async(
|
||||
self, compaction_options: Optional[Dict[str, Any]] = None
|
||||
) -> Job: ...
|
||||
async def optimize(
|
||||
self,
|
||||
*,
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Results of durable remote compaction jobs."""
|
||||
|
||||
from dataclasses import dataclass, fields
|
||||
import json
|
||||
from typing import Optional
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CompactionResult:
|
||||
"""Actual committed outcome of one remote compaction invocation.
|
||||
|
||||
``rows_failed`` counts planned live rows that were not committed, including
|
||||
partial progress. ``more_work`` means a bounded run left eligible work for
|
||||
another invocation. File/fragment counts are None if an older worker did
|
||||
not report them; they are never inferred from unrelated table versions.
|
||||
"""
|
||||
|
||||
partial_commit: bool
|
||||
rows_succeeded: int
|
||||
rows_failed: int
|
||||
completion_percentage: float
|
||||
more_work: bool = False
|
||||
files_added: Optional[int] = None
|
||||
files_removed: Optional[int] = None
|
||||
fragments_added: Optional[int] = None
|
||||
fragments_removed: Optional[int] = None
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, raw: str) -> "CompactionResult":
|
||||
"""Decode a server result, ignoring additive fields from newer servers."""
|
||||
value = json.loads(raw)
|
||||
names = {field.name for field in fields(cls)}
|
||||
return cls(**{key: item for key, item in value.items() if key in names})
|
||||
@@ -18,6 +18,7 @@ from lancedb.background_loop import LOOP
|
||||
from . import _lancedb
|
||||
from ._lancedb import JobDescription, JobFailureInfo, JobInfo, _append_doc_url
|
||||
from .functions import RefreshColumnResult
|
||||
from .compaction import CompactionResult
|
||||
from .remote.errors import HttpError, RetryError
|
||||
|
||||
T = TypeVar("T")
|
||||
@@ -698,4 +699,6 @@ def _typed_job(
|
||||
def _opened_job(inner: "_lancedb.Job") -> AsyncJob:
|
||||
if inner.job_type in ("function_refresh", "computed_refresh", "refresh_column"):
|
||||
return _typed_job(inner, RefreshColumnResult.from_json)
|
||||
if inner.job_type == "compact":
|
||||
return _typed_job(inner, CompactionResult.from_json)
|
||||
return AsyncJob(inner)
|
||||
|
||||
@@ -76,6 +76,7 @@ from ..table import (
|
||||
BlobMode,
|
||||
Branches,
|
||||
CompactionOptions,
|
||||
CompactionResult,
|
||||
IndexStatistics,
|
||||
Query,
|
||||
Table,
|
||||
@@ -1085,6 +1086,13 @@ class RemoteTable(Table):
|
||||
)
|
||||
pass
|
||||
|
||||
def compact_async(
|
||||
self, *, compaction_options: Optional[CompactionOptions] = None
|
||||
) -> Job[CompactionResult]:
|
||||
return Job(
|
||||
LOOP.run(self._table.compact_async(compaction_options=compaction_options))
|
||||
)
|
||||
|
||||
def optimize(
|
||||
self,
|
||||
*,
|
||||
|
||||
@@ -49,6 +49,7 @@ from .types import BlobMode
|
||||
from lancedb.arrow import peek_reader
|
||||
from lancedb.background_loop import LOOP, embedding_executor
|
||||
from lancedb.job import AsyncJob, Job, _typed_job
|
||||
from lancedb.compaction import CompactionResult
|
||||
from .dependencies import (
|
||||
_check_for_hugging_face,
|
||||
_check_for_lance,
|
||||
@@ -2999,6 +3000,33 @@ class Table(ABC):
|
||||
compaction for you automatically.
|
||||
"""
|
||||
|
||||
def compact_async(
|
||||
self, *, compaction_options: Optional[CompactionOptions] = None
|
||||
) -> Job[CompactionResult]:
|
||||
"""Submit remote compaction 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
|
||||
[CompactionOptions][lancedb.table.CompactionOptions].
|
||||
Requires a compatible remote server, table Ownership and parent Usage.
|
||||
Local and historical-version handles are unsupported. Existing
|
||||
``optimize()`` retains its return-on-submission behavior remotely.
|
||||
|
||||
``job.wait()`` waits for the actual rewrite and returns
|
||||
[CompactionResult][lancedb.compaction.CompactionResult]. Partial/bounded
|
||||
runs report uncommitted rows and ``more_work``; unknown file statistics
|
||||
are None. Servers without a result payload raise an error rather than
|
||||
returning fabricated zero statistics. Wait timeouts do not cancel work.
|
||||
Save ``job.id`` and reopen with ``db.open_job(id)``. Monitoring and
|
||||
cancellation use generic HTTP job APIs and their existing permissions.
|
||||
|
||||
>>> job = table.compact_async( # doctest: +SKIP
|
||||
... compaction_options={"target_rows_per_fragment": 1000})
|
||||
>>> result = job.wait() # doctest: +SKIP
|
||||
>>> print(result.rows_succeeded) # doctest: +SKIP
|
||||
"""
|
||||
raise NotImplementedError("compaction jobs are only supported on remote tables")
|
||||
|
||||
@abstractmethod
|
||||
def optimize(
|
||||
self,
|
||||
@@ -5477,6 +5505,13 @@ class LanceTable(Table):
|
||||
self.checkout_latest()
|
||||
return stats
|
||||
|
||||
def compact_async(
|
||||
self, *, compaction_options: Optional[CompactionOptions] = None
|
||||
) -> Job[CompactionResult]:
|
||||
return Job(
|
||||
LOOP.run(self._table.compact_async(compaction_options=compaction_options))
|
||||
)
|
||||
|
||||
def optimize(
|
||||
self,
|
||||
*,
|
||||
@@ -8824,6 +8859,19 @@ class AsyncTable:
|
||||
"""The branch this table handle is scoped to, or ``None`` for ``main``."""
|
||||
return self._inner.current_branch()
|
||||
|
||||
async def compact_async(
|
||||
self, *, compaction_options: Optional[CompactionOptions] = None
|
||||
) -> AsyncJob[CompactionResult]:
|
||||
"""Submit remote compaction; await the returned job for actual results.
|
||||
|
||||
See [Table.compact_async][lancedb.table.Table.compact_async] for options,
|
||||
permissions, completion semantics and compatibility requirements.
|
||||
"""
|
||||
return _typed_job(
|
||||
await self._inner.compact_async(compaction_options),
|
||||
CompactionResult.from_json,
|
||||
)
|
||||
|
||||
async def optimize(
|
||||
self,
|
||||
*,
|
||||
|
||||
@@ -7563,3 +7563,193 @@ def test_remote_data_prewarm_malformed_receipt_is_not_retried():
|
||||
with pytest.raises(Exception, match="inspect jobs before retrying"):
|
||||
table.prewarm_data_async()
|
||||
assert len(server.tickets) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"outcome",
|
||||
[
|
||||
"counts",
|
||||
"legacy",
|
||||
"partial",
|
||||
"bounded",
|
||||
"no_op",
|
||||
"missing",
|
||||
"FAILED",
|
||||
"CANCELLED",
|
||||
],
|
||||
)
|
||||
async def test_remote_compaction_job_result_and_reopen(asynchronous, outcome):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
polls = []
|
||||
result = {
|
||||
"partial_commit": False,
|
||||
"rows_succeeded": 12,
|
||||
"rows_failed": 0,
|
||||
"completion_percentage": 100.0,
|
||||
}
|
||||
if outcome == "counts":
|
||||
result.update(
|
||||
files_added=1, files_removed=3, fragments_added=1, fragments_removed=3
|
||||
)
|
||||
|
||||
if outcome == "partial":
|
||||
result.update(
|
||||
partial_commit=True,
|
||||
rows_succeeded=8,
|
||||
rows_failed=4,
|
||||
completion_percentage=100 * 8 / 12,
|
||||
)
|
||||
if outcome == "bounded":
|
||||
result.update(more_work=True)
|
||||
if outcome == "no_op":
|
||||
result.update(
|
||||
rows_succeeded=0,
|
||||
files_added=0,
|
||||
files_removed=0,
|
||||
fragments_added=0,
|
||||
fragments_removed=0,
|
||||
)
|
||||
|
||||
class Server(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.tickets = []
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.tickets.append(ticket.ticket)
|
||||
return flight.RecordBatchStream(pa.table({"job_id": ["compacting-job"]}))
|
||||
|
||||
def handler(request):
|
||||
if request.path != "/v1/jobs/describe":
|
||||
return _create_table_handler(request)
|
||||
body = json.loads(request.rfile.read(int(request.headers["Content-Length"])))
|
||||
assert body == {"job_id": "compacting-job"}
|
||||
polls.append(body)
|
||||
request.send_response(200)
|
||||
request.send_header("Content-Type", "application/json")
|
||||
request.end_headers()
|
||||
request.wfile.write(
|
||||
json.dumps(
|
||||
{
|
||||
"job_id": "compacting-job",
|
||||
"job_type": "compact",
|
||||
"job_state": outcome
|
||||
if outcome in ("FAILED", "CANCELLED")
|
||||
else "DONE",
|
||||
"result": None if outcome == "missing" else result,
|
||||
}
|
||||
).encode()
|
||||
)
|
||||
|
||||
server = Server()
|
||||
with _mock_remote_sql_connection(server, handler) as kwargs:
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(**kwargs)
|
||||
table = await db.create_table("test", [{"id": 1}])
|
||||
job = await table.compact_async(
|
||||
compaction_options={"target_rows_per_fragment": 100}
|
||||
)
|
||||
assert job.id == "compacting-job" and not polls
|
||||
if outcome in ("missing", "FAILED", "CANCELLED"):
|
||||
with pytest.raises(
|
||||
Exception,
|
||||
match={
|
||||
"missing": "did not contain a result",
|
||||
"FAILED": "failed",
|
||||
"CANCELLED": "cancel",
|
||||
}[outcome],
|
||||
):
|
||||
await job.wait()
|
||||
else:
|
||||
stats = await job.wait()
|
||||
reopened = await db.open_job(job.id)
|
||||
assert await reopened.wait() == stats
|
||||
else:
|
||||
db = lancedb.connect(**kwargs)
|
||||
table = db.create_table("test", [{"id": 1}])
|
||||
job = table.compact_async(
|
||||
compaction_options={"target_rows_per_fragment": 100}
|
||||
)
|
||||
assert job.id == "compacting-job" and not polls
|
||||
if outcome in ("missing", "FAILED", "CANCELLED"):
|
||||
with pytest.raises(
|
||||
Exception,
|
||||
match={
|
||||
"missing": "did not contain a result",
|
||||
"FAILED": "failed",
|
||||
"CANCELLED": "cancel",
|
||||
}[outcome],
|
||||
):
|
||||
job.wait()
|
||||
else:
|
||||
stats = job.wait()
|
||||
assert db.open_job(job.id).wait() == stats
|
||||
if outcome in ("counts", "legacy", "partial", "bounded", "no_op"):
|
||||
from lancedb.compaction import CompactionResult
|
||||
|
||||
assert isinstance(stats, CompactionResult)
|
||||
assert stats.rows_succeeded == (
|
||||
0 if outcome == "no_op" else 8 if outcome == "partial" else 12
|
||||
)
|
||||
assert stats.rows_failed == (4 if outcome == "partial" else 0)
|
||||
assert stats.partial_commit == (outcome == "partial")
|
||||
assert stats.more_work == (outcome == "bounded")
|
||||
assert stats.fragments_removed == (
|
||||
3 if outcome == "counts" else 0 if outcome == "no_op" else None
|
||||
)
|
||||
assert len(server.tickets) == 1
|
||||
assert b"OPTIMIZE" in server.tickets[0]
|
||||
assert b"target_rows_per_fragment = 100" in server.tickets[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ids", [[], [None], [""], ["a", "b"]])
|
||||
def test_remote_compaction_rejects_ambiguous_receipt_without_resubmission(ids):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
class Server(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.calls = 0
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.calls += 1
|
||||
return flight.RecordBatchStream(
|
||||
pa.table({"job_id": pa.array(ids, pa.string())})
|
||||
)
|
||||
|
||||
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.compact_async()
|
||||
assert server.calls == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", ["compact_async", "optimize"])
|
||||
@pytest.mark.parametrize(
|
||||
"option",
|
||||
["target_rows_per_fragment", "max_source_rows", "io_buffer_size", "batch_size"],
|
||||
)
|
||||
@pytest.mark.parametrize("value", [False, True])
|
||||
def test_remote_compaction_rejects_boolean_budgets_without_submitting(
|
||||
method, option, value
|
||||
):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
class UnusedServer(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.calls = 0
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.calls += 1
|
||||
raise AssertionError("boolean compaction settings must not submit SQL")
|
||||
|
||||
server = UnusedServer()
|
||||
with _mock_remote_table_with_sql(server) as table:
|
||||
with pytest.raises(ValueError, match="must be an integer, not a bool"):
|
||||
getattr(table, method)(compaction_options={option: value})
|
||||
assert server.calls == 0
|
||||
|
||||
@@ -898,6 +898,10 @@ impl Connection {
|
||||
job.into_typed::<RefreshColumnResult>().infer_error()?,
|
||||
))
|
||||
}
|
||||
Some("compact") => Ok(crate::job::Job::new_typed(
|
||||
job.into_typed::<lancedb::table::CompactionResult>()
|
||||
.infer_error()?,
|
||||
)),
|
||||
_ => Ok(crate::job::Job::new(job)),
|
||||
}
|
||||
})
|
||||
|
||||
@@ -370,6 +370,16 @@ fn parse_compaction_options(options: Option<&Bound<'_, PyDict>>) -> PyResult<Com
|
||||
|
||||
for (key, value) in options.iter() {
|
||||
let key: String = key.extract()?;
|
||||
// Python bool is an int subclass: never turn True into a one-row budget.
|
||||
if matches!(
|
||||
key.as_str(),
|
||||
"target_rows_per_fragment" | "max_source_rows" | "io_buffer_size" | "batch_size"
|
||||
) && value.is_instance_of::<PyBool>()
|
||||
{
|
||||
return Err(PyValueError::new_err(format!(
|
||||
"{key} must be an integer, not a bool"
|
||||
)));
|
||||
}
|
||||
match key.as_str() {
|
||||
"target_rows_per_fragment" => {
|
||||
parsed.target_rows_per_fragment = positive_u32(&value, &key)?
|
||||
@@ -2119,6 +2129,29 @@ impl Table {
|
||||
})
|
||||
}
|
||||
|
||||
/// Submit remote compaction and retain its durable job and actual result.
|
||||
#[pyo3(signature = (compaction_options=None))]
|
||||
pub fn compact_async<'py>(
|
||||
self_: PyRef<'py, Self>,
|
||||
compaction_options: Option<&Bound<'py, PyDict>>,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
let target_specified = compaction_options
|
||||
.map(|options| options.contains("target_rows_per_fragment"))
|
||||
.transpose()?
|
||||
.unwrap_or(false);
|
||||
let options = parse_compaction_options(compaction_options)?;
|
||||
let mut overrides =
|
||||
lancedb::table::optimize::CompactionOverrides::try_from(options).infer_error()?;
|
||||
if !target_specified {
|
||||
overrides.target_rows_per_fragment = None;
|
||||
}
|
||||
future_into_py(self_.py(), async move {
|
||||
let job = inner.compact_async(overrides).await.infer_error()?;
|
||||
Ok(crate::job::Job::new_typed(job))
|
||||
})
|
||||
}
|
||||
|
||||
/// Optimize the on-disk data by compacting and pruning old data, for better performance.
|
||||
#[pyo3(signature = (cleanup_since_ms=None, delete_unverified=None, compaction_options=None))]
|
||||
pub fn optimize<'py>(
|
||||
|
||||
Reference in New Issue
Block a user