feat: profile Enterprise Function workers from official clients

This commit is contained in:
Jack Ye
2026-11-21 00:51:08 -08:00
committed by GitHub
parent 49dedd4329
commit 0511aed6e9
26 changed files with 2692 additions and 6 deletions
+17
View File
@@ -471,6 +471,23 @@ class Job:
async def refresh(self) -> None: ...
async def timeline(self) -> str: ...
async def stack(self, worker_id: str) -> str: ...
async def capture_profile(
self,
worker_id: str,
*,
kind: str = "cpu",
duration_seconds: Optional[float] = None,
session_slot: int = 0,
) -> str: ...
async def profile_status(self, profile_id: str) -> str: ...
async def wait_for_profile(
self,
profile_id: str,
*,
timeout_seconds: Optional[float] = None,
poll_interval_seconds: Optional[float] = None,
) -> str: ...
async def profile_artifact(self, profile_id: str) -> str: ...
async def stats(self) -> Optional[str]: ...
async def events(
self,
+215
View File
@@ -35,6 +35,7 @@ from .functions import RefreshColumnResult
from .compaction import CompactionResult
from .cleanup import CleanupResult
from .prewarm import PrewarmDataResult
from .profiling import FunctionProfile, FunctionProfileKind, FunctionProfileStatus
from .remote.errors import HttpError, RetryError
T = TypeVar("T")
@@ -46,6 +47,9 @@ __all__ = [
"JobFailureInfo",
"JobInfo",
"JobState",
"FunctionProfile",
"FunctionProfileKind",
"FunctionProfileStatus",
]
@@ -88,6 +92,14 @@ class JobState(str, Enum):
return self.value
def _profile_seconds(value: Optional[timedelta], name: str) -> Optional[float]:
if value is None:
return None
if not isinstance(value, timedelta):
raise TypeError(f"{name} must be a datetime.timedelta")
return value.total_seconds()
def _timeout_message(
job_id: Optional[str], timeout: timedelta, job_type: Optional[str]
) -> str:
@@ -700,6 +712,122 @@ class AsyncJob(Generic[T]):
)
return json.loads(await self._inner.stack(worker_id))
async def capture_profile(
self,
worker_id: str,
*,
kind: FunctionProfileKind = "cpu",
duration: Optional[timedelta] = None,
session_slot: int = 0,
) -> FunctionProfile:
"""Request a profile of one running Enterprise Function worker session.
Return an accepted capture identity without waiting for recording to
finish. The capture belongs to this existing refresh job. The server
pins its worker, Python session and execution epoch. System Operate
permission and server profiling support are required.
``kind`` is ``"cpu"`` for Python CPU samples, ``"memory"`` for Python
allocations retained at the end of capture, or ``"gpu"`` for PyTorch
CUDA activities. CPU and memory allow 1–30 seconds, defaulting to 10;
GPU allows 1–5 seconds, defaulting to 5. Slot zero is the first Python
session. GPU tracing requires initialized PyTorch CUDA/CUPTI. CPU
sampling requires readable per-thread procfs and is unavailable in
dedicated sandboxes. Captures add workload-dependent overhead.
Examples
--------
>>> from datetime import timedelta
>>> profile = await job.capture_profile( # doctest: +SKIP
... "worker-id", kind="gpu", duration=timedelta(seconds=2)
... )
>>> print(profile.profile_id) # doctest: +SKIP
"""
if self._inner is None:
raise NotImplementedError(
"Function profiling requires an Enterprise Function refresh job"
)
return FunctionProfile._from_json(
await self._inner.capture_profile(
worker_id,
kind=kind,
duration_seconds=_profile_seconds(duration, "duration"),
session_slot=session_slot,
)
)
async def profile_status(self, profile_id: str) -> FunctionProfile:
"""Fetch capture status and identity without waiting.
A failed capture returns ``status="failed"`` and the server's ``error``.
This does not change the parent job's status. Keep the profile ID to
retrieve retained evidence after the refresh finishes.
"""
if self._inner is None:
raise NotImplementedError(
"Function profiling requires an Enterprise Function refresh job"
)
return FunctionProfile._from_json(await self._inner.profile_status(profile_id))
async def wait_for_profile(
self,
profile_id: str,
*,
timeout: Optional[timedelta] = None,
poll_interval: Optional[timedelta] = None,
) -> FunctionProfile:
"""Wait for a capture independently of the parent Function refresh.
Defaults to a 60-second timeout and two seconds between status requests.
Set ``poll_interval`` to change the polling cadence. The timeout includes
HTTP requests and sleeps. It raises ``TimeoutError`` without cancelling
either the capture or the refresh; keep the ID to wait again. A failed
capture raises ``RuntimeError`` with the server's reason. Use
``profile_status`` to inspect a failed capture's typed metadata.
"""
if self._inner is None:
raise NotImplementedError(
"Function profiling requires an Enterprise Function refresh job"
)
return FunctionProfile._from_json(
await self._inner.wait_for_profile(
profile_id,
timeout_seconds=_profile_seconds(timeout, "timeout"),
poll_interval_seconds=_profile_seconds(poll_interval, "poll_interval"),
)
)
async def profile_artifact(self, profile_id: str) -> dict[str, Any]:
"""Retrieve the actual JSON for a completed capture.
CPU artifacts use speedscope, Python allocations use tracemalloc, and
GPU artifacts use Chrome Trace Event JSON. Truncation metadata is
preserved. The server retains up to eight captures per job for at most
an hour, or until job scratch is reclaimed or archived. Permission,
expired-artifact and unsupported-server errors propagate to the caller.
"""
if self._inner is None:
raise NotImplementedError(
"Function profiling requires an Enterprise Function refresh job"
)
return json.loads(await self._inner.profile_artifact(profile_id))
async def export_profile(self, profile_id: str, path: str | PathLike[str]) -> None:
"""Write a completed capture's actual JSON to a file.
The destination is overwritten only after retrieval succeeds. Export a
CPU capture to a speedscope file, or a GPU capture to a trace file for
Perfetto. GPU kernel/transfer durations may overlap and are not GPU
utilization. Python operator attribution and GPU allocation stacks are
outside the GPU trace format.
"""
if self._inner is None:
raise NotImplementedError(
"Function profiling requires an Enterprise Function refresh job"
)
artifact = await self._inner.profile_artifact(profile_id)
await asyncio.to_thread(Path(path).write_text, artifact, encoding="utf-8")
async def stats(self) -> Optional[str]:
"""Return a printable run report for this Function job.
@@ -1112,6 +1240,93 @@ class Job(Generic[T]):
)
return LOOP.run(self._inner.stack(worker_id))
def capture_profile(
self,
worker_id: str,
*,
kind: FunctionProfileKind = "cpu",
duration: Optional[timedelta] = None,
session_slot: int = 0,
) -> FunctionProfile:
"""Request a profile of a running Enterprise Function worker session.
See [AsyncJob.capture_profile][lancedb.job.AsyncJob.capture_profile] for
kinds, recording windows, permissions and runtime requirements.
>>> from datetime import timedelta
>>> profile = job.capture_profile( # doctest: +SKIP
... "worker-id", kind="cpu", duration=timedelta(seconds=10)
... )
>>> job.wait_for_profile(profile.profile_id) # doctest: +SKIP
>>> job.export_profile( # doctest: +SKIP
... profile.profile_id, "cpu.speedscope.json"
... )
"""
if self._inner is None:
raise NotImplementedError(
"Function profiling requires an Enterprise Function refresh job"
)
return LOOP.run(
self._inner.capture_profile(
worker_id, kind=kind, duration=duration, session_slot=session_slot
)
)
def profile_status(self, profile_id: str) -> FunctionProfile:
"""Fetch capture status, including retained captures after refresh.
See [AsyncJob.profile_status][lancedb.job.AsyncJob.profile_status].
"""
if self._inner is None:
raise NotImplementedError(
"Function profiling requires an Enterprise Function refresh job"
)
return LOOP.run(self._inner.profile_status(profile_id))
def wait_for_profile(
self,
profile_id: str,
*,
timeout: Optional[timedelta] = None,
poll_interval: Optional[timedelta] = None,
) -> FunctionProfile:
"""Wait for a capture with a configurable timeout and polling cadence.
See [AsyncJob.wait_for_profile][lancedb.job.AsyncJob.wait_for_profile].
A client timeout never cancels the capture or parent refresh job.
"""
if self._inner is None:
raise NotImplementedError(
"Function profiling requires an Enterprise Function refresh job"
)
return LOOP.run(
self._inner.wait_for_profile(
profile_id, timeout=timeout, poll_interval=poll_interval
)
)
def profile_artifact(self, profile_id: str) -> dict[str, Any]:
"""Retrieve a completed capture's actual JSON, preserving its format.
See [AsyncJob.profile_artifact][lancedb.job.AsyncJob.profile_artifact].
"""
if self._inner is None:
raise NotImplementedError(
"Function profiling requires an Enterprise Function refresh job"
)
return LOOP.run(self._inner.profile_artifact(profile_id))
def export_profile(self, profile_id: str, path: str | PathLike[str]) -> None:
"""Write a retained capture's JSON after successful retrieval.
See [AsyncJob.export_profile][lancedb.job.AsyncJob.export_profile].
"""
if self._inner is None:
raise NotImplementedError(
"Function profiling requires an Enterprise Function refresh job"
)
return LOOP.run(self._inner.export_profile(profile_id, path))
def stats(self) -> Optional[str]:
"""Return a printable Function job run report.
+49
View File
@@ -0,0 +1,49 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
"""Typed snapshots of on-demand Enterprise Function worker captures."""
import json
from dataclasses import dataclass
from typing import Literal, Optional
FunctionProfileKind = Literal["cpu", "gpu", "memory"]
FunctionProfileStatus = Literal["pending", "capturing", "complete", "failed"]
__all__ = ["FunctionProfile", "FunctionProfileKind", "FunctionProfileStatus"]
@dataclass(frozen=True)
class FunctionProfile:
"""A capture's identity, current status and artifact retention bounds.
Retain ``profile_id`` to retrieve the capture through the parent Job,
including after its refresh completes. ``status`` and ``error`` describe
the capture independently of the parent refresh job. Timestamp fields are
milliseconds since the Unix epoch. ``expires_at_millis`` is an upper bound:
the server may reclaim job scratch or evict an older capture sooner.
CPU evidence contains Python stacks weighted by thread CPU time. Memory
evidence contains Python allocations made during capture and retained at
its end. GPU evidence contains PyTorch CUDA activities; it excludes Python
operator attribution and GPU allocation stacks.
"""
profile_id: str
job_id: str
worker_id: str
execution_epoch: int
session_slot: int
kind: FunctionProfileKind
duration_seconds: float
status: FunctionProfileStatus
requested_at_millis: int
deadline_at_millis: int
expires_at_millis: int
completed_at_millis: Optional[int] = None
error: Optional[str] = None
artifact_id: Optional[str] = None
@classmethod
def _from_json(cls, value: str) -> "FunctionProfile":
return cls(**json.loads(value))
+63
View File
@@ -1353,3 +1353,66 @@ async def test_prewarm_progress_bar_preserves_unknown_and_zero_totals(
assert bar.n == 0
assert bar.total == (0 if known_empty else None)
assert bar.unit == " executors"
@pytest.mark.asyncio
@pytest.mark.parametrize("sync", [False, True])
async def test_profile_wait_preserves_timeout_and_never_waits_or_cancels_parent(sync):
error = TimeoutError("capture and refresh continue")
inner = SimpleNamespace(
wait_for_profile=AsyncMock(side_effect=error),
wait=AsyncMock(),
cancel=AsyncMock(),
)
job = AsyncJob(inner)
kwargs = {
"timeout": timedelta(milliseconds=50),
"poll_interval": timedelta(seconds=5),
}
with pytest.raises(TimeoutError) as caught:
if sync:
await asyncio.to_thread(Job(job).wait_for_profile, "profile-1", **kwargs)
else:
await job.wait_for_profile("profile-1", **kwargs)
assert caught.value is error
inner.wait_for_profile.assert_awaited_once_with(
"profile-1", timeout_seconds=0.05, poll_interval_seconds=5.0
)
inner.wait.assert_not_awaited()
inner.cancel.assert_not_awaited()
@pytest.mark.asyncio
@pytest.mark.parametrize("sync", [False, True])
async def test_profile_export_failure_preserves_destination_and_server_error(
sync, tmp_path
):
error = HttpError("403: System Operate required", "request-1", 403)
inner = SimpleNamespace(profile_artifact=AsyncMock(side_effect=error))
job = AsyncJob(inner)
path = tmp_path / "profile.json"
path.write_text("previous capture")
with pytest.raises(HttpError) as caught:
if sync:
await asyncio.to_thread(Job(job).export_profile, "profile-1", path)
else:
await job.export_profile("profile-1", path)
assert caught.value is error
assert path.read_text() == "previous capture"
@pytest.mark.asyncio
@pytest.mark.parametrize(
"method,args",
[
("capture_profile", ("worker-1",)),
("profile_status", ("profile-1",)),
("wait_for_profile", ("profile-1",)),
("profile_artifact", ("profile-1",)),
],
)
async def test_function_profiles_reject_embedded_handles(method, args):
with pytest.raises(NotImplementedError, match="Enterprise Function refresh job"):
await getattr(AsyncJob(None), method)(*args)
with pytest.raises(NotImplementedError, match="Enterprise Function refresh job"):
getattr(Job(None), method)(*args)
+139
View File
@@ -9115,3 +9115,142 @@ async def test_paged_function_errors_retain_history_and_expose_continuation(
with pytest.raises(ValueError, match="current failures"):
errors.rows()
assert received == [{"job_id": "attempt-1", "page_token": "", "history": True}]
@pytest.mark.asyncio
@pytest.mark.parametrize("sync_api", [False, True])
@pytest.mark.parametrize("kind", ["cpu", "memory", "gpu"])
@pytest.mark.parametrize("submitted_job", [False, True])
async def test_function_profile_capture_wait_and_retained_export(
sync_api, kind, submitted_job, tmp_path
):
state = {"polls": 0, "finished": False}
paths = []
profile = {
"profile_id": "profile-1",
"job_id": "job-1",
"worker_id": "worker-1",
"execution_epoch": 3,
"session_slot": 2,
"kind": kind,
"duration_seconds": 2,
"status": "pending",
"requested_at_millis": 1000,
"deadline_at_millis": 46000,
"expires_at_millis": 3601000,
"completed_at_millis": None,
"error": None,
"artifact_id": None,
}
artifacts = {
"cpu": {
"$schema": "https://www.speedscope.app/file-format-schema.json",
"shared": {"frames": [{"name": "work"}]},
"profiles": [],
},
"memory": {
"format": "lancedb.tracemalloc.v1",
"allocations": [{"size_bytes": 4096}],
"truncated": False,
},
"gpu": {
"format": "lancedb.cuda.v1",
"traceEvents": [{"name": "compute", "ph": "X", "ts": 10, "dur": 2}],
"truncated": True,
},
}
def handler(request):
paths.append(request.path)
assert request.headers["x-api-key"] == "fake"
assert request.headers["x-lancedb-database"] == "dev"
length = int(request.headers.get("Content-Length", 0))
body = json.loads(request.rfile.read(length)) if length else {}
if request.path == "/v1/table/test/describe/":
result = {"version": 1, "schema": {"fields": []}}
elif request.path == "/v1/table/test/backfill_column":
assert body["column"] == "result"
result = {"job_id": "job-1"}
elif request.path == "/v1/jobs/describe":
result = {
"job_id": "job-1",
"job_type": "function_refresh",
"job_state": "DONE" if state["finished"] else "IN_PROGRESS",
}
elif request.path == "/v1/jobs/profile/capture":
assert body == {
"job_id": "job-1",
"worker_id": "worker-1",
"session_slot": 2,
"kind": kind,
"duration_seconds": 2.0,
}
result = profile
elif request.path == "/v1/jobs/profile/status":
assert body == {"job_id": "job-1", "profile_id": "profile-1"}
state["polls"] += 1
result = dict(
profile,
status="complete" if state["polls"] > 1 else "capturing",
artifact_id="profile-1" if state["polls"] > 1 else None,
)
elif request.path == "/v1/jobs/profile/artifact":
assert body == {"job_id": "job-1", "profile_id": "profile-1"}
result = artifacts[kind]
else:
raise AssertionError(f"Unexpected request: {request.path}")
request.send_response(
200 if request.path != "/v1/jobs/profile/capture" else 202
)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(json.dumps(result).encode())
async def exercise(db):
async def invoke(function, *args, **kwargs):
if sync_api:
return await asyncio.to_thread(function, *args, **kwargs)
return await function(*args, **kwargs)
if submitted_job:
table = await invoke(db.open_table, "test")
job = await invoke(table.refresh_column_async, "result")
await invoke(job.refresh)
else:
job = await invoke(db.open_job, "job-1")
capture = await invoke(
job.capture_profile,
"worker-1",
kind=kind,
duration=timedelta(seconds=2),
session_slot=2,
)
assert capture.profile_id == "profile-1"
assert capture.worker_id == "worker-1"
assert capture.session_slot == 2
assert capture.execution_epoch == 3
assert capture.status == "pending"
completed = await invoke(
job.wait_for_profile,
capture.profile_id,
timeout=timedelta(seconds=2),
poll_interval=timedelta(milliseconds=10),
)
assert completed.status == "complete"
assert job.state() == "running"
state["finished"] = True
await invoke(job.refresh)
assert job.state() == "finished"
assert await invoke(job.profile_artifact, capture.profile_id) == artifacts[kind]
path = tmp_path / "profile.json"
await invoke(job.export_profile, capture.profile_id, path)
assert json.loads(path.read_text()) == artifacts[kind]
assert paths.count("/v1/jobs/describe") == 2
assert not any(path.endswith("/cancel") for path in paths)
if sync_api:
with mock_lancedb_connection(handler) as db:
await exercise(db)
else:
async with mock_lancedb_connection_async(handler) as db:
await exercise(db)