mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
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:
@@ -332,6 +332,36 @@ by the jobs API.
|
||||
`estimated_remaining_time_millis` is a best-effort client-side estimate. It is
|
||||
omitted while a job is initializing, queued, or paused, and when there is no
|
||||
positive progress rate from two compatible samples.
|
||||
|
||||
### Inspect a slow Function worker
|
||||
|
||||
On a supported Enterprise server, Python's `Job.stack(worker_id)` and
|
||||
`await AsyncJob.stack(worker_id)` capture Python thread stacks from a running
|
||||
Function refresh worker. Rust provides `job.stack(worker_id).await?`.
|
||||
TypeScript does not yet expose this method. Stack inspection requires the
|
||||
system operate privilege.
|
||||
|
||||
Select a worker ID from the job's progress warnings or recorded events. For
|
||||
example, inspect a worker named in the current no-progress or slow-split warnings:
|
||||
|
||||
```python
|
||||
job = db.open_job(job_id)
|
||||
snapshot = job.progress() or {}
|
||||
warnings = snapshot.get("warnings", [])
|
||||
if warnings:
|
||||
evidence = job.stack(warnings[0]["worker_id"])
|
||||
print(evidence["status"], evidence["omitted_sessions"])
|
||||
for session in evidence["stacks"]:
|
||||
print(session["status"], session["captured_at_millis"])
|
||||
print(session["stack"], session["truncated"])
|
||||
```
|
||||
|
||||
`unavailable` and `unsupported` are explicit capture statuses; missing frames
|
||||
do not establish that a worker is healthy or finished. Captures are bounded and
|
||||
may reuse a recent sample. They contain Python frames without source text,
|
||||
locals or native frames. Local operations and SQL-backed query handles do not
|
||||
support stack inspection. For a worker that already timed out, inspect the
|
||||
recorded failure events for retained traceback evidence.
|
||||
*/}
|
||||
|
||||
## Embedded and Enterprise execution {#in-process}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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() })
|
||||
|
||||
@@ -90,6 +90,10 @@ pub(crate) trait JobHandle: Send + Sync {
|
||||
job_detail_not_supported("job timeline export")
|
||||
}
|
||||
|
||||
async fn stack(&self, _worker_id: &str) -> Result<Value> {
|
||||
job_detail_not_supported("worker stack capture")
|
||||
}
|
||||
|
||||
/// A printable report of recorded Function job metrics.
|
||||
async fn stats(&self) -> Result<Option<String>> {
|
||||
job_detail_not_supported("job statistics")
|
||||
@@ -536,6 +540,34 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// Capture Python thread stacks from a running Function worker.
|
||||
///
|
||||
/// Requires a server supporting stack inspection and system operate privilege.
|
||||
/// The JSON response reports capture availability per session, timestamps and
|
||||
/// truncation. Stacks exclude source text, locals and native frames. A server
|
||||
/// may reuse a recent capture to bound sampling overhead. Unsupported local
|
||||
/// operations return [`crate::Error::NotSupported`].
|
||||
///
|
||||
/// ```no_run
|
||||
/// # async fn inspect(job: &lancedb::job::Job) -> Result<(), Box<dyn std::error::Error>> {
|
||||
/// let evidence = job.stack("worker-id").await?;
|
||||
/// println!("{evidence}");
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub async fn stack(&self, worker_id: impl AsRef<str>) -> Result<Value> {
|
||||
let worker_id = worker_id.as_ref();
|
||||
if worker_id.is_empty() || worker_id.len() > 256 {
|
||||
return Err(Error::InvalidInput {
|
||||
message: "worker_id must contain 1 to 256 bytes".into(),
|
||||
});
|
||||
}
|
||||
match &self.inner {
|
||||
JobInner::Handle { handle, .. } => handle.stack(worker_id).await,
|
||||
JobInner::Completed(_) => job_detail_not_supported("worker stack capture"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch a printable run report for a server-side Function job.
|
||||
///
|
||||
/// The server report includes recorded phase timings, finishing-supervisor
|
||||
|
||||
@@ -261,6 +261,46 @@ impl<S: HttpSend> JobHandle for RemoteJob<S> {
|
||||
Ok(trace)
|
||||
}
|
||||
|
||||
async fn stack(&self, worker_id: &str) -> Result<serde_json::Value> {
|
||||
let request = self
|
||||
.client
|
||||
.post("/v1/jobs/stack")
|
||||
.json(&serde_json::json!({"job_id": self.job_id, "worker_id": worker_id}));
|
||||
let (request_id, response) = self.client.send(request).await?;
|
||||
let response = self.client.check_response(&request_id, response).await?;
|
||||
let body = response.text().await.err_to_http(request_id.clone())?;
|
||||
let evidence: serde_json::Value =
|
||||
serde_json::from_str(&body).map_err(|error| Error::Http {
|
||||
source: format!("failed to parse worker stack response: {error}").into(),
|
||||
request_id: request_id.clone(),
|
||||
status_code: None,
|
||||
})?;
|
||||
if evidence
|
||||
.get("worker_id")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
!= Some(worker_id)
|
||||
|| !matches!(
|
||||
evidence.get("status").and_then(serde_json::Value::as_str),
|
||||
Some("captured" | "unavailable" | "unsupported")
|
||||
)
|
||||
|| !evidence
|
||||
.get("stacks")
|
||||
.is_some_and(serde_json::Value::is_array)
|
||||
|| !evidence
|
||||
.get("execution_epoch")
|
||||
.is_some_and(serde_json::Value::is_i64)
|
||||
{
|
||||
return Err(Error::Http {
|
||||
source:
|
||||
"server response is not worker stack evidence; capture requires server support"
|
||||
.into(),
|
||||
request_id,
|
||||
status_code: None,
|
||||
});
|
||||
}
|
||||
Ok(evidence)
|
||||
}
|
||||
|
||||
async fn stats(&self) -> Result<Option<String>> {
|
||||
let request = self
|
||||
.client
|
||||
@@ -401,6 +441,59 @@ mod tests {
|
||||
include_str!("../../tests/fixtures/first_class_functions/v1/remote_unit_job.json");
|
||||
const MISSING_RESULT_JOB: &str = r#"{"job_state":"DONE"}"#;
|
||||
|
||||
#[tokio::test]
|
||||
async fn stack_preserves_availability_and_uses_the_selected_worker() {
|
||||
for status in ["captured", "unsupported", "unavailable"] {
|
||||
let client = client_with_handler(move |request| {
|
||||
assert_eq!(request.url().path(), "/v1/jobs/stack");
|
||||
let body: serde_json::Value =
|
||||
serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
body,
|
||||
serde_json::json!({"job_id":"job-1", "worker_id":"worker-1"})
|
||||
);
|
||||
http::Response::builder().status(200).body(serde_json::json!({
|
||||
"worker_id":"worker-1", "status":status, "execution_epoch":1, "stacks":[], "omitted_sessions":0
|
||||
}).to_string()).unwrap()
|
||||
});
|
||||
let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into())));
|
||||
assert_eq!(job.stack("worker-1").await.unwrap()["status"], status);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stack_rejects_unrelated_responses_and_preserves_authorization_errors() {
|
||||
for body in [
|
||||
"{}",
|
||||
r#"{"worker_id":"other","status":"captured","execution_epoch":1,"stacks":[]}"#,
|
||||
] {
|
||||
let client = client_with_handler(move |_| {
|
||||
http::Response::builder().status(200).body(body).unwrap()
|
||||
});
|
||||
assert!(matches!(
|
||||
RemoteJob::new(client, "job-1".into())
|
||||
.stack("worker-1")
|
||||
.await
|
||||
.unwrap_err(),
|
||||
crate::Error::Http { .. }
|
||||
));
|
||||
}
|
||||
let client = client_with_handler(|_| {
|
||||
http::Response::builder()
|
||||
.status(403)
|
||||
.body("access denied")
|
||||
.unwrap()
|
||||
});
|
||||
assert!(
|
||||
RemoteJob::new(client, "job-1".into())
|
||||
.stack("worker-1")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("403")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stats_reads_report_verbatim_and_preserves_unavailable_without_waiting() {
|
||||
let requests = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
@@ -324,6 +324,10 @@ impl<S: HttpSend> crate::job::JobHandle for FreshnessJob<S> {
|
||||
crate::job::JobHandle::timeline(&self.inner).await
|
||||
}
|
||||
|
||||
async fn stack(&self, worker_id: &str) -> Result<serde_json::Value> {
|
||||
crate::job::JobHandle::stack(&self.inner, worker_id).await
|
||||
}
|
||||
|
||||
async fn events(
|
||||
&self,
|
||||
request: crate::job::JobEventsRequest,
|
||||
@@ -409,6 +413,10 @@ impl<S: HttpSend> crate::job::JobHandle for MaterializedViewRefreshJob<S> {
|
||||
crate::job::JobHandle::timeline(&self.inner).await
|
||||
}
|
||||
|
||||
async fn stack(&self, worker_id: &str) -> Result<serde_json::Value> {
|
||||
crate::job::JobHandle::stack(&self.inner, worker_id).await
|
||||
}
|
||||
|
||||
async fn events(
|
||||
&self,
|
||||
request: crate::job::JobEventsRequest,
|
||||
|
||||
Reference in New Issue
Block a user