feat: expose Function worker stack inspection (#5043)

Adds `Job::stack(worker_id)` in Rust and `Job.stack(worker_id)` /
`AsyncJob.stack(worker_id)` in Python for server-side Function jobs. The
response preserves capture availability, timestamps, truncation, and
session details; unsupported local or query handles retain their
existing unsupported-operation behavior. Refresh wrappers forward the
request to their tracked server job.

```python
evidence = job.stack("worker-id")
for session in evidence["stacks"]:
    print(session["status"], session["stack"])
```

Requires a server implementing `/v1/jobs/stack` and system operate
privilege. The API propagates authorization and transport errors without
waiting for job completion. Existing progress snapshots already preserve
server warning fields.

Includes mocked request/response and synchronous/asynchronous Python
coverage. Local builds and tests were intentionally skipped as
requested.
This commit is contained in:
Jack Ye
2026-11-17 02:54:18 -08:00
committed by GitHub
parent 57b20fb11d
commit ba4e3ef3f9
8 changed files with 257 additions and 0 deletions
+1
View File
@@ -449,6 +449,7 @@ class Job:
async def cancel(self) -> None: ...
async def refresh(self) -> None: ...
async def timeline(self) -> str: ...
async def stack(self, worker_id: str) -> str: ...
async def stats(self) -> Optional[str]: ...
async def events(
self,
+41
View File
@@ -4,6 +4,7 @@
"""Handles to asynchronous registry jobs, SQL queries, and local operations."""
import asyncio
import json
import logging
import reprlib
import time
@@ -486,6 +487,30 @@ class AsyncJob(Generic[T]):
description = self._inner._description if self._inner is not None else None
return getattr(description, name) if description is not None else None
async def stack(self, worker_id: str) -> dict[str, Any]:
"""Capture Python thread stacks from a running Function worker.
Requires server support and system operate privilege. The response has
``status``, ``worker_id``, ``execution_epoch`` and ``stacks``. Each session
reports its status, capture timestamp, Python frames and truncation.
``omitted_sessions`` counts sessions beyond the server's capture limit.
Captures exclude source text, locals and native frames; a recent capture
may be reused to bound overhead. Unsupported or unavailable captures
have an explicit status. Transport and authorization errors propagate.
Local operations and SQL query handles raise ``NotImplementedError``.
Timeout stack evidence remains in the job's failure events.
Examples
--------
>>> evidence = await job.stack("worker-id") # doctest: +SKIP
>>> print(evidence["stacks"]) # doctest: +SKIP
"""
if self._inner is None:
raise NotImplementedError(
"worker stacks require a server-side Function job"
)
return json.loads(await self._inner.stack(worker_id))
async def stats(self) -> Optional[str]:
"""Return a printable run report for this Function job.
@@ -736,6 +761,22 @@ class Job(Generic[T]):
def _field(self, name: str) -> Optional[Any]:
return getattr(self._inner, name) if self._inner is not None else None
def stack(self, worker_id: str) -> dict[str, Any]:
"""Capture Python thread stacks from a running Function worker.
See [AsyncJob.stack][lancedb.job.AsyncJob.stack] for availability,
permissions and response fields.
Examples
--------
>>> print(job.stack("worker-id")["stacks"]) # doctest: +SKIP
"""
if self._inner is None:
raise NotImplementedError(
"worker stacks require a server-side Function job"
)
return LOOP.run(self._inner.stack(worker_id))
def stats(self) -> Optional[str]:
"""Return a printable Function job run report.
+45
View File
@@ -1027,3 +1027,48 @@ async def test_export_timeline_reports_filesystem_errors(tmp_path):
)
with pytest.raises(FileNotFoundError):
await job.export_timeline(tmp_path / "missing" / "trace.json")
@pytest.mark.asyncio
@pytest.mark.parametrize("sync", [False, True])
async def test_stack_preserves_evidence_and_does_not_wait(sync):
evidence = {
"worker_id": "worker",
"status": "unavailable",
"execution_epoch": 1,
"stacks": [],
"omitted_sessions": 0,
}
inner = SimpleNamespace(
stack=AsyncMock(return_value=json.dumps(evidence)),
wait=AsyncMock(),
cancel=AsyncMock(),
)
job = AsyncJob(inner)
actual = (
await asyncio.to_thread(Job(job).stack, "worker")
if sync
else await job.stack("worker")
)
assert actual == evidence
inner.stack.assert_awaited_once_with("worker")
inner.wait.assert_not_awaited()
inner.cancel.assert_not_awaited()
@pytest.mark.asyncio
@pytest.mark.parametrize("sync", [False, True])
async def test_stack_propagates_errors_and_rejects_local_handles(sync):
error = RuntimeError("system operate privilege required")
job = AsyncJob(SimpleNamespace(stack=AsyncMock(side_effect=error)))
with pytest.raises(RuntimeError) as failure:
if sync:
await asyncio.to_thread(Job(job).stack, "worker")
else:
await job.stack("worker")
assert failure.value is error
with pytest.raises(NotImplementedError):
if sync:
Job(None).stack("worker")
else:
await AsyncJob(None).stack("worker")
+7
View File
@@ -159,6 +159,13 @@ impl Job {
})
}
pub fn stack(self_: PyRef<'_, Self>, worker_id: String) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner.clone();
future_into_py(self_.py(), async move {
Ok(inner.stack(worker_id).await.infer_error()?.to_string())
})
}
pub fn stats(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner.clone();
future_into_py(self_.py(), async move { inner.stats().await.infer_error() })