mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
feat: profile Enterprise Function workers from official clients
This commit is contained in:
@@ -247,6 +247,43 @@ Request cancellation. Cancelling a finished operation is a no-op.
|
||||
|
||||
***
|
||||
|
||||
### captureProfile()
|
||||
|
||||
```ts
|
||||
captureProfile(workerId, options): Promise<FunctionProfile>
|
||||
```
|
||||
|
||||
Request a profile of a running Enterprise Function worker session.
|
||||
Returns the accepted identity without waiting for recording to finish.
|
||||
Requires System Operate permission and server profiling support. The server
|
||||
pins the worker, Python session and execution epoch. One capture per job
|
||||
can be active. Captures add workload-dependent overhead.
|
||||
|
||||
GPU tracing requires initialized PyTorch CUDA/CUPTI. CPU sampling requires
|
||||
readable per-thread procfs and is unavailable in dedicated sandboxes.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **workerId**: `string`
|
||||
|
||||
* **options**: [`FunctionProfileOptions`](../interfaces/FunctionProfileOptions.md) = `{}`
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<[`FunctionProfile`](../interfaces/FunctionProfile.md)>
|
||||
|
||||
#### Example
|
||||
|
||||
```ts
|
||||
const profile = await job.captureProfile("worker-id", {
|
||||
kind: "gpu", durationSeconds: 2,
|
||||
});
|
||||
await job.waitForProfile(profile.profileId, { timeoutMs: 60_000 });
|
||||
await job.exportProfile(profile.profileId, "gpu.trace.json");
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### events()
|
||||
|
||||
```ts
|
||||
@@ -276,6 +313,29 @@ per fragment. `filter` is a SQL-like expression over the `state`,
|
||||
|
||||
***
|
||||
|
||||
### exportProfile()
|
||||
|
||||
```ts
|
||||
exportProfile(profileId, path): Promise<void>
|
||||
```
|
||||
|
||||
Write a completed capture's JSON after successful retrieval. Open CPU
|
||||
exports in speedscope and GPU exports in Perfetto. GPU activity durations
|
||||
can overlap and are not utilization; Python operator attribution and GPU
|
||||
allocation stacks are excluded. Filesystem errors propagate to the caller.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **profileId**: `string`
|
||||
|
||||
* **path**: `string`
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<`void`>
|
||||
|
||||
***
|
||||
|
||||
### history()
|
||||
|
||||
```ts
|
||||
@@ -294,6 +354,48 @@ Walk retained history one page at a time using the server's continuation.
|
||||
|
||||
***
|
||||
|
||||
### profileArtifact()
|
||||
|
||||
```ts
|
||||
profileArtifact(profileId): Promise<Record<string, unknown>>
|
||||
```
|
||||
|
||||
Retrieve a completed capture's actual JSON: speedscope for CPU,
|
||||
tracemalloc for Python allocations, or Chrome Trace Event JSON for GPU.
|
||||
Truncation flags are preserved. Retention is at most one hour and eight
|
||||
captures per job, until earlier scratch reclamation or archival.
|
||||
Permission, expired-artifact and unsupported-server errors propagate.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **profileId**: `string`
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<`Record`<`string`, `unknown`>>
|
||||
|
||||
***
|
||||
|
||||
### profileStatus()
|
||||
|
||||
```ts
|
||||
profileStatus(profileId): Promise<FunctionProfile>
|
||||
```
|
||||
|
||||
Fetch capture identity and status, including retained lookup after refresh.
|
||||
Failed captures return status "failed" with the server's error reason.
|
||||
This never changes the parent job's cached state.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **profileId**: `string`
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<[`FunctionProfile`](../interfaces/FunctionProfile.md)>
|
||||
|
||||
***
|
||||
|
||||
### progress()
|
||||
|
||||
```ts
|
||||
@@ -422,3 +524,26 @@ can also be reopened with `Connection.openJob`; query IDs cannot.
|
||||
```ts
|
||||
const result = await job.wait({ timeoutMs: 60_000, onProgress: console.log });
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### waitForProfile()
|
||||
|
||||
```ts
|
||||
waitForProfile(profileId, options): Promise<FunctionProfile>
|
||||
```
|
||||
|
||||
Wait for a capture with a configurable timeout and polling cadence.
|
||||
Defaults to 60 seconds with two seconds between requests. A timeout stops
|
||||
only this wait; the capture and Function refresh continue. A failed capture
|
||||
rejects with its server-reported reason. Keep its ID to wait again.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **profileId**: `string`
|
||||
|
||||
* **options**: [`FunctionProfileWaitOptions`](../interfaces/FunctionProfileWaitOptions.md) = `{}`
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<[`FunctionProfile`](../interfaces/FunctionProfile.md)>
|
||||
|
||||
@@ -109,6 +109,9 @@
|
||||
- [FunctionErrorRecord](interfaces/FunctionErrorRecord.md)
|
||||
- [FunctionErrors](interfaces/FunctionErrors.md)
|
||||
- [FunctionErrorsOptions](interfaces/FunctionErrorsOptions.md)
|
||||
- [FunctionProfile](interfaces/FunctionProfile.md)
|
||||
- [FunctionProfileOptions](interfaces/FunctionProfileOptions.md)
|
||||
- [FunctionProfileWaitOptions](interfaces/FunctionProfileWaitOptions.md)
|
||||
- [FunctionRefreshPlanningConfig](interfaces/FunctionRefreshPlanningConfig.md)
|
||||
- [FunctionRefreshPodResources](interfaces/FunctionRefreshPodResources.md)
|
||||
- [FunctionRetryPolicy](interfaces/FunctionRetryPolicy.md)
|
||||
@@ -195,6 +198,8 @@
|
||||
- [DeltaVersion](type-aliases/DeltaVersion.md)
|
||||
- [ExprLike](type-aliases/ExprLike.md)
|
||||
- [FieldLike](type-aliases/FieldLike.md)
|
||||
- [FunctionProfileKind](type-aliases/FunctionProfileKind.md)
|
||||
- [FunctionProfileStatus](type-aliases/FunctionProfileStatus.md)
|
||||
- [IntoSql](type-aliases/IntoSql.md)
|
||||
- [IntoVector](type-aliases/IntoVector.md)
|
||||
- [JobProgressCallback](type-aliases/JobProgressCallback.md)
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / FunctionProfile
|
||||
|
||||
# Interface: FunctionProfile
|
||||
|
||||
A capture identity and status snapshot. Keep profileId for retained lookup
|
||||
after the Function refresh completes. Timestamp fields are epoch milliseconds.
|
||||
|
||||
## Properties
|
||||
|
||||
### artifactId
|
||||
|
||||
```ts
|
||||
readonly artifactId: null | string;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### completedAtMillis
|
||||
|
||||
```ts
|
||||
readonly completedAtMillis: null | number;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### deadlineAtMillis
|
||||
|
||||
```ts
|
||||
readonly deadlineAtMillis: number;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### durationSeconds
|
||||
|
||||
```ts
|
||||
readonly durationSeconds: number;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### error
|
||||
|
||||
```ts
|
||||
readonly error: null | string;
|
||||
```
|
||||
|
||||
The server's capture failure reason; this is not a refresh job failure.
|
||||
|
||||
***
|
||||
|
||||
### executionEpoch
|
||||
|
||||
```ts
|
||||
readonly executionEpoch: number;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### expiresAtMillis
|
||||
|
||||
```ts
|
||||
readonly expiresAtMillis: number;
|
||||
```
|
||||
|
||||
Upper retention bound; job scratch reclamation can remove artifacts sooner.
|
||||
|
||||
***
|
||||
|
||||
### jobId
|
||||
|
||||
```ts
|
||||
readonly jobId: string;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### kind
|
||||
|
||||
```ts
|
||||
readonly kind: FunctionProfileKind;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### profileId
|
||||
|
||||
```ts
|
||||
readonly profileId: string;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### requestedAtMillis
|
||||
|
||||
```ts
|
||||
readonly requestedAtMillis: number;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### sessionSlot
|
||||
|
||||
```ts
|
||||
readonly sessionSlot: number;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### status
|
||||
|
||||
```ts
|
||||
readonly status: FunctionProfileStatus;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### workerId
|
||||
|
||||
```ts
|
||||
readonly workerId: string;
|
||||
```
|
||||
@@ -0,0 +1,39 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / FunctionProfileOptions
|
||||
|
||||
# Interface: FunctionProfileOptions
|
||||
|
||||
Options for requesting a Function worker capture.
|
||||
|
||||
## Properties
|
||||
|
||||
### durationSeconds?
|
||||
|
||||
```ts
|
||||
optional durationSeconds: number;
|
||||
```
|
||||
|
||||
1–30 seconds for CPU/memory, default 10; 1–5 for GPU, default 5.
|
||||
|
||||
***
|
||||
|
||||
### kind?
|
||||
|
||||
```ts
|
||||
optional kind: FunctionProfileKind;
|
||||
```
|
||||
|
||||
CPU samples, retained Python allocations, or PyTorch CUDA activities.
|
||||
|
||||
***
|
||||
|
||||
### sessionSlot?
|
||||
|
||||
```ts
|
||||
optional sessionSlot: number;
|
||||
```
|
||||
|
||||
Python execution session within the worker; default zero.
|
||||
@@ -0,0 +1,29 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / FunctionProfileWaitOptions
|
||||
|
||||
# Interface: FunctionProfileWaitOptions
|
||||
|
||||
Client-side controls while waiting for a Function worker capture.
|
||||
|
||||
## Properties
|
||||
|
||||
### pollIntervalMs?
|
||||
|
||||
```ts
|
||||
optional pollIntervalMs: number;
|
||||
```
|
||||
|
||||
Delay between status requests; defaults to 2,000 ms and must be positive.
|
||||
|
||||
***
|
||||
|
||||
### timeoutMs?
|
||||
|
||||
```ts
|
||||
optional timeoutMs: number;
|
||||
```
|
||||
|
||||
Maximum wait including HTTP requests and sleeps; defaults to 60,000 ms.
|
||||
@@ -0,0 +1,13 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / FunctionProfileKind
|
||||
|
||||
# Type Alias: FunctionProfileKind
|
||||
|
||||
```ts
|
||||
type FunctionProfileKind: "cpu" | "gpu" | "memory";
|
||||
```
|
||||
|
||||
Evidence collected from one Function worker's Python execution session.
|
||||
@@ -0,0 +1,13 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / FunctionProfileStatus
|
||||
|
||||
# Type Alias: FunctionProfileStatus
|
||||
|
||||
```ts
|
||||
type FunctionProfileStatus: "pending" | "capturing" | "complete" | "failed";
|
||||
```
|
||||
|
||||
A capture's lifecycle, independent of its parent refresh job.
|
||||
@@ -755,6 +755,12 @@ with BlobReader(read_range, len(payload)) as reader:
|
||||
|
||||
::: lancedb.job.JobFailureInfo
|
||||
|
||||
::: lancedb.profiling.FunctionProfile
|
||||
|
||||
::: lancedb.profiling.FunctionProfileKind
|
||||
|
||||
::: lancedb.profiling.FunctionProfileStatus
|
||||
|
||||
::: lancedb.sql.Query
|
||||
|
||||
::: lancedb.sql.AsyncQuery
|
||||
|
||||
@@ -691,6 +691,118 @@ support stack inspection. For a worker that already timed out, inspect the
|
||||
recorded failure events for retained traceback evidence.
|
||||
*/}
|
||||
|
||||
## Profile a Function worker {#profiling}
|
||||
|
||||
On a supporting Enterprise server, request a CPU profile, retained Python
|
||||
allocation profile, or PyTorch CUDA activity trace through the existing Job
|
||||
handle. A capture is a diagnostic operation on that refresh job. It records
|
||||
one selected worker's Python execution session and pins its execution epoch.
|
||||
Choose a worker ID from the job's recorded events or the Console.
|
||||
|
||||
<CodeGroup>
|
||||
```python Synchronous Python icon="python"
|
||||
from datetime import timedelta
|
||||
|
||||
job = db.open_job(refresh_job_id)
|
||||
profile = job.capture_profile(
|
||||
worker_id,
|
||||
kind="cpu",
|
||||
duration=timedelta(seconds=10),
|
||||
session_slot=0,
|
||||
)
|
||||
print(profile.profile_id, profile.status)
|
||||
job.wait_for_profile(
|
||||
profile.profile_id,
|
||||
timeout=timedelta(seconds=60),
|
||||
poll_interval=timedelta(seconds=5),
|
||||
)
|
||||
job.export_profile(profile.profile_id, "cpu.speedscope.json")
|
||||
```
|
||||
|
||||
```python Asynchronous Python icon="python"
|
||||
from datetime import timedelta
|
||||
|
||||
job = await async_db.open_job(refresh_job_id)
|
||||
profile = await job.capture_profile(
|
||||
worker_id, kind="gpu", duration=timedelta(seconds=2)
|
||||
)
|
||||
await job.wait_for_profile(profile.profile_id, timeout=timedelta(seconds=60))
|
||||
await job.export_profile(profile.profile_id, "gpu.trace.json")
|
||||
```
|
||||
|
||||
```typescript TypeScript icon="js"
|
||||
const job = await db.openJob(refreshJobId);
|
||||
const profile = await job.captureProfile(workerId, {
|
||||
kind: "gpu",
|
||||
durationSeconds: 2,
|
||||
sessionSlot: 0,
|
||||
});
|
||||
console.log(profile.profileId, profile.status);
|
||||
await job.waitForProfile(profile.profileId, {
|
||||
timeoutMs: 60_000,
|
||||
pollIntervalMs: 5_000,
|
||||
});
|
||||
await job.exportProfile(profile.profileId, "gpu.trace.json");
|
||||
```
|
||||
|
||||
```rust Rust icon="rust"
|
||||
use std::time::Duration;
|
||||
use lancedb::job::{
|
||||
FunctionProfileKind, FunctionProfileOptions, FunctionProfileWaitOptions,
|
||||
};
|
||||
|
||||
let job = db.open_job(refresh_job_id).await?;
|
||||
let profile = job.capture_profile(
|
||||
worker_id,
|
||||
FunctionProfileOptions::new(FunctionProfileKind::Cpu)
|
||||
.duration(Duration::from_secs(10)),
|
||||
).await?;
|
||||
job.wait_for_profile(
|
||||
&profile.profile_id,
|
||||
FunctionProfileWaitOptions::new()
|
||||
.timeout(Duration::from_secs(60))
|
||||
.poll_interval(Duration::from_secs(5)),
|
||||
).await?;
|
||||
let artifact = job.profile_artifact(&profile.profile_id).await?;
|
||||
std::fs::write("cpu.speedscope.json", serde_json::to_vec(&artifact)?)?;
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
| Kind | Evidence and export | Recording window |
|
||||
| --- | --- | --- |
|
||||
| `cpu` | Python stack samples weighted by thread CPU time; speedscope JSON | 1–30 seconds, default 10 |
|
||||
| `memory` | Python allocations made during capture and retained at its end; tracemalloc JSON | 1–30 seconds, default 10 |
|
||||
| `gpu` | PyTorch CUDA kernels, copies, memset and available CUDA host APIs; Chrome Trace Event JSON | 1–5 seconds, default 5 |
|
||||
|
||||
Captures require System Operate permission and a running Function refresh with
|
||||
an available worker session. Slot zero selects the first Python session.
|
||||
Only one capture per job can be active. The capture window excludes supervisor
|
||||
dispatch delay. CPU sampling needs readable per-thread procfs and is unavailable
|
||||
in dedicated sandboxes. GPU tracing needs already initialized PyTorch CUDA with
|
||||
CUPTI support. Captures add workload-dependent time and memory overhead.
|
||||
|
||||
`wait_for_profile` / `waitForProfile` defaults to a 60-second timeout and two
|
||||
seconds between status requests. Both are configurable. A timeout stops only
|
||||
that client's wait; the capture and parent refresh keep running. Keep the
|
||||
profile ID to wait again. A failed capture raises an error with the server's
|
||||
reason. Use `profile_status` / `profileStatus` to inspect its typed status and
|
||||
failure details independently of the refresh job's status.
|
||||
|
||||
Retrieve a completed capture with `profile_artifact` / `profileArtifact` to get
|
||||
the actual JSON in memory, or export it to a file as above. Files are overwritten
|
||||
only after retrieval succeeds. Retained lookup works after refresh completion:
|
||||
reopen the parent job, then use the saved profile ID. Retention is at most one
|
||||
hour and eight captures per job, until earlier scratch reclamation or archival.
|
||||
Permission, unsupported-session, expired-artifact and unsupported-server errors
|
||||
are surfaced by the normal client error handling.
|
||||
|
||||
Open CPU exports in speedscope and GPU exports in Perfetto. Truncation flags
|
||||
remain in the downloaded JSON. CUDA durations can overlap across streams, so
|
||||
their sum is not elapsed time or GPU utilization. Python operator attribution,
|
||||
GPU allocation stacks, native CPU frames and native allocations are outside
|
||||
these capture formats. Concurrent CUDA profilers in the same Python session
|
||||
are unsupported.
|
||||
|
||||
## Embedded and Enterprise execution {#in-process}
|
||||
|
||||
The following table describes LanceDB Embedded operations and registry jobs on
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { type IncomingHttpHeaders, createServer } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { type Connection, type FunctionProfileKind, connect } from "../lancedb";
|
||||
|
||||
type Response = { body: unknown; status?: number };
|
||||
|
||||
function metadata(kind: FunctionProfileKind, status: string) {
|
||||
return {
|
||||
["profile_id"]: "profile-1",
|
||||
["job_id"]: "job-1",
|
||||
["worker_id"]: "worker-1",
|
||||
["execution_epoch"]: 3,
|
||||
["session_slot"]: 0,
|
||||
kind,
|
||||
["duration_seconds"]: 2,
|
||||
status,
|
||||
["requested_at_millis"]: 1000,
|
||||
["deadline_at_millis"]: 46000,
|
||||
["expires_at_millis"]: 3601000,
|
||||
["completed_at_millis"]: null,
|
||||
error: status === "failed" ? "gpu_unavailable" : null,
|
||||
["artifact_id"]: status === "complete" ? "profile-1" : null,
|
||||
};
|
||||
}
|
||||
|
||||
const artifacts: Record<FunctionProfileKind, Record<string, unknown>> = {
|
||||
cpu: {
|
||||
$schema: "https://www.speedscope.app/file-format-schema.json",
|
||||
shared: { frames: [{ name: "work" }] },
|
||||
profiles: [],
|
||||
futureField: 7,
|
||||
},
|
||||
memory: {
|
||||
format: "lancedb.tracemalloc.v1",
|
||||
allocations: [{ ["size_bytes"]: 4096 }],
|
||||
truncated: false,
|
||||
},
|
||||
gpu: {
|
||||
format: "lancedb.cuda.v1",
|
||||
traceEvents: [{ name: "compute", cat: "kernel", ph: "X", ts: 10, dur: 2 }],
|
||||
truncated: true,
|
||||
},
|
||||
};
|
||||
|
||||
async function withProfileServer(
|
||||
handler: (
|
||||
path: string,
|
||||
body: Record<string, unknown>,
|
||||
headers: IncomingHttpHeaders,
|
||||
) => Response,
|
||||
run: (db: Connection) => Promise<void>,
|
||||
) {
|
||||
let serverError: unknown;
|
||||
const server = createServer(async (request, response) => {
|
||||
try {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of request) chunks.push(chunk);
|
||||
const bytes = Buffer.concat(chunks);
|
||||
const body = bytes.length === 0 ? {} : JSON.parse(bytes.toString());
|
||||
const result = handler(request.url ?? "", body, request.headers);
|
||||
response.writeHead(result.status ?? 200, {
|
||||
"Content-Type": "application/json",
|
||||
});
|
||||
response.end(JSON.stringify(result.body));
|
||||
} catch (error) {
|
||||
serverError = error;
|
||||
response.writeHead(500);
|
||||
response.end("test request handler failed");
|
||||
}
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const port = (server.address() as AddressInfo).port;
|
||||
try {
|
||||
const db = await connect("db://dev", {
|
||||
apiKey: "fake",
|
||||
hostOverride: `http://127.0.0.1:${port}`,
|
||||
});
|
||||
try {
|
||||
await run(db);
|
||||
} catch (error) {
|
||||
throw serverError ?? error;
|
||||
}
|
||||
if (serverError) throw serverError;
|
||||
} finally {
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
}
|
||||
|
||||
describe("Function worker profiles", () => {
|
||||
it.each(
|
||||
(["cpu", "memory", "gpu"] as FunctionProfileKind[]).flatMap((kind) =>
|
||||
[false, true].map((submitted) => [kind, submitted] as const),
|
||||
),
|
||||
)(
|
||||
"captures and exports retained %s evidence (submitted handle: %s)",
|
||||
async (kind, submitted) => {
|
||||
let polls = 0;
|
||||
let finished = false;
|
||||
const paths: string[] = [];
|
||||
const directory = await mkdtemp(join(tmpdir(), "lancedb-profile-"));
|
||||
try {
|
||||
await withProfileServer(
|
||||
(path, body, headers) => {
|
||||
paths.push(path);
|
||||
expect(headers["x-api-key"]).toBe("fake");
|
||||
expect(headers["x-lancedb-database"]).toBe("dev");
|
||||
if (path === "/v1/table/test/describe/")
|
||||
return { body: { version: 1, schema: { fields: [] } } };
|
||||
if (path === "/v1/table/test/backfill_column") {
|
||||
expect(body.column).toBe("result");
|
||||
return { status: 202, body: { ["job_id"]: "job-1" } };
|
||||
}
|
||||
if (path === "/v1/jobs/describe")
|
||||
return {
|
||||
body: {
|
||||
["job_id"]: "job-1",
|
||||
["job_type"]: "function_refresh",
|
||||
["job_state"]: finished ? "DONE" : "IN_PROGRESS",
|
||||
},
|
||||
};
|
||||
if (path === "/v1/jobs/profile/capture") {
|
||||
expect(body).toEqual({
|
||||
["job_id"]: "job-1",
|
||||
["worker_id"]: "worker-1",
|
||||
["session_slot"]: 0,
|
||||
kind,
|
||||
["duration_seconds"]: 2,
|
||||
});
|
||||
return { status: 202, body: metadata(kind, "pending") };
|
||||
}
|
||||
expect(body).toEqual({
|
||||
["job_id"]: "job-1",
|
||||
["profile_id"]: "profile-1",
|
||||
});
|
||||
if (path === "/v1/jobs/profile/status")
|
||||
return {
|
||||
body: metadata(kind, ++polls > 1 ? "complete" : "capturing"),
|
||||
};
|
||||
expect(path).toBe("/v1/jobs/profile/artifact");
|
||||
return { body: artifacts[kind] };
|
||||
},
|
||||
async (db) => {
|
||||
const job = submitted
|
||||
? await (await db.openTable("test")).refreshColumnAsync("result")
|
||||
: await db.openJob("job-1");
|
||||
if (submitted) await job.refresh();
|
||||
const capture = await job.captureProfile("worker-1", {
|
||||
kind,
|
||||
durationSeconds: 2,
|
||||
});
|
||||
expect(capture).toMatchObject({
|
||||
profileId: "profile-1",
|
||||
workerId: "worker-1",
|
||||
executionEpoch: 3,
|
||||
sessionSlot: 0,
|
||||
status: "pending",
|
||||
});
|
||||
const complete = await job.waitForProfile(capture.profileId, {
|
||||
timeoutMs: 2000,
|
||||
pollIntervalMs: 10,
|
||||
});
|
||||
expect(complete.status).toBe("complete");
|
||||
expect(job.state).toBe("running");
|
||||
finished = true;
|
||||
await job.refresh();
|
||||
expect(job.state).toBe("finished");
|
||||
expect(await job.profileArtifact(capture.profileId)).toEqual(
|
||||
artifacts[kind],
|
||||
);
|
||||
const path = join(directory, "capture.json");
|
||||
await job.exportProfile(capture.profileId, path);
|
||||
expect(JSON.parse(await readFile(path, "utf8"))).toEqual(
|
||||
artifacts[kind],
|
||||
);
|
||||
expect(
|
||||
paths.filter((path) => path === "/v1/jobs/describe"),
|
||||
).toHaveLength(2);
|
||||
expect(paths.some((path) => path.endsWith("/cancel"))).toBe(false);
|
||||
},
|
||||
);
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("can resume after a wait timeout without cancelling the refresh", async () => {
|
||||
let complete = false;
|
||||
const paths: string[] = [];
|
||||
await withProfileServer(
|
||||
(path) => {
|
||||
paths.push(path);
|
||||
if (path === "/v1/jobs/describe")
|
||||
return {
|
||||
body: {
|
||||
["job_id"]: "job-1",
|
||||
["job_type"]: "function_refresh",
|
||||
["job_state"]: "IN_PROGRESS",
|
||||
},
|
||||
};
|
||||
expect(path).toBe("/v1/jobs/profile/status");
|
||||
return { body: metadata("gpu", complete ? "complete" : "pending") };
|
||||
},
|
||||
async (db) => {
|
||||
const job = await db.openJob("job-1");
|
||||
await expect(
|
||||
job.waitForProfile("profile-1", {
|
||||
timeoutMs: 50,
|
||||
pollIntervalMs: 10,
|
||||
}),
|
||||
).rejects.toThrow(/waiting for Function worker profile/);
|
||||
expect(await job.status()).toBe("running");
|
||||
complete = true;
|
||||
expect(
|
||||
(await job.waitForProfile("profile-1", { timeoutMs: 2000 })).status,
|
||||
).toBe("complete");
|
||||
expect(paths.some((path) => path.endsWith("/cancel"))).toBe(false);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("reports failed captures independently of the parent", async () => {
|
||||
await withProfileServer(
|
||||
(path) => ({
|
||||
body:
|
||||
path === "/v1/jobs/describe"
|
||||
? {
|
||||
["job_id"]: "job-1",
|
||||
["job_type"]: "function_refresh",
|
||||
["job_state"]: "IN_PROGRESS",
|
||||
}
|
||||
: metadata("gpu", "failed"),
|
||||
}),
|
||||
async (db) => {
|
||||
const job = await db.openJob("job-1");
|
||||
expect(await job.profileStatus("profile-1")).toMatchObject({
|
||||
status: "failed",
|
||||
error: "gpu_unavailable",
|
||||
});
|
||||
await expect(job.waitForProfile("profile-1")).rejects.toThrow(
|
||||
"gpu_unavailable",
|
||||
);
|
||||
expect(job.state).toBe("running");
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves permission errors and existing export files", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "lancedb-profile-"));
|
||||
const path = join(directory, "capture.json");
|
||||
await writeFile(path, "previous capture");
|
||||
try {
|
||||
await withProfileServer(
|
||||
(path) => {
|
||||
if (path === "/v1/jobs/describe")
|
||||
return {
|
||||
body: {
|
||||
["job_id"]: "job-1",
|
||||
["job_type"]: "function_refresh",
|
||||
["job_state"]: "DONE",
|
||||
},
|
||||
};
|
||||
if (path.endsWith("/status"))
|
||||
return { body: metadata("gpu", "complete") };
|
||||
return { status: 403, body: { error: "System Operate required" } };
|
||||
},
|
||||
async (db) => {
|
||||
const job = await db.openJob("job-1");
|
||||
await expect(job.exportProfile("profile-1", path)).rejects.toThrow(
|
||||
"403",
|
||||
);
|
||||
expect(await readFile(path, "utf8")).toBe("previous capture");
|
||||
},
|
||||
);
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects invalid options before submitting a capture", async () => {
|
||||
await withProfileServer(
|
||||
(path) => {
|
||||
expect(path).toBe("/v1/jobs/describe");
|
||||
return {
|
||||
body: {
|
||||
["job_id"]: "job-1",
|
||||
["job_type"]: "function_refresh",
|
||||
["job_state"]: "IN_PROGRESS",
|
||||
},
|
||||
};
|
||||
},
|
||||
async (db) => {
|
||||
const job = await db.openJob("job-1");
|
||||
for (const durationSeconds of [
|
||||
Number.NaN,
|
||||
Number.POSITIVE_INFINITY,
|
||||
-1,
|
||||
0,
|
||||
6,
|
||||
]) {
|
||||
await expect(
|
||||
job.captureProfile("worker-1", { kind: "gpu", durationSeconds }),
|
||||
).rejects.toThrow(/duration/);
|
||||
}
|
||||
for (const sessionSlot of [
|
||||
-1,
|
||||
0.5,
|
||||
Number.NaN,
|
||||
Number.MAX_SAFE_INTEGER + 1,
|
||||
]) {
|
||||
await expect(
|
||||
job.captureProfile("worker-1", { sessionSlot }),
|
||||
).rejects.toThrow("sessionSlot");
|
||||
}
|
||||
await expect(
|
||||
job.captureProfile("worker-1", { duration: 10 } as never),
|
||||
).rejects.toThrow("Unknown profiling option");
|
||||
await expect(
|
||||
job.waitForProfile("profile-1", { timeoutMs: -1 }),
|
||||
).rejects.toThrow("timeoutMs");
|
||||
await expect(
|
||||
job.waitForProfile("profile-1", { pollIntervalMs: 0 }),
|
||||
).rejects.toThrow("poll interval");
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -124,6 +124,13 @@ export type {
|
||||
JobState,
|
||||
JobWaitOptions,
|
||||
} from "./job";
|
||||
export type {
|
||||
FunctionProfile,
|
||||
FunctionProfileKind,
|
||||
FunctionProfileOptions,
|
||||
FunctionProfileStatus,
|
||||
FunctionProfileWaitOptions,
|
||||
} from "./profiling";
|
||||
|
||||
export {
|
||||
AutoQuery,
|
||||
|
||||
@@ -1,11 +1,19 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { Table as ArrowTable, tableFromIPC } from "apache-arrow";
|
||||
import { decodeCleanupResult } from "./cleanup";
|
||||
import { decodeCompactionResult } from "./compaction";
|
||||
import type { JobFailureInfo, Job as NativeJob } from "./native";
|
||||
import { decodePrewarmDataResult } from "./prewarm";
|
||||
import {
|
||||
type FunctionProfile,
|
||||
type FunctionProfileOptions,
|
||||
type FunctionProfileWaitOptions,
|
||||
decodeFunctionProfile,
|
||||
validateProfileOptions,
|
||||
} from "./profiling";
|
||||
|
||||
/** Which of a job's events {@link Job.events} returns. */
|
||||
export interface JobEventsOptions {
|
||||
@@ -394,6 +402,95 @@ export class Job<T = void> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Request a profile of a running Enterprise Function worker session.
|
||||
* Returns the accepted identity without waiting for recording to finish.
|
||||
* Requires System Operate permission and server profiling support. The server
|
||||
* pins the worker, Python session and execution epoch. One capture per job
|
||||
* can be active. Captures add workload-dependent overhead.
|
||||
*
|
||||
* GPU tracing requires initialized PyTorch CUDA/CUPTI. CPU sampling requires
|
||||
* readable per-thread procfs and is unavailable in dedicated sandboxes.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const profile = await job.captureProfile("worker-id", {
|
||||
* kind: "gpu", durationSeconds: 2,
|
||||
* });
|
||||
* await job.waitForProfile(profile.profileId, { timeoutMs: 60_000 });
|
||||
* await job.exportProfile(profile.profileId, "gpu.trace.json");
|
||||
* ```
|
||||
*/
|
||||
async captureProfile(
|
||||
workerId: string,
|
||||
options: FunctionProfileOptions = {},
|
||||
): Promise<FunctionProfile> {
|
||||
validateProfileOptions(options, ["kind", "durationSeconds", "sessionSlot"]);
|
||||
const kind = options.kind ?? "cpu";
|
||||
if (!["cpu", "gpu", "memory"].includes(kind)) {
|
||||
throw new TypeError("kind must be cpu, memory or gpu");
|
||||
}
|
||||
return decodeFunctionProfile(
|
||||
await this.inner.captureProfile(
|
||||
workerId,
|
||||
kind,
|
||||
options.durationSeconds,
|
||||
options.sessionSlot,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch capture identity and status, including retained lookup after refresh.
|
||||
* Failed captures return status "failed" with the server's error reason.
|
||||
* This never changes the parent job's cached state.
|
||||
*/
|
||||
async profileStatus(profileId: string): Promise<FunctionProfile> {
|
||||
return decodeFunctionProfile(await this.inner.profileStatus(profileId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for a capture with a configurable timeout and polling cadence.
|
||||
* Defaults to 60 seconds with two seconds between requests. A timeout stops
|
||||
* only this wait; the capture and Function refresh continue. A failed capture
|
||||
* rejects with its server-reported reason. Keep its ID to wait again.
|
||||
*/
|
||||
async waitForProfile(
|
||||
profileId: string,
|
||||
options: FunctionProfileWaitOptions = {},
|
||||
): Promise<FunctionProfile> {
|
||||
validateProfileOptions(options, ["timeoutMs", "pollIntervalMs"]);
|
||||
return decodeFunctionProfile(
|
||||
await this.inner.waitForProfile(
|
||||
profileId,
|
||||
options.timeoutMs,
|
||||
options.pollIntervalMs,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a completed capture's actual JSON: speedscope for CPU,
|
||||
* tracemalloc for Python allocations, or Chrome Trace Event JSON for GPU.
|
||||
* Truncation flags are preserved. Retention is at most one hour and eight
|
||||
* captures per job, until earlier scratch reclamation or archival.
|
||||
* Permission, expired-artifact and unsupported-server errors propagate.
|
||||
*/
|
||||
async profileArtifact(profileId: string): Promise<Record<string, unknown>> {
|
||||
return JSON.parse(await this.inner.profileArtifact(profileId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Write a completed capture's JSON after successful retrieval. Open CPU
|
||||
* exports in speedscope and GPU exports in Perfetto. GPU activity durations
|
||||
* can overlap and are not utilization; Python operator attribution and GPU
|
||||
* allocation stacks are excluded. Filesystem errors propagate to the caller.
|
||||
*/
|
||||
async exportProfile(profileId: string, path: string): Promise<void> {
|
||||
const artifact = await this.inner.profileArtifact(profileId);
|
||||
await writeFile(path, artifact, "utf8");
|
||||
}
|
||||
|
||||
private lastProgress: JobProgress | null = null;
|
||||
|
||||
private enrichProgress(progress: Record<string, unknown>): JobProgress {
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
/** Evidence collected from one Function worker's Python execution session. */
|
||||
export type FunctionProfileKind = "cpu" | "gpu" | "memory";
|
||||
|
||||
/** A capture's lifecycle, independent of its parent refresh job. */
|
||||
export type FunctionProfileStatus =
|
||||
| "pending"
|
||||
| "capturing"
|
||||
| "complete"
|
||||
| "failed";
|
||||
|
||||
/** Options for requesting a Function worker capture. */
|
||||
export interface FunctionProfileOptions {
|
||||
/** CPU samples, retained Python allocations, or PyTorch CUDA activities. */
|
||||
kind?: FunctionProfileKind;
|
||||
/** 1–30 seconds for CPU/memory, default 10; 1–5 for GPU, default 5. */
|
||||
durationSeconds?: number;
|
||||
/** Python execution session within the worker; default zero. */
|
||||
sessionSlot?: number;
|
||||
}
|
||||
|
||||
/** Client-side controls while waiting for a Function worker capture. */
|
||||
export interface FunctionProfileWaitOptions {
|
||||
/** Maximum wait including HTTP requests and sleeps; defaults to 60,000 ms. */
|
||||
timeoutMs?: number;
|
||||
/** Delay between status requests; defaults to 2,000 ms and must be positive. */
|
||||
pollIntervalMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* A capture identity and status snapshot. Keep profileId for retained lookup
|
||||
* after the Function refresh completes. Timestamp fields are epoch milliseconds.
|
||||
*/
|
||||
export interface FunctionProfile {
|
||||
readonly profileId: string;
|
||||
readonly jobId: string;
|
||||
readonly workerId: string;
|
||||
readonly executionEpoch: number;
|
||||
readonly sessionSlot: number;
|
||||
readonly kind: FunctionProfileKind;
|
||||
readonly durationSeconds: number;
|
||||
readonly status: FunctionProfileStatus;
|
||||
readonly requestedAtMillis: number;
|
||||
readonly deadlineAtMillis: number;
|
||||
/** Upper retention bound; job scratch reclamation can remove artifacts sooner. */
|
||||
readonly expiresAtMillis: number;
|
||||
readonly completedAtMillis: number | null;
|
||||
/** The server's capture failure reason; this is not a refresh job failure. */
|
||||
readonly error: string | null;
|
||||
readonly artifactId: string | null;
|
||||
}
|
||||
|
||||
export function decodeFunctionProfile(value: string): FunctionProfile {
|
||||
const data = JSON.parse(value);
|
||||
return {
|
||||
profileId: data.profile_id,
|
||||
jobId: data.job_id,
|
||||
workerId: data.worker_id,
|
||||
executionEpoch: data.execution_epoch,
|
||||
sessionSlot: data.session_slot,
|
||||
kind: data.kind,
|
||||
durationSeconds: data.duration_seconds,
|
||||
status: data.status,
|
||||
requestedAtMillis: data.requested_at_millis,
|
||||
deadlineAtMillis: data.deadline_at_millis,
|
||||
expiresAtMillis: data.expires_at_millis,
|
||||
completedAtMillis: data.completed_at_millis,
|
||||
error: data.error,
|
||||
artifactId: data.artifact_id,
|
||||
};
|
||||
}
|
||||
|
||||
export function validateProfileOptions(options: object, names: string[]): void {
|
||||
if (
|
||||
typeof options !== "object" ||
|
||||
options === null ||
|
||||
Array.isArray(options)
|
||||
) {
|
||||
throw new TypeError("profiling expects an options object");
|
||||
}
|
||||
for (const key of Object.keys(options)) {
|
||||
if (!names.includes(key)) {
|
||||
throw new TypeError(`Unknown profiling option: ${key}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
+94
-2
@@ -4,7 +4,10 @@
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use arrow_array::RecordBatch;
|
||||
use lancedb::job::{JobEventsRequest, JobWaitOptions};
|
||||
use lancedb::job::{
|
||||
FunctionProfileKind, FunctionProfileOptions, FunctionProfileWaitOptions, JobEventsRequest,
|
||||
JobWaitOptions,
|
||||
};
|
||||
use napi::bindgen_prelude::Buffer;
|
||||
use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode};
|
||||
use napi_derive::napi;
|
||||
@@ -14,6 +17,18 @@ use crate::error::NapiErrorExt;
|
||||
type JobProgressFn =
|
||||
ThreadsafeFunction<serde_json::Value, (), serde_json::Value, napi::Status, false>;
|
||||
|
||||
const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;
|
||||
|
||||
fn profile_integer(value: f64, name: &str) -> napi::Result<u64> {
|
||||
if !value.is_finite() || value.fract() != 0.0 || !(0.0..=MAX_SAFE_INTEGER).contains(&value) {
|
||||
return Err(napi::Error::new(
|
||||
napi::Status::InvalidArg,
|
||||
format!("{name} must be a nonnegative safe integer"),
|
||||
));
|
||||
}
|
||||
Ok(value as u64)
|
||||
}
|
||||
|
||||
/// A handle to an operation that may still be running.
|
||||
#[napi]
|
||||
pub struct Job {
|
||||
@@ -142,7 +157,6 @@ impl Job {
|
||||
) -> napi::Result<Option<serde_json::Value>> {
|
||||
let mut options = JobWaitOptions::new();
|
||||
if let Some(timeout_ms) = timeout_ms {
|
||||
const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;
|
||||
if !timeout_ms.is_finite()
|
||||
|| timeout_ms.fract() != 0.0
|
||||
|| !(0.0..=MAX_SAFE_INTEGER).contains(&timeout_ms)
|
||||
@@ -233,6 +247,84 @@ impl Job {
|
||||
self.inner.failure().map(Into::into)
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn capture_profile(
|
||||
&self,
|
||||
worker_id: String,
|
||||
kind: String,
|
||||
duration_seconds: Option<f64>,
|
||||
session_slot: Option<f64>,
|
||||
) -> napi::Result<String> {
|
||||
let kind: FunctionProfileKind =
|
||||
serde_json::from_value(serde_json::json!(kind)).map_err(|_| {
|
||||
napi::Error::new(napi::Status::InvalidArg, "kind must be cpu, memory or gpu")
|
||||
})?;
|
||||
let mut options = FunctionProfileOptions::new(kind);
|
||||
if let Some(slot) = session_slot {
|
||||
options = options.session_slot(profile_integer(slot, "sessionSlot")? as usize);
|
||||
}
|
||||
if let Some(seconds) = duration_seconds {
|
||||
let duration = Duration::try_from_secs_f64(seconds).map_err(|_| {
|
||||
napi::Error::new(
|
||||
napi::Status::InvalidArg,
|
||||
"durationSeconds must be finite and nonnegative",
|
||||
)
|
||||
})?;
|
||||
options = options.duration(duration);
|
||||
}
|
||||
let profile = self
|
||||
.inner
|
||||
.capture_profile(worker_id, options)
|
||||
.await
|
||||
.default_error()?;
|
||||
serde_json::to_string(&profile).map_err(|error| napi::Error::from_reason(error.to_string()))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn profile_status(&self, profile_id: String) -> napi::Result<String> {
|
||||
let profile = self
|
||||
.inner
|
||||
.profile_status(profile_id)
|
||||
.await
|
||||
.default_error()?;
|
||||
serde_json::to_string(&profile).map_err(|error| napi::Error::from_reason(error.to_string()))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn wait_for_profile(
|
||||
&self,
|
||||
profile_id: String,
|
||||
timeout_ms: Option<f64>,
|
||||
poll_interval_ms: Option<f64>,
|
||||
) -> napi::Result<String> {
|
||||
let mut options = FunctionProfileWaitOptions::new();
|
||||
if let Some(ms) = timeout_ms {
|
||||
options = options.timeout(Duration::from_millis(profile_integer(ms, "timeoutMs")?));
|
||||
}
|
||||
if let Some(ms) = poll_interval_ms {
|
||||
options = options.poll_interval(Duration::from_millis(profile_integer(
|
||||
ms,
|
||||
"pollIntervalMs",
|
||||
)?));
|
||||
}
|
||||
let profile = self
|
||||
.inner
|
||||
.wait_for_profile(profile_id, options)
|
||||
.await
|
||||
.default_error()?;
|
||||
serde_json::to_string(&profile).map_err(|error| napi::Error::from_reason(error.to_string()))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn profile_artifact(&self, profile_id: String) -> napi::Result<String> {
|
||||
Ok(self
|
||||
.inner
|
||||
.profile_artifact(profile_id)
|
||||
.await
|
||||
.default_error()?
|
||||
.to_string())
|
||||
}
|
||||
|
||||
/// This job's recorded lifecycle events, as an Arrow IPC stream buffer.
|
||||
/// The TypeScript wrapper turns it into an Arrow table.
|
||||
#[napi(catch_unwind)]
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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))
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
+84
-2
@@ -2,16 +2,20 @@
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::runtime::future_into_py;
|
||||
use arrow::{
|
||||
datatypes::Schema,
|
||||
pyarrow::{IntoPyArrow, Table as PyArrowTable},
|
||||
};
|
||||
use lancedb::job::JobEventsRequest;
|
||||
use lancedb::job::{
|
||||
FunctionProfile, FunctionProfileKind, FunctionProfileOptions, FunctionProfileWaitOptions,
|
||||
JobEventsRequest,
|
||||
};
|
||||
use pyo3::{
|
||||
Bound, Py, PyAny, PyRef, PyResult, Python,
|
||||
exceptions::PyValueError,
|
||||
exceptions::{PyTimeoutError, PyValueError},
|
||||
pyclass, pymethods,
|
||||
types::{PyAnyMethods, PyDict, PyDictMethods},
|
||||
};
|
||||
@@ -21,6 +25,17 @@ use crate::error::PythonErrorExt;
|
||||
|
||||
const REPR_INDENT: &str = " ";
|
||||
|
||||
fn profile_json(result: lancedb::Result<FunctionProfile>) -> PyResult<String> {
|
||||
let profile = result.infer_error()?;
|
||||
serde_json::to_string(&profile)
|
||||
.map_err(|error| PyValueError::new_err(format!("invalid profile metadata: {error}")))
|
||||
}
|
||||
|
||||
fn profile_duration(seconds: f64) -> PyResult<Duration> {
|
||||
Duration::try_from_secs_f64(seconds)
|
||||
.map_err(|_| PyValueError::new_err("profile durations must be finite and nonnegative"))
|
||||
}
|
||||
|
||||
/// Parse a stored JSON payload into Python data. The bindings carry these as
|
||||
/// strings because that is what crosses the boundary cheaply; the public
|
||||
/// Python surface is the parsed form.
|
||||
@@ -212,6 +227,73 @@ impl Job {
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (worker_id, *, kind="cpu", duration_seconds=None, session_slot=0))]
|
||||
pub fn capture_profile<'py>(
|
||||
self_: PyRef<'py, Self>,
|
||||
worker_id: String,
|
||||
kind: &str,
|
||||
duration_seconds: Option<f64>,
|
||||
session_slot: usize,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
let kind: FunctionProfileKind = serde_json::from_value(serde_json::json!(kind))
|
||||
.map_err(|_| PyValueError::new_err("kind must be 'cpu', 'memory' or 'gpu'"))?;
|
||||
let mut options = FunctionProfileOptions::new(kind).session_slot(session_slot);
|
||||
if let Some(seconds) = duration_seconds {
|
||||
options = options.duration(profile_duration(seconds)?);
|
||||
}
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
profile_json(inner.capture_profile(worker_id, options).await)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn profile_status(
|
||||
self_: PyRef<'_, Self>,
|
||||
profile_id: String,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
profile_json(inner.profile_status(profile_id).await)
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (profile_id, *, timeout_seconds=None, poll_interval_seconds=None))]
|
||||
pub fn wait_for_profile(
|
||||
self_: PyRef<'_, Self>,
|
||||
profile_id: String,
|
||||
timeout_seconds: Option<f64>,
|
||||
poll_interval_seconds: Option<f64>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let mut options = FunctionProfileWaitOptions::new();
|
||||
if let Some(seconds) = timeout_seconds {
|
||||
options = options.timeout(profile_duration(seconds)?);
|
||||
}
|
||||
if let Some(seconds) = poll_interval_seconds {
|
||||
options = options.poll_interval(profile_duration(seconds)?);
|
||||
}
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
match inner.wait_for_profile(profile_id, options).await {
|
||||
Err(lancedb::Error::Timeout { message }) => Err(PyTimeoutError::new_err(message)),
|
||||
result => profile_json(result),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn profile_artifact(
|
||||
self_: PyRef<'_, Self>,
|
||||
profile_id: String,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
Ok(inner
|
||||
.profile_artifact(profile_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() })
|
||||
|
||||
@@ -3,6 +3,13 @@
|
||||
|
||||
//! Handles to operations a server may run asynchronously.
|
||||
|
||||
mod profile;
|
||||
|
||||
pub use profile::{
|
||||
FunctionProfile, FunctionProfileKind, FunctionProfileOptions, FunctionProfileStatus,
|
||||
FunctionProfileWaitOptions,
|
||||
};
|
||||
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard};
|
||||
@@ -14,6 +21,7 @@ use serde::{Serialize, de::DeserializeOwned};
|
||||
use serde_json::Value;
|
||||
use tokio::sync::watch;
|
||||
use tokio::task::{AbortHandle, JoinHandle};
|
||||
use tokio::time::{Instant, sleep_until, timeout_at};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::database::JobDescription;
|
||||
@@ -164,6 +172,22 @@ pub(crate) trait JobHandle: Send + Sync {
|
||||
job_detail_not_supported("worker stack capture")
|
||||
}
|
||||
|
||||
async fn capture_profile(
|
||||
&self,
|
||||
_worker_id: &str,
|
||||
_options: FunctionProfileOptions,
|
||||
) -> Result<FunctionProfile> {
|
||||
job_detail_not_supported("Function worker profiling")
|
||||
}
|
||||
|
||||
async fn profile_status(&self, _profile_id: &str) -> Result<FunctionProfile> {
|
||||
job_detail_not_supported("Function worker profiling")
|
||||
}
|
||||
|
||||
async fn profile_artifact(&self, _profile_id: &str) -> Result<Value> {
|
||||
job_detail_not_supported("Function worker profiling")
|
||||
}
|
||||
|
||||
/// A printable report of recorded Function job metrics.
|
||||
async fn stats(&self) -> Result<Option<String>> {
|
||||
job_detail_not_supported("job statistics")
|
||||
@@ -753,6 +777,135 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// Request an on-demand profile from a running Enterprise Function worker.
|
||||
///
|
||||
/// Returns the accepted capture identity without waiting for recording to
|
||||
/// finish. The server pins the worker, Python session and execution epoch.
|
||||
/// Requires System Operate permission and a supporting Enterprise server.
|
||||
/// Only one capture per job can be active. GPU traces require initialized
|
||||
/// PyTorch CUDA/CUPTI; CPU sampling requires readable per-thread procfs.
|
||||
/// Captures add workload-dependent overhead.
|
||||
///
|
||||
/// ```no_run
|
||||
/// # async fn capture(job: &lancedb::job::Job) -> Result<(), Box<dyn std::error::Error>> {
|
||||
/// use std::time::Duration;
|
||||
/// use lancedb::job::{FunctionProfileKind, FunctionProfileOptions, FunctionProfileWaitOptions};
|
||||
/// let profile = job.capture_profile("worker-id",
|
||||
/// FunctionProfileOptions::new(FunctionProfileKind::Gpu)
|
||||
/// .duration(Duration::from_secs(2))).await?;
|
||||
/// job.wait_for_profile(&profile.profile_id, FunctionProfileWaitOptions::new()).await?;
|
||||
/// let artifact = job.profile_artifact(&profile.profile_id).await?;
|
||||
/// std::fs::write("gpu.trace.json", serde_json::to_vec(&artifact)?)?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub async fn capture_profile(
|
||||
&self,
|
||||
worker_id: impl AsRef<str>,
|
||||
options: FunctionProfileOptions,
|
||||
) -> Result<FunctionProfile> {
|
||||
let worker_id = worker_id.as_ref();
|
||||
options.validate(worker_id)?;
|
||||
match &self.inner {
|
||||
JobInner::Handle { handle, .. } => handle.capture_profile(worker_id, options).await,
|
||||
JobInner::Completed(_) => job_detail_not_supported("Function worker profiling"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch the capture's current identity and status without waiting.
|
||||
///
|
||||
/// Capture failures are returned as [`FunctionProfileStatus::Failed`] with
|
||||
/// the server's reason. This does not change the parent job's cached state.
|
||||
/// Retained captures can be looked up after the refresh job completes.
|
||||
pub async fn profile_status(&self, profile_id: impl AsRef<str>) -> Result<FunctionProfile> {
|
||||
let profile_id = profile_id.as_ref();
|
||||
profile::validate_profile_id(profile_id)?;
|
||||
match &self.inner {
|
||||
JobInner::Handle { handle, .. } => handle.profile_status(profile_id).await,
|
||||
JobInner::Completed(_) => job_detail_not_supported("Function worker profiling"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait for a capture to finish, independently of the Function refresh job.
|
||||
///
|
||||
/// Returns [`Error::Timeout`] when the client deadline elapses and
|
||||
/// [`Error::Runtime`] when capture fails. Neither cancels the capture or
|
||||
/// refresh job. Keep the profile ID to wait again or retrieve it later.
|
||||
pub async fn wait_for_profile(
|
||||
&self,
|
||||
profile_id: impl AsRef<str>,
|
||||
options: FunctionProfileWaitOptions,
|
||||
) -> Result<FunctionProfile> {
|
||||
let profile_id = profile_id.as_ref();
|
||||
profile::validate_profile_id(profile_id)?;
|
||||
if options.poll_interval.is_zero() {
|
||||
return Err(Error::InvalidInput {
|
||||
message: "profile poll interval must be greater than zero".into(),
|
||||
});
|
||||
}
|
||||
let deadline =
|
||||
Instant::now()
|
||||
.checked_add(options.timeout)
|
||||
.ok_or_else(|| Error::InvalidInput {
|
||||
message: "profile wait timeout is too large".into(),
|
||||
})?;
|
||||
let wait = async {
|
||||
let mut previous: Option<FunctionProfile> = None;
|
||||
loop {
|
||||
let profile = self.profile_status(profile_id).await?;
|
||||
if previous
|
||||
.as_ref()
|
||||
.is_some_and(|old| !old.same_capture(&profile))
|
||||
{
|
||||
return Err(Error::Runtime {
|
||||
message: "profile response changed the capture's execution identity".into(),
|
||||
});
|
||||
}
|
||||
match profile.status {
|
||||
FunctionProfileStatus::Complete => return Ok(profile),
|
||||
FunctionProfileStatus::Failed => {
|
||||
return Err(Error::Runtime {
|
||||
message: format!(
|
||||
"Function worker profile {} failed: {}",
|
||||
profile.profile_id,
|
||||
profile.error.as_deref().unwrap_or("no reason reported")
|
||||
),
|
||||
});
|
||||
}
|
||||
FunctionProfileStatus::Pending | FunctionProfileStatus::Capturing => {}
|
||||
}
|
||||
previous = Some(profile);
|
||||
let next_poll = Instant::now()
|
||||
.checked_add(options.poll_interval)
|
||||
.unwrap_or(deadline)
|
||||
.min(deadline);
|
||||
sleep_until(next_poll).await;
|
||||
}
|
||||
};
|
||||
timeout_at(deadline, wait)
|
||||
.await
|
||||
.map_err(|_| Error::Timeout {
|
||||
message: format!(
|
||||
"waiting for Function worker profile {profile_id}; capture and refresh job continue on the server"
|
||||
),
|
||||
})?
|
||||
}
|
||||
|
||||
/// Retrieve the actual profile JSON, including a retained capture after refresh.
|
||||
///
|
||||
/// CPU artifacts use speedscope, Python memory artifacts use tracemalloc,
|
||||
/// and GPU artifacts use Chrome Trace Event JSON. GPU truncation flags are
|
||||
/// preserved. Artifacts expire after at most one hour and eight captures
|
||||
/// per job, or earlier when job scratch is reclaimed or archived.
|
||||
pub async fn profile_artifact(&self, profile_id: impl AsRef<str>) -> Result<Value> {
|
||||
let profile_id = profile_id.as_ref();
|
||||
profile::validate_profile_id(profile_id)?;
|
||||
match &self.inner {
|
||||
JobInner::Handle { handle, .. } => handle.profile_artifact(profile_id).await,
|
||||
JobInner::Completed(_) => job_detail_not_supported("Function worker profiling"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch a printable run report for a server-side Function job.
|
||||
///
|
||||
/// The server report includes recorded phase timings, finishing-supervisor
|
||||
@@ -1112,6 +1265,48 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
struct PendingProfileStatus;
|
||||
|
||||
#[async_trait]
|
||||
impl JobHandle for PendingProfileStatus {
|
||||
async fn status(&self) -> Result<String> {
|
||||
panic!("profile wait fetched parent status")
|
||||
}
|
||||
async fn wait(&self) -> Result<TerminalResult> {
|
||||
panic!("profile wait waited for parent completion")
|
||||
}
|
||||
async fn cancel(&self) -> Result<()> {
|
||||
panic!("profile wait cancelled parent job")
|
||||
}
|
||||
async fn profile_status(&self, _profile_id: &str) -> Result<FunctionProfile> {
|
||||
pending().await
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn profile_timeout_bounds_pending_requests_and_rejects_deadline_overflow() {
|
||||
let job = Job::new(Box::new(PendingProfileStatus));
|
||||
let started = Instant::now();
|
||||
assert!(matches!(
|
||||
job.wait_for_profile(
|
||||
"profile-1",
|
||||
FunctionProfileWaitOptions::new().timeout(Duration::from_millis(50))
|
||||
)
|
||||
.await,
|
||||
Err(Error::Timeout { .. })
|
||||
));
|
||||
assert_eq!(started.elapsed(), Duration::from_millis(50));
|
||||
assert_eq!(job.state(), None);
|
||||
assert!(matches!(
|
||||
job.wait_for_profile(
|
||||
"profile-1",
|
||||
FunctionProfileWaitOptions::new().timeout(Duration::MAX)
|
||||
)
|
||||
.await,
|
||||
Err(Error::InvalidInput { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn wait_timeout_preserves_local_task_and_typed_result() {
|
||||
let job = Job::spawned(tokio::spawn(async {
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
//! On-demand profiling of a Function worker's Python execution session.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
|
||||
pub(crate) fn validate_profile_id(profile_id: &str) -> Result<()> {
|
||||
if profile_id.is_empty() || profile_id.len() > 256 {
|
||||
return Err(Error::InvalidInput {
|
||||
message: "profile_id must contain between 1 and 256 bytes".into(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What to record in one Function worker process.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[non_exhaustive]
|
||||
pub enum FunctionProfileKind {
|
||||
/// Python stack samples weighted by thread CPU time, exported as speedscope JSON.
|
||||
Cpu,
|
||||
/// PyTorch CUDA kernels, transfers and available CUDA host API activities.
|
||||
Gpu,
|
||||
/// Python allocations made during the capture and retained at its end.
|
||||
Memory,
|
||||
}
|
||||
|
||||
impl FunctionProfileKind {
|
||||
fn maximum_duration(self) -> Duration {
|
||||
Duration::from_secs(if self == Self::Gpu { 5 } else { 30 })
|
||||
}
|
||||
}
|
||||
|
||||
/// Server-reported state of a profile capture, independent of its parent job.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[non_exhaustive]
|
||||
pub enum FunctionProfileStatus {
|
||||
/// Waiting for the Function supervisor to dispatch the capture.
|
||||
Pending,
|
||||
/// Recording the selected execution session.
|
||||
Capturing,
|
||||
/// The artifact can be retrieved until expiry or scratch reclamation.
|
||||
Complete,
|
||||
/// Capture failed; inspect [`FunctionProfile::error`] for the server's reason.
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// A snapshot of a capture's identity, status and retention information.
|
||||
///
|
||||
/// It describes a diagnostic capture on an existing Function refresh job, not
|
||||
/// another job. Use its profile ID with [`super::Job::profile_status`] or
|
||||
/// [`super::Job::profile_artifact`], including after the refresh finishes.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[non_exhaustive]
|
||||
pub struct FunctionProfile {
|
||||
/// Retain this ID to retrieve the capture later.
|
||||
pub profile_id: String,
|
||||
/// The parent Function refresh job.
|
||||
pub job_id: String,
|
||||
/// The selected Function worker.
|
||||
pub worker_id: String,
|
||||
/// Execution epoch pinned by the server when accepting the capture.
|
||||
pub execution_epoch: i64,
|
||||
/// Python session slot; zero is the first session.
|
||||
pub session_slot: usize,
|
||||
/// The kind of evidence collected.
|
||||
pub kind: FunctionProfileKind,
|
||||
/// Requested recording window, excluding dispatch delay.
|
||||
pub duration_seconds: f64,
|
||||
/// Current capture state.
|
||||
pub status: FunctionProfileStatus,
|
||||
/// Acceptance time, in milliseconds since the Unix epoch.
|
||||
pub requested_at_millis: i64,
|
||||
/// Server deadline for an unfinished capture, in epoch milliseconds.
|
||||
pub deadline_at_millis: i64,
|
||||
/// Retention bound in epoch milliseconds; scratch reclamation may remove it sooner.
|
||||
pub expires_at_millis: i64,
|
||||
/// Completion time, when reported.
|
||||
pub completed_at_millis: Option<i64>,
|
||||
/// Server-reported failure reason, including unsupported-session errors.
|
||||
pub error: Option<String>,
|
||||
/// Server artifact identity, when the capture completes.
|
||||
pub artifact_id: Option<String>,
|
||||
}
|
||||
|
||||
impl FunctionProfile {
|
||||
pub(crate) fn same_capture(&self, other: &Self) -> bool {
|
||||
self.profile_id == other.profile_id
|
||||
&& self.job_id == other.job_id
|
||||
&& self.worker_id == other.worker_id
|
||||
&& self.execution_epoch == other.execution_epoch
|
||||
&& self.session_slot == other.session_slot
|
||||
&& self.kind == other.kind
|
||||
&& self.duration_seconds == other.duration_seconds
|
||||
}
|
||||
|
||||
pub(crate) fn valid_for(&self, job_id: &str, profile_id: Option<&str>) -> bool {
|
||||
self.job_id == job_id
|
||||
&& !self.profile_id.is_empty()
|
||||
&& self.profile_id.len() <= 256
|
||||
&& profile_id.is_none_or(|id| id == self.profile_id)
|
||||
&& !self.worker_id.is_empty()
|
||||
&& self.worker_id.len() <= 256
|
||||
&& self.duration_seconds.is_finite()
|
||||
&& (1.0..=self.kind.maximum_duration().as_secs_f64()).contains(&self.duration_seconds)
|
||||
&& (self.status != FunctionProfileStatus::Complete
|
||||
|| self.artifact_id.as_ref().is_some_and(|id| !id.is_empty()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Options for [`super::Job::capture_profile`].
|
||||
///
|
||||
/// CPU and memory captures allow 1–30 seconds; GPU captures allow 1–5.
|
||||
/// Omitting the duration selects 10 seconds for CPU/memory and 5 for GPU.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FunctionProfileOptions {
|
||||
pub(crate) kind: FunctionProfileKind,
|
||||
pub(crate) duration: Option<Duration>,
|
||||
pub(crate) session_slot: usize,
|
||||
}
|
||||
|
||||
impl Default for FunctionProfileOptions {
|
||||
fn default() -> Self {
|
||||
Self::new(FunctionProfileKind::Cpu)
|
||||
}
|
||||
}
|
||||
|
||||
impl FunctionProfileOptions {
|
||||
/// Select the kind of capture, using its default duration and session zero.
|
||||
pub fn new(kind: FunctionProfileKind) -> Self {
|
||||
Self {
|
||||
kind,
|
||||
duration: None,
|
||||
session_slot: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the recording window. Dispatch time is additional.
|
||||
pub fn duration(mut self, duration: Duration) -> Self {
|
||||
self.duration = Some(duration);
|
||||
self
|
||||
}
|
||||
|
||||
/// Select the Python session within the worker.
|
||||
pub fn session_slot(mut self, slot: usize) -> Self {
|
||||
self.session_slot = slot;
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn duration_seconds(&self) -> f64 {
|
||||
self.duration
|
||||
.unwrap_or_else(|| {
|
||||
Duration::from_secs(if self.kind == FunctionProfileKind::Gpu {
|
||||
5
|
||||
} else {
|
||||
10
|
||||
})
|
||||
})
|
||||
.as_secs_f64()
|
||||
}
|
||||
|
||||
pub(crate) fn validate(&self, worker_id: &str) -> Result<()> {
|
||||
if worker_id.is_empty() || worker_id.len() > 256 {
|
||||
return Err(Error::InvalidInput {
|
||||
message: "worker_id must contain between 1 and 256 bytes".into(),
|
||||
});
|
||||
}
|
||||
if !(1.0..=self.kind.maximum_duration().as_secs_f64()).contains(&self.duration_seconds()) {
|
||||
return Err(Error::InvalidInput {
|
||||
message: format!(
|
||||
"profile duration must be between 1 and {} seconds",
|
||||
self.kind.maximum_duration().as_secs()
|
||||
),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Client controls for [`super::Job::wait_for_profile`].
|
||||
///
|
||||
/// Defaults to a 60-second timeout and two seconds between status requests.
|
||||
/// The timeout includes requests and sleeps, and never cancels the capture or job.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FunctionProfileWaitOptions {
|
||||
pub(crate) timeout: Duration,
|
||||
pub(crate) poll_interval: Duration,
|
||||
}
|
||||
|
||||
impl Default for FunctionProfileWaitOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
timeout: Duration::from_secs(60),
|
||||
poll_interval: Duration::from_secs(2),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FunctionProfileWaitOptions {
|
||||
/// Use the default timeout and polling interval.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Bound this wait without cancelling server-side work.
|
||||
pub fn timeout(mut self, timeout: Duration) -> Self {
|
||||
self.timeout = timeout;
|
||||
self
|
||||
}
|
||||
|
||||
/// Delay between status requests; must be greater than zero.
|
||||
pub fn poll_interval(mut self, interval: Duration) -> Self {
|
||||
self.poll_interval = interval;
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@
|
||||
|
||||
//! Tracking for server-side jobs through the `/v1/jobs` API.
|
||||
|
||||
mod profile;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use arrow_array::RecordBatch;
|
||||
@@ -13,7 +15,10 @@ use serde::Deserialize;
|
||||
|
||||
use crate::database::JobDescription;
|
||||
use crate::error::{Error, JobFailure, Result};
|
||||
use crate::job::{JobEventsRequest, JobHandle, JobProgressCallback, TerminalResult};
|
||||
use crate::job::{
|
||||
FunctionProfile, FunctionProfileOptions, JobEventsRequest, JobHandle, JobProgressCallback,
|
||||
TerminalResult,
|
||||
};
|
||||
use crate::remote::client::{HttpSend, RequestResultExt, RestfulLanceDbClient};
|
||||
|
||||
/// Delay before the second job-state poll; doubles up to [`MAX_POLL_INTERVAL`].
|
||||
@@ -356,6 +361,22 @@ impl<S: HttpSend> JobHandle for RemoteJob<S> {
|
||||
Ok(evidence)
|
||||
}
|
||||
|
||||
async fn capture_profile(
|
||||
&self,
|
||||
worker_id: &str,
|
||||
options: FunctionProfileOptions,
|
||||
) -> Result<FunctionProfile> {
|
||||
self.capture_profile_inner(worker_id, options).await
|
||||
}
|
||||
|
||||
async fn profile_status(&self, profile_id: &str) -> Result<FunctionProfile> {
|
||||
self.profile_status_inner(profile_id).await
|
||||
}
|
||||
|
||||
async fn profile_artifact(&self, profile_id: &str) -> Result<serde_json::Value> {
|
||||
self.profile_artifact_inner(profile_id).await
|
||||
}
|
||||
|
||||
async fn stats(&self) -> Result<Option<String>> {
|
||||
let request = self
|
||||
.client
|
||||
|
||||
@@ -0,0 +1,476 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::RemoteJob;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::job::{
|
||||
FunctionProfile, FunctionProfileKind, FunctionProfileOptions, FunctionProfileStatus,
|
||||
};
|
||||
use crate::remote::client::{HttpSend, RequestResultExt};
|
||||
|
||||
impl<S: HttpSend> RemoteJob<S> {
|
||||
async fn profile_request<T: DeserializeOwned>(
|
||||
&self,
|
||||
action: &str,
|
||||
body: Value,
|
||||
) -> Result<(String, T)> {
|
||||
let request = self
|
||||
.client
|
||||
.post(&format!("/v1/jobs/profile/{action}"))
|
||||
.json(&body);
|
||||
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 value = serde_json::from_str(&body).map_err(|error| Error::Http {
|
||||
source: format!("invalid Function profile {action} response: {error}").into(),
|
||||
request_id: request_id.clone(),
|
||||
status_code: None,
|
||||
})?;
|
||||
Ok((request_id, value))
|
||||
}
|
||||
|
||||
pub(super) async fn capture_profile_inner(
|
||||
&self,
|
||||
worker_id: &str,
|
||||
options: FunctionProfileOptions,
|
||||
) -> Result<FunctionProfile> {
|
||||
let duration = options.duration_seconds();
|
||||
let (request_id, profile): (_, FunctionProfile) = self
|
||||
.profile_request(
|
||||
"capture",
|
||||
json!({
|
||||
"job_id": self.job_id,
|
||||
"worker_id": worker_id,
|
||||
"session_slot": options.session_slot,
|
||||
"kind": options.kind,
|
||||
"duration_seconds": duration,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
if !profile.valid_for(&self.job_id, None)
|
||||
|| profile.worker_id != worker_id
|
||||
|| profile.session_slot != options.session_slot
|
||||
|| profile.kind != options.kind
|
||||
|| profile.duration_seconds != duration
|
||||
{
|
||||
return Err(Error::Http {
|
||||
source: "Function profile response does not match the requested capture".into(),
|
||||
request_id,
|
||||
status_code: None,
|
||||
});
|
||||
}
|
||||
Ok(profile)
|
||||
}
|
||||
|
||||
pub(super) async fn profile_status_inner(&self, profile_id: &str) -> Result<FunctionProfile> {
|
||||
let (request_id, profile): (_, FunctionProfile) = self
|
||||
.profile_request(
|
||||
"status",
|
||||
json!({"job_id": self.job_id, "profile_id": profile_id}),
|
||||
)
|
||||
.await?;
|
||||
if !profile.valid_for(&self.job_id, Some(profile_id)) {
|
||||
return Err(Error::Http {
|
||||
source: "Function profile response does not match the requested identity".into(),
|
||||
request_id,
|
||||
status_code: None,
|
||||
});
|
||||
}
|
||||
Ok(profile)
|
||||
}
|
||||
|
||||
pub(super) async fn profile_artifact_inner(&self, profile_id: &str) -> Result<Value> {
|
||||
let profile = self.profile_status_inner(profile_id).await?;
|
||||
if profile.status != FunctionProfileStatus::Complete {
|
||||
return Err(Error::Runtime {
|
||||
message: format!(
|
||||
"Function worker profile {profile_id} is not complete ({:?}): {}",
|
||||
profile.status,
|
||||
profile
|
||||
.error
|
||||
.as_deref()
|
||||
.unwrap_or("artifact is not available")
|
||||
),
|
||||
});
|
||||
}
|
||||
let (request_id, artifact): (_, Value) = self
|
||||
.profile_request(
|
||||
"artifact",
|
||||
json!({"job_id": self.job_id, "profile_id": profile_id}),
|
||||
)
|
||||
.await?;
|
||||
let valid = match profile.kind {
|
||||
FunctionProfileKind::Cpu => {
|
||||
artifact.get("$schema").and_then(Value::as_str)
|
||||
== Some("https://www.speedscope.app/file-format-schema.json")
|
||||
&& artifact
|
||||
.pointer("/shared/frames")
|
||||
.is_some_and(Value::is_array)
|
||||
&& artifact.get("profiles").is_some_and(Value::is_array)
|
||||
}
|
||||
FunctionProfileKind::Memory => {
|
||||
artifact.get("format").and_then(Value::as_str) == Some("lancedb.tracemalloc.v1")
|
||||
&& artifact.get("allocations").is_some_and(Value::is_array)
|
||||
}
|
||||
FunctionProfileKind::Gpu => {
|
||||
artifact.get("format").and_then(Value::as_str) == Some("lancedb.cuda.v1")
|
||||
&& artifact.get("traceEvents").is_some_and(Value::is_array)
|
||||
&& artifact.get("truncated").is_some_and(Value::is_boolean)
|
||||
}
|
||||
};
|
||||
if !valid {
|
||||
return Err(Error::Http {
|
||||
source: "Function profile artifact does not match its declared format".into(),
|
||||
request_id,
|
||||
status_code: None,
|
||||
});
|
||||
}
|
||||
Ok(artifact)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::error::Error;
|
||||
use crate::job::{
|
||||
FunctionProfileKind, FunctionProfileOptions, FunctionProfileStatus,
|
||||
FunctionProfileWaitOptions, Job,
|
||||
};
|
||||
use crate::remote::client::test_utils::client_with_handler;
|
||||
use crate::remote::job::RemoteJob;
|
||||
|
||||
fn metadata(kind: &str, status: &str) -> Value {
|
||||
json!({
|
||||
"profile_id": "profile-1", "job_id": "job-1", "worker_id": "worker-1",
|
||||
"execution_epoch": 3, "session_slot": 0, "kind": kind,
|
||||
"duration_seconds": 2.0, "status": status,
|
||||
"requested_at_millis": 1000, "deadline_at_millis": 46000,
|
||||
"expires_at_millis": 3601000, "completed_at_millis": null,
|
||||
"error": if status == "failed" { Some("gpu_unavailable") } else { None },
|
||||
"artifact_id": if status == "complete" { Some("profile-1") } else { None },
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn capture_sends_selected_identity_and_kind_specific_defaults() {
|
||||
for (kind, name, duration) in [
|
||||
(FunctionProfileKind::Cpu, "cpu", 10.0),
|
||||
(FunctionProfileKind::Memory, "memory", 10.0),
|
||||
(FunctionProfileKind::Gpu, "gpu", 5.0),
|
||||
] {
|
||||
let client = client_with_handler(move |request| {
|
||||
assert_eq!(request.url().path(), "/v1/jobs/profile/capture");
|
||||
let body: Value =
|
||||
serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
body,
|
||||
json!({
|
||||
"job_id":"job-1", "worker_id":"worker-1", "kind":name,
|
||||
"session_slot":2, "duration_seconds":duration,
|
||||
})
|
||||
);
|
||||
let mut value = metadata(name, "pending");
|
||||
value["session_slot"] = json!(2);
|
||||
value["duration_seconds"] = json!(duration);
|
||||
http::Response::builder()
|
||||
.status(202)
|
||||
.body(value.to_string())
|
||||
.unwrap()
|
||||
});
|
||||
let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into())));
|
||||
let profile = job
|
||||
.capture_profile(
|
||||
"worker-1",
|
||||
FunctionProfileOptions::new(kind).session_slot(2),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(profile.kind, kind);
|
||||
assert_eq!(profile.execution_epoch, 3);
|
||||
assert_eq!(profile.status, FunctionProfileStatus::Pending);
|
||||
assert_eq!(job.state(), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_capture_options_never_send_a_request() {
|
||||
let client =
|
||||
client_with_handler::<String>(|_| panic!("invalid capture sent an HTTP request"));
|
||||
let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into())));
|
||||
for (kind, duration) in [
|
||||
(FunctionProfileKind::Cpu, Duration::from_millis(999)),
|
||||
(FunctionProfileKind::Memory, Duration::from_secs(31)),
|
||||
(FunctionProfileKind::Gpu, Duration::from_millis(5001)),
|
||||
] {
|
||||
assert!(matches!(
|
||||
job.capture_profile(
|
||||
"worker-1",
|
||||
FunctionProfileOptions::new(kind).duration(duration)
|
||||
)
|
||||
.await,
|
||||
Err(Error::InvalidInput { .. })
|
||||
));
|
||||
}
|
||||
assert!(
|
||||
job.capture_profile("", FunctionProfileOptions::default())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
job.capture_profile("é".repeat(129), FunctionProfileOptions::default())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(job.profile_status("").await.is_err());
|
||||
assert!(job.profile_artifact("p".repeat(257)).await.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn response_identity_and_unsupported_servers_are_not_accepted_as_captures() {
|
||||
for mutation in [
|
||||
"profile_id",
|
||||
"job_id",
|
||||
"worker_id",
|
||||
"kind",
|
||||
"session_slot",
|
||||
"duration_seconds",
|
||||
] {
|
||||
let client = client_with_handler(move |_| {
|
||||
let mut value = metadata("gpu", "pending");
|
||||
value[mutation] = match mutation {
|
||||
"profile_id" => json!(""),
|
||||
"session_slot" => json!(1),
|
||||
"duration_seconds" => json!(3),
|
||||
"kind" => json!("cpu"),
|
||||
_ => json!("other"),
|
||||
};
|
||||
http::Response::builder()
|
||||
.status(200)
|
||||
.body(value.to_string())
|
||||
.unwrap()
|
||||
});
|
||||
let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into())));
|
||||
assert!(matches!(
|
||||
job.capture_profile(
|
||||
"worker-1",
|
||||
FunctionProfileOptions::new(FunctionProfileKind::Gpu)
|
||||
.duration(Duration::from_secs(2))
|
||||
)
|
||||
.await,
|
||||
Err(Error::Http { .. })
|
||||
));
|
||||
}
|
||||
let client =
|
||||
client_with_handler(|_| http::Response::builder().status(200).body("{}").unwrap());
|
||||
let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into())));
|
||||
assert!(matches!(
|
||||
job.profile_status("profile-1").await,
|
||||
Err(Error::Http { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn wait_timeout_is_resumable_and_does_not_cancel_or_refresh_the_job() {
|
||||
let complete = Arc::new(AtomicBool::new(false));
|
||||
let status = complete.clone();
|
||||
let client = client_with_handler(move |request| {
|
||||
assert_eq!(request.url().path(), "/v1/jobs/profile/status");
|
||||
let value = metadata(
|
||||
"gpu",
|
||||
if status.load(Ordering::SeqCst) {
|
||||
"complete"
|
||||
} else {
|
||||
"pending"
|
||||
},
|
||||
);
|
||||
http::Response::builder()
|
||||
.status(200)
|
||||
.body(value.to_string())
|
||||
.unwrap()
|
||||
});
|
||||
let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into())));
|
||||
let error = job
|
||||
.wait_for_profile(
|
||||
"profile-1",
|
||||
FunctionProfileWaitOptions::new().timeout(Duration::from_millis(50)),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(error, Error::Timeout { .. }));
|
||||
assert_eq!(job.state(), None);
|
||||
complete.store(true, Ordering::SeqCst);
|
||||
assert_eq!(
|
||||
job.wait_for_profile("profile-1", FunctionProfileWaitOptions::new())
|
||||
.await
|
||||
.unwrap()
|
||||
.status,
|
||||
FunctionProfileStatus::Complete
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn waiting_honors_poll_interval_and_rejects_execution_changes() {
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let count = calls.clone();
|
||||
let client = client_with_handler(move |_| {
|
||||
let next = count.fetch_add(1, Ordering::SeqCst);
|
||||
let mut value = metadata("gpu", if next == 0 { "pending" } else { "complete" });
|
||||
if next > 0 {
|
||||
value["execution_epoch"] = json!(4);
|
||||
}
|
||||
http::Response::builder()
|
||||
.status(200)
|
||||
.body(value.to_string())
|
||||
.unwrap()
|
||||
});
|
||||
let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into())));
|
||||
let started = tokio::time::Instant::now();
|
||||
let error = job
|
||||
.wait_for_profile(
|
||||
"profile-1",
|
||||
FunctionProfileWaitOptions::new().poll_interval(Duration::from_secs(5)),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("execution identity"));
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 2);
|
||||
assert!(started.elapsed() >= Duration::from_secs(5));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_capture_keeps_its_reason_and_is_not_a_failed_refresh() {
|
||||
let client = client_with_handler(|request| {
|
||||
assert_eq!(request.url().path(), "/v1/jobs/profile/status");
|
||||
http::Response::builder()
|
||||
.status(200)
|
||||
.body(metadata("gpu", "failed").to_string())
|
||||
.unwrap()
|
||||
});
|
||||
let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into())));
|
||||
let profile = job.profile_status("profile-1").await.unwrap();
|
||||
assert_eq!(profile.status, FunctionProfileStatus::Failed);
|
||||
assert_eq!(profile.error.as_deref(), Some("gpu_unavailable"));
|
||||
let error = job
|
||||
.wait_for_profile("profile-1", FunctionProfileWaitOptions::new())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(error, Error::Runtime { .. }));
|
||||
assert!(error.to_string().contains("gpu_unavailable"));
|
||||
assert_eq!(job.state(), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn artifacts_preserve_all_supported_formats_and_truncation_after_refresh() {
|
||||
for (kind, artifact) in [
|
||||
(
|
||||
"cpu",
|
||||
json!({"$schema":"https://www.speedscope.app/file-format-schema.json","shared":{"frames":[{"name":"work"}]},"profiles":[],"future_field":7}),
|
||||
),
|
||||
(
|
||||
"memory",
|
||||
json!({"format":"lancedb.tracemalloc.v1","allocations":[{"size_bytes":4096,"frames":[]}],"truncated":false}),
|
||||
),
|
||||
(
|
||||
"gpu",
|
||||
json!({"format":"lancedb.cuda.v1","traceEvents":[{"cat":"kernel","name":"compute","ph":"X","ts":10,"dur":2}],"truncated":true}),
|
||||
),
|
||||
] {
|
||||
let output = artifact.clone();
|
||||
let client = client_with_handler(move |request| {
|
||||
let body: Value =
|
||||
serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap();
|
||||
assert_eq!(body, json!({"job_id":"job-1","profile_id":"profile-1"}));
|
||||
let response = match request.url().path() {
|
||||
"/v1/jobs/profile/status" => metadata(kind, "complete"),
|
||||
"/v1/jobs/profile/artifact" => output.clone(),
|
||||
other => panic!("retrieval must not describe or restart refresh: {other}"),
|
||||
};
|
||||
http::Response::builder()
|
||||
.status(200)
|
||||
.body(response.to_string())
|
||||
.unwrap()
|
||||
});
|
||||
let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into())));
|
||||
assert_eq!(job.profile_artifact("profile-1").await.unwrap(), artifact);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn permission_missing_and_expired_errors_are_preserved_without_retry() {
|
||||
for code in [403, 404, 500] {
|
||||
for operation in ["capture", "status", "artifact"] {
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let seen = calls.clone();
|
||||
let client = client_with_handler(move |request| {
|
||||
let path = request.url().path();
|
||||
if operation == "artifact" && path.ends_with("/status") {
|
||||
return http::Response::builder()
|
||||
.status(200)
|
||||
.body(metadata("gpu", "complete").to_string())
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(path, format!("/v1/jobs/profile/{operation}"));
|
||||
seen.fetch_add(1, Ordering::SeqCst);
|
||||
http::Response::builder()
|
||||
.status(code)
|
||||
.body("profile is unavailable".to_owned())
|
||||
.unwrap()
|
||||
});
|
||||
let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into())));
|
||||
let error = match operation {
|
||||
"capture" => job
|
||||
.capture_profile("worker-1", FunctionProfileOptions::default())
|
||||
.await
|
||||
.unwrap_err(),
|
||||
"status" => job.profile_status("profile-1").await.unwrap_err(),
|
||||
_ => job.profile_artifact("profile-1").await.unwrap_err(),
|
||||
};
|
||||
assert!(
|
||||
matches!(error, Error::Http { status_code: Some(status), .. } if status.as_u16() == code)
|
||||
);
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unrelated_or_incomplete_artifacts_are_not_exported_as_profiles() {
|
||||
let client = client_with_handler(|request| {
|
||||
let value = if request.url().path().ends_with("/status") {
|
||||
metadata("gpu", "complete")
|
||||
} else {
|
||||
json!({"traceEvents":[]})
|
||||
};
|
||||
http::Response::builder()
|
||||
.status(200)
|
||||
.body(value.to_string())
|
||||
.unwrap()
|
||||
});
|
||||
let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into())));
|
||||
assert!(matches!(
|
||||
job.profile_artifact("profile-1").await,
|
||||
Err(Error::Http { .. })
|
||||
));
|
||||
let client = client_with_handler(|request| {
|
||||
assert!(request.url().path().ends_with("/status"));
|
||||
http::Response::builder()
|
||||
.status(200)
|
||||
.body(metadata("gpu", "capturing").to_string())
|
||||
.unwrap()
|
||||
});
|
||||
let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into())));
|
||||
assert!(matches!(
|
||||
job.profile_artifact("profile-1").await,
|
||||
Err(Error::Runtime { .. })
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ mod ipc_stream;
|
||||
mod optimize;
|
||||
mod prewarm;
|
||||
#[cfg(test)]
|
||||
mod profile_tests;
|
||||
#[cfg(test)]
|
||||
mod write_tests;
|
||||
|
||||
use self::insert::{RemoteWriteExec, WriteOp};
|
||||
@@ -24,7 +26,7 @@ use crate::index::Index;
|
||||
use crate::index::IndexStatistics;
|
||||
use crate::index::scalar::{FtsQuery, Operator};
|
||||
use crate::index::waiter::{MAX_WAIT, wait_for_index};
|
||||
use crate::job::Job;
|
||||
use crate::job::{FunctionProfile, FunctionProfileOptions, Job};
|
||||
use crate::materialized_view::{MaterializedViewInfo, RefreshMaterializedViewResult};
|
||||
use crate::query::wal_fusion::PkFusionMemory; // WAL-PK-FUSION: delete.
|
||||
use crate::query::{QueryFilter, QueryRequest, Select, VectorQueryRequest};
|
||||
@@ -330,6 +332,22 @@ impl<S: HttpSend> crate::job::JobHandle for FreshnessJob<S> {
|
||||
crate::job::JobHandle::stack(&self.inner, worker_id).await
|
||||
}
|
||||
|
||||
async fn capture_profile(
|
||||
&self,
|
||||
worker_id: &str,
|
||||
options: FunctionProfileOptions,
|
||||
) -> Result<FunctionProfile> {
|
||||
crate::job::JobHandle::capture_profile(&self.inner, worker_id, options).await
|
||||
}
|
||||
|
||||
async fn profile_status(&self, profile_id: &str) -> Result<FunctionProfile> {
|
||||
crate::job::JobHandle::profile_status(&self.inner, profile_id).await
|
||||
}
|
||||
|
||||
async fn profile_artifact(&self, profile_id: &str) -> Result<serde_json::Value> {
|
||||
crate::job::JobHandle::profile_artifact(&self.inner, profile_id).await
|
||||
}
|
||||
|
||||
async fn events(
|
||||
&self,
|
||||
request: crate::job::JobEventsRequest,
|
||||
@@ -433,6 +451,22 @@ impl<S: HttpSend> crate::job::JobHandle for MaterializedViewRefreshJob<S> {
|
||||
crate::job::JobHandle::stack(&self.inner, worker_id).await
|
||||
}
|
||||
|
||||
async fn capture_profile(
|
||||
&self,
|
||||
worker_id: &str,
|
||||
options: FunctionProfileOptions,
|
||||
) -> Result<FunctionProfile> {
|
||||
crate::job::JobHandle::capture_profile(&self.inner, worker_id, options).await
|
||||
}
|
||||
|
||||
async fn profile_status(&self, profile_id: &str) -> Result<FunctionProfile> {
|
||||
crate::job::JobHandle::profile_status(&self.inner, profile_id).await
|
||||
}
|
||||
|
||||
async fn profile_artifact(&self, profile_id: &str) -> Result<serde_json::Value> {
|
||||
crate::job::JobHandle::profile_artifact(&self.inner, profile_id).await
|
||||
}
|
||||
|
||||
async fn events(
|
||||
&self,
|
||||
request: crate::job::JobEventsRequest,
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use super::{FreshnessHeaders, FreshnessState, MaterializedViewRefreshJob};
|
||||
use crate::job::{
|
||||
FunctionProfileKind, FunctionProfileOptions, FunctionProfileStatus, FunctionProfileWaitOptions,
|
||||
Job,
|
||||
};
|
||||
use crate::materialized_view::RefreshMaterializedViewResult;
|
||||
use crate::remote::client::test_utils::client_with_handler;
|
||||
use crate::remote::job::RemoteJob;
|
||||
|
||||
#[tokio::test]
|
||||
async fn materialized_view_refresh_handles_forward_profile_operations_without_finishing_refresh() {
|
||||
let client = client_with_handler(|request| {
|
||||
let body: serde_json::Value =
|
||||
serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap();
|
||||
assert_eq!(body["job_id"], "job-1");
|
||||
let action = request.url().path();
|
||||
let value = if action == "/v1/jobs/profile/artifact" {
|
||||
json!({"format":"lancedb.cuda.v1", "traceEvents":[], "truncated":true})
|
||||
} else {
|
||||
assert!(matches!(
|
||||
action,
|
||||
"/v1/jobs/profile/capture" | "/v1/jobs/profile/status"
|
||||
));
|
||||
if action.ends_with("/capture") {
|
||||
assert_eq!(body["worker_id"], "worker-1");
|
||||
assert_eq!(body["kind"], "gpu");
|
||||
} else {
|
||||
assert_eq!(body["profile_id"], "profile-1");
|
||||
}
|
||||
json!({
|
||||
"profile_id":"profile-1", "job_id":"job-1", "worker_id":"worker-1",
|
||||
"execution_epoch":1, "session_slot":0, "kind":"gpu", "duration_seconds":2,
|
||||
"status":if action.ends_with("/capture") { "pending" } else { "complete" },
|
||||
"requested_at_millis":1000, "deadline_at_millis":46000,
|
||||
"expires_at_millis":3601000, "artifact_id":"profile-1"
|
||||
})
|
||||
};
|
||||
http::Response::builder()
|
||||
.status(200)
|
||||
.body(value.to_string())
|
||||
.unwrap()
|
||||
});
|
||||
let freshness = Arc::new(Mutex::new(FreshnessState::default()));
|
||||
let job: Job<RefreshMaterializedViewResult> =
|
||||
Job::new_typed(Box::new(MaterializedViewRefreshJob {
|
||||
inner: RemoteJob::new(client.clone(), "job-1".into()),
|
||||
client,
|
||||
db_name: "analytics".into(),
|
||||
name: "view".into(),
|
||||
namespace: vec![],
|
||||
identifier: "view".into(),
|
||||
server_version: Default::default(),
|
||||
sql_client: None,
|
||||
freshness: freshness.clone(),
|
||||
freshness_request: FreshnessHeaders::default(),
|
||||
}));
|
||||
let capture = job
|
||||
.capture_profile(
|
||||
"worker-1",
|
||||
FunctionProfileOptions::new(FunctionProfileKind::Gpu).duration(Duration::from_secs(2)),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(capture.status, FunctionProfileStatus::Pending);
|
||||
assert_eq!(
|
||||
job.wait_for_profile(&capture.profile_id, FunctionProfileWaitOptions::new())
|
||||
.await
|
||||
.unwrap()
|
||||
.status,
|
||||
FunctionProfileStatus::Complete
|
||||
);
|
||||
assert_eq!(
|
||||
job.profile_artifact(&capture.profile_id).await.unwrap()["truncated"],
|
||||
true
|
||||
);
|
||||
assert_eq!(job.state(), None);
|
||||
assert!(freshness.lock().unwrap().checkout_baseline.is_none());
|
||||
}
|
||||
Reference in New Issue
Block a user