Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Let agents list and abort their own unfinished uploads (#2559)

Joshua France61a5f0278bc5
diff --git a/docs/files-publication.md b/docs/files-publication.md
index 38636744e..837c1aa38 100644
--- a/docs/files-publication.md
+++ b/docs/files-publication.md
@@ -12,7 +12,7 @@ curl -fsS "$AGENT_API_URL/v1/files/upload-client" \
python3 /tmp/qm-upload.py path/to/report.pdf
```
-The helper prints the published file and its content URL only after completion. It needs Python and curl (curl carries every request, so it works through the sandbox's HTTPS egress proxy), holds at most one 64 MiB part in memory, retries transfers, and obtains another signed URL if one expires. A local `<filename>.qm-upload.json` tracks progress without storing credentials or signed URLs. Rerunning the same command resumes the same upload and returns the same artifact. If the file changed since an unfinished attempt, the helper cancels that attempt and starts a new upload, so it does not hold one of the four active-upload slots. `--state` selects another progress file; `--name` changes the published name. Keep the source file unchanged during transfer. The helper binds its progress to the API origin, actor, conversation scope, and complete part manifest.
+The helper prints the published file and its content URL only after completion. It needs Python and curl (curl carries every request, so it works through the sandbox's HTTPS egress proxy), holds at most one 64 MiB part in memory, retries transfers, and obtains another signed URL if one expires. A local `<filename>.qm-upload.json` tracks progress without storing credentials or signed URLs. Rerunning the same command resumes the same upload and returns the same artifact. If the file changed since an unfinished attempt, the helper cancels that attempt and starts a new upload, so it does not hold one of the four active-upload slots. `--state` selects another progress file; `--name` changes the published name. `--list` shows the caller's unfinished uploads in this conversation and `--abort ID...` aborts them; when the quota refuses a new upload, the helper prints that list and these commands. Keep the source file unchanged during transfer. The helper binds its progress to the API origin, actor, conversation scope, and complete part manifest.
The file belongs to the conversation scope. An agent token cannot publish into another scope or inspect another scope's upload sessions, even if its actor belongs to both scopes. Retirement of a sandbox does not affect a completed file. An unfinished upload is not a file and does not appear in Files.
@@ -23,6 +23,7 @@ Each JSON request requires the existing authenticated agent or user identity. A
| Method | Endpoint | Meaning |
| ------ | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| POST | `/v1/files/uploads` | Begin with `name`, optional `mimetype`, optional `scopeId`, `sizeBytes`, ordered `checksums`, optional `requestId` |
+| GET | `/v1/files/uploads` | List the caller's unfinished sessions in this scope; `elsewhere` counts ones in other scopes |
| GET | `/v1/files/uploads/:id` | Read the caller's session state |
| POST | `/v1/files/uploads/:id/parts/:number` | Obtain a signed PUT URL plus required headers |
| POST | `/v1/files/uploads/:id/complete` | Verify uploaded parts and publish the file |
@@ -30,7 +31,7 @@ Each JSON request requires the existing authenticated agent or user identity. A
Split bytes into 64 MiB parts and supply each part's base64 SHA-256 checksum. An empty file has one empty part and the SHA-256 checksum of empty bytes. `requestId` is 32 lowercase hexadecimal characters; persist it before initiation to make response-loss retries idempotent. Reusing it with another manifest is rejected. Upload every part using the returned headers, including the signed content length and SHA-256 checksum. Completion uses S3's actual part sizes, checksums, and ETags rather than accepting a client claim that the transfer succeeded.
-The limit is 100 GiB per file, four active uploads per actor, and 500 GiB of active declared bytes per actor. Sessions expire after 24 hours; signed URLs last at most 15 minutes and never outlast their session. Abort and completion have mutually exclusive durable state transitions. Once completion has begun, retry completion instead of aborting. Core can recover completion after S3 succeeded but a response or database write failed. Deleting an already-published artifact records an ID-only tombstone. Publication and deletion serialize on that ID, so recovery cannot recreate the file even if the upload state update failed after publication.
+The limit is 100 GiB per file, four active uploads per actor, and 500 GiB of active declared bytes per actor. Sessions expire after 24 hours and the sweeper then aborts them; a quota refusal (`429 upload_quota`) carries the same listing as `GET /v1/files/uploads`; signed URLs last at most 15 minutes and never outlast their session. Abort and completion have mutually exclusive durable state transitions. Once completion has begun, retry completion instead of aborting. Core can recover completion after S3 succeeded but a response or database write failed. Deleting an already-published artifact records an ID-only tombstone. Publication and deletion serialize on that ID, so recovery cannot recreate the file even if the upload state update failed after publication.
S3 stores a SHA-256 composite checksum for multipart objects. This is a checksum of the ordered part checksums, with a part-count suffix. It is not the SHA-256 of the entire file: these artifacts intentionally have `sha256: null`. Their unique blob key and server-verified multipart manifest identify the uploaded bytes.
diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.ts
index 5a53f744a..fcd2b9993 100644
--- a/src/api/agent-api-catalog.ts
+++ b/src/api/agent-api-catalog.ts
@@ -87,7 +87,7 @@ const FAMILIES: AgentApiFamily[] = [
},
{
guidance:
- 'Publish important outputs to durable Files before retiring a sandbox. Run: curl -fsS "$AGENT_API_URL/v1/files/upload-client" -H "x-agent-capability: $AGENT_API_TOKEN" -o /tmp/qm-upload.py && python3 /tmp/qm-upload.py path/to/file. The helper uploads directly to S3, retries parts, and resumes when rerun with the same file. Only final success means the file is published. Files are saved to this conversation\'s scope. Up to 100 GiB per file, including empty files.',
+ 'Publish important outputs to durable Files before retiring a sandbox. Run: curl -fsS "$AGENT_API_URL/v1/files/upload-client" -H "x-agent-capability: $AGENT_API_TOKEN" -o /tmp/qm-upload.py && python3 /tmp/qm-upload.py path/to/file. The helper uploads directly to S3, retries parts, and resumes when rerun with the same file. Only final success means the file is published. Files are saved to this conversation\'s scope. Up to 100 GiB per file, including empty files. If the upload quota is full, the helper\'s --list and --abort ID free slots.',
routes: [
{
method: "GET",
@@ -100,6 +100,11 @@ const FAMILIES: AgentApiFamily[] = [
summary:
"begin a direct upload with {name,mimetype?,scopeId?,sizeBytes,checksums,requestId?}; checksums are ordered base64 SHA-256 hashes of 64 MiB parts",
},
+ {
+ method: "GET",
+ path: "/v1/files/uploads",
+ summary: "list your unfinished uploads here",
+ },
{ method: "GET", path: "/v1/files/uploads/:id", summary: "inspect an owned upload session" },
{
method: "POST",
diff --git a/src/api/routes/file-uploads.ts b/src/api/routes/file-uploads.ts
index 3bdedae37..61e139e6a 100644
--- a/src/api/routes/file-uploads.ts
+++ b/src/api/routes/file-uploads.ts
@@ -8,6 +8,28 @@ import { withActor, type ApiCtx, type Route } from "./route.ts";
type Uploads = NonNullable<ApiCtx["deps"]["fileUploads"]>;
type Upload = NonNullable<Awaited<ReturnType<Uploads["get"]>>>;
+const visible = async ({ app, capability }: ApiCtx, actorId: string, upload: Upload) =>
+ upload.actorId === actorId &&
+ (!capability || upload.scopeId === capability.scopeId) &&
+ (await app.belongsToScope(actorId, upload.scopeId));
+
+const unfinished = async (ctx: ApiCtx, uploads: Uploads, actorId: string) => {
+ const rows = await uploads.list(actorId);
+ const shown = [];
+ for (const row of rows)
+ if (await visible(ctx, actorId, row))
+ shown.push({
+ id: row.id,
+ name: row.name,
+ sizeBytes: row.sizeBytes,
+ state: row.state,
+ createdAt: row.createdAt,
+ lastActivityAt: row.lastActivityAt,
+ expiresAt: row.expiresAt,
+ });
+ return { uploads: shown, elsewhere: rows.length - shown.length };
+};
+
const uploadRoute =
(handle: (ctx: ApiCtx, uploads: Uploads, actorId: string) => Promise<void>) =>
async (ctx: ApiCtx): Promise<void> => {
@@ -20,26 +42,26 @@ const uploadRoute =
try {
return await handle(ctx, uploads, actorId);
} catch (error) {
- if (error instanceof FileUploadError)
- return sendJson(res, error.status, { error: error.code, message: error.message });
- throw error;
+ if (!(error instanceof FileUploadError)) throw error;
+ return sendJson(res, error.status, {
+ error: error.code,
+ message: error.message,
+ ...(error.code === "upload_quota" ? await unfinished(ctx, uploads, actorId) : {}),
+ });
}
};
const ownedUpload = (handle: (ctx: ApiCtx, uploads: Uploads, upload: Upload, actorId: string) => Promise<void>) =>
uploadRoute(async (ctx, uploads, actorId) => {
- const { res, app, capability, params } = ctx;
- const upload = await uploads.get(params.id!);
- if (
- !upload ||
- upload.actorId !== actorId ||
- (capability && upload.scopeId !== capability.scopeId) ||
- !(await app.belongsToScope(actorId, upload.scopeId))
- )
- return sendJson(res, 404, { error: "not_found" });
+ const upload = await uploads.get(ctx.params.id!);
+ if (!upload || !(await visible(ctx, actorId, upload))) return sendJson(ctx.res, 404, { error: "not_found" });
return handle(ctx, uploads, upload, actorId);
});
+const listUploads = uploadRoute(async (ctx, uploads, actorId) =>
+ sendJson(ctx.res, 200, await unfinished(ctx, uploads, actorId)),
+);
+
const uploadClient = uploadRoute(async ({ res }) => {
const script = await readFile(new URL("../../files/upload-client.py", import.meta.url), "utf8");
res.writeHead(200, { "content-type": "text/x-python; charset=utf-8", "cache-control": "private, max-age=300" });
@@ -99,6 +121,7 @@ const abortUpload = ownedUpload(async ({ res, deps }, uploads, upload, actorId)
export const fileUploadRoutes: ReadonlyArray<Route<ApiCtx>> = [
{ method: "GET", path: "/v1/files/upload-client", actor: "query.viewer", auth: "either", handle: uploadClient },
+ { method: "GET", path: "/v1/files/uploads", actor: "query.viewer", auth: "either", handle: listUploads },
{ method: "GET", path: "/v1/files/uploads/:id", actor: "query.viewer", auth: "either", handle: getUpload },
...withActor("body.principalId", [
{ method: "POST", path: "/v1/files/uploads", auth: "either", handle: beginUpload },
diff --git a/src/files/direct-file-upload.ts b/src/files/direct-file-upload.ts
index 8c092068a..57b96d542 100644
--- a/src/files/direct-file-upload.ts
+++ b/src/files/direct-file-upload.ts
@@ -25,7 +25,6 @@ import { createSweeper } from "../util/sweeper.ts";
export const FILE_UPLOAD_PART_SIZE = 64 * 1024 * 1024;
const MAX_DIRECT_FILE_BYTES = 100 * 1024 ** 3;
const UPLOAD_TTL_MS = 24 * 60 * 60 * 1000;
-const UPLOAD_IDLE_MS = 60 * 60 * 1000;
const URL_TTL_SECONDS = 15 * 60;
const SHA256_BASE64 = /^[A-Za-z0-9+/]{43}=$/;
@@ -42,6 +41,7 @@ export interface DirectFileUploads {
},
): Promise<FileUpload>;
get(id: string): Promise<FileUpload | null>;
+ list(actorId: string): Promise<FileUpload[]>;
sign(id: string, partNumber: number): Promise<{ url: string; headers: Record<string, string>; expiresAt: number }>;
complete(id: string): Promise<FileArtifact>;
abort(id: string): Promise<void>;
@@ -158,7 +158,8 @@ export function createDirectFileUploads(options: {
uploadId: "",
state: "pending",
createdAt: now(),
- expiresAt: now() + UPLOAD_IDLE_MS,
+ lastActivityAt: now(),
+ expiresAt: now() + UPLOAD_TTL_MS,
};
const matches = (existing: FileUpload) =>
existing.actorId === row.actorId &&
@@ -195,6 +196,7 @@ export function createDirectFileUploads(options: {
return row;
},
get: (id) => store.get(id),
+ list: (actorId) => store.active(actorId, now()),
async sign(id, partNumber) {
const row = await requireRow(id);
if (row.state !== "pending" || row.expiresAt <= now())
@@ -202,10 +204,9 @@ export function createDirectFileUploads(options: {
if (!Number.isSafeInteger(partNumber) || partNumber < 1 || partNumber > row.checksums.length)
throw new FileUploadError("invalid part number");
const length = Math.min(row.partSize, row.sizeBytes - (partNumber - 1) * row.partSize);
- const expiresAt = Math.min(row.createdAt + UPLOAD_TTL_MS, now() + UPLOAD_IDLE_MS);
- if (!(await store.extend(id, expiresAt))) throw new FileUploadError("upload is not pending or has expired", 409);
- const expiresIn = Math.min(URL_TTL_SECONDS, Math.floor((expiresAt - now()) / 1000));
+ const expiresIn = Math.min(URL_TTL_SECONDS, Math.floor((row.expiresAt - now()) / 1000));
if (expiresIn < 1) throw new FileUploadError("upload expired", 409);
+ if (!(await store.touch(id, now()))) throw new FileUploadError("upload is not pending or has expired", 409);
const checksum = row.checksums[partNumber - 1]!;
const url = await presign(
new UploadPartCommand({
diff --git a/src/files/file-upload-store.ts b/src/files/file-upload-store.ts
index 58d260995..886ddb3f1 100644
--- a/src/files/file-upload-store.ts
+++ b/src/files/file-upload-store.ts
@@ -16,13 +16,15 @@ export interface FileUpload {
state: FileUploadState;
expiresAt: number;
createdAt: number;
+ lastActivityAt: number;
}
export interface FileUploadStore {
insert(upload: FileUpload): Promise<void>;
get(id: string): Promise<FileUpload | null>;
transition(id: string, from: FileUploadState[], to: FileUploadState): Promise<boolean>;
- extend(id: string, expiresAt: number): Promise<boolean>;
+ touch(id: string, at: number): Promise<boolean>;
+ active(actorId: string, now: number): Promise<FileUpload[]>;
expired(now: number): Promise<FileUpload[]>;
}
@@ -39,6 +41,8 @@ export class FileUploadError extends Error {
export const MAX_ACTIVE_UPLOADS = 4;
const MAX_ACTIVE_UPLOAD_BYTES = 500 * 1024 ** 3;
+const HOLDS_QUOTA =
+ "actor_id=$1 AND state NOT IN ('complete','aborted','failed') AND NOT (state='pending' AND expires_at <= $2)";
export function createPostgresFileUploadStore(connectionString: string): FileUploadStore {
const db = createPgPool(connectionString, [
@@ -74,7 +78,7 @@ export function createPostgresFileUploadStore(connectionString: string): FileUpl
await withPgTransaction(await db.pool(), async (client) => {
await client.query("SELECT pg_advisory_xact_lock(hashtext($1))", [`file-uploads:${upload.actorId}`]);
const result = await client.query(
- "SELECT count(*) AS count, coalesce(sum(size_bytes),0) AS bytes FROM file_uploads WHERE actor_id=$1 AND state NOT IN ('complete','aborted','failed') AND NOT (state='pending' AND expires_at <= $2)",
+ `SELECT count(*) AS count, coalesce(sum(size_bytes),0) AS bytes FROM file_uploads WHERE ${HOLDS_QUOTA}`,
[upload.actorId, upload.createdAt],
);
if (
@@ -82,7 +86,7 @@ export function createPostgresFileUploadStore(connectionString: string): FileUpl
Number(result.rows[0].bytes) + upload.sizeBytes > MAX_ACTIVE_UPLOAD_BYTES
)
throw new FileUploadError(
- "active upload quota exceeded; finish or DELETE /v1/files/uploads/:id an unfinished upload, or wait an hour for idle ones to expire",
+ `active upload quota exceeded: at most ${MAX_ACTIVE_UPLOADS} unfinished uploads or ${MAX_ACTIVE_UPLOAD_BYTES / 1024 ** 3} GiB at once. Finish or abort (DELETE /v1/files/uploads/:id) one of the uploads listed here; unfinished uploads are aborted 24 hours after they start`,
429,
"upload_quota",
);
@@ -102,16 +106,21 @@ export function createPostgresFileUploadStore(connectionString: string): FileUpl
.rowCount === 1
);
},
- async extend(id, expiresAt) {
+ async touch(id, at) {
return (
(
await db.query(
- "UPDATE file_uploads SET expires_at=$2, data=jsonb_set(data,'{expiresAt}',to_jsonb($2::bigint)) WHERE id=$1 AND state='pending'",
- [id, expiresAt],
+ "UPDATE file_uploads SET data=jsonb_set(data,'{lastActivityAt}',to_jsonb($2::bigint)) WHERE id=$1 AND state='pending'",
+ [id, at],
)
).rowCount === 1
);
},
+ async active(actorId, now) {
+ return (
+ await db.q(`SELECT data,state FROM file_uploads WHERE ${HOLDS_QUOTA} ORDER BY expires_at`, [actorId, now])
+ ).map(decode);
+ },
async expired(now) {
return (
await db.q(
diff --git a/src/files/upload-client.py b/src/files/upload-client.py
index 3f3c663a9..bf2d8e156 100644
--- a/src/files/upload-client.py
+++ b/src/files/upload-client.py
@@ -15,9 +15,10 @@ PART_SIZE = 64 * 1024 * 1024
class RequestError(RuntimeError):
- def __init__(self, status, message):
+ def __init__(self, status, message, content=b""):
super().__init__(message)
self.status = status
+ self.content = content
def quote(value):
@@ -52,7 +53,7 @@ def request(method, url, data=None, headers=None):
if 200 <= status < 300:
return content
if status < 500 and (status != 429 or error_code(content) == "upload_quota"):
- raise RequestError(status, f"request failed ({status}): {content[:4096].decode(errors='replace')}")
+ raise RequestError(status, f"request failed ({status}): {content[:4096].decode(errors='replace')}", content)
failure = f"HTTP {status}: {content[:200].decode(errors='replace')}"
else:
failure = result.stderr.decode(errors="replace").strip() or f"curl exited {result.returncode}"
@@ -67,6 +68,18 @@ def api(method, path, data=None):
return json.loads(request(method, os.environ["AGENT_API_URL"].rstrip("/") + path, body, headers))
+def describe(listing):
+ lines = [f"{'id':32} {'state':10} {'size':>12} {'started (UTC)':16} {'last activity (UTC)':19} name"]
+ when = lambda ms: time.strftime("%Y-%m-%d %H:%M", time.gmtime(ms / 1000)) if ms else "-"
+ for upload in listing["uploads"]:
+ lines.append(f"{upload['id']:32} {upload['state']:10} {upload['sizeBytes']:>12} {when(upload['createdAt']):16} {when(upload.get('lastActivityAt')):19} {upload['name']}")
+ if not listing["uploads"]:
+ lines.append("(no unfinished uploads in this conversation)")
+ if listing["elsewhere"]:
+ lines.append(f"{listing['elsewhere']} more unfinished upload(s) belong to other conversations and can only be aborted there.")
+ return "\n".join(lines)
+
+
def save(path, state):
temporary = path.with_name(path.name + ".tmp")
fd = os.open(temporary, os.O_CREAT | os.O_TRUNC | os.O_WRONLY, 0o600)
@@ -79,11 +92,23 @@ def save(path, state):
def main():
parser = argparse.ArgumentParser(description="Publish a file durably to Files with resumable direct uploads")
- parser.add_argument("file", type=Path)
+ parser.add_argument("file", type=Path, nargs="?")
parser.add_argument("--state", type=Path)
parser.add_argument("--scope")
parser.add_argument("--name")
+ parser.add_argument("--list", action="store_true", help="list your unfinished uploads")
+ parser.add_argument("--abort", nargs="+", metavar="ID", help="abort unfinished uploads by id")
args = parser.parse_args()
+ if args.list:
+ print(describe(api("GET", "/v1/files/uploads")))
+ return
+ if args.abort:
+ for upload_id in args.abort:
+ api("DELETE", f"/v1/files/uploads/{upload_id}")
+ print(f"aborted {upload_id}")
+ return
+ if args.file is None:
+ parser.error("a file path, --list or --abort is required")
state_path = args.state or args.file.with_name(args.file.name + ".qm-upload.json")
checksums = []
size = 0
@@ -132,7 +157,13 @@ def main():
state = {"id": uuid.uuid4().hex, "manifest": manifest, "destination": destination, "next": 1}
save(state_path, state)
if status is None:
- status = api("POST", "/v1/files/uploads", {**manifest, "requestId": state["id"]})["upload"]
+ try:
+ status = api("POST", "/v1/files/uploads", {**manifest, "requestId": state["id"]})["upload"]
+ except RequestError as error:
+ if error_code(error.content) != "upload_quota":
+ raise
+ me = f"python3 {sys.argv[0]}"
+ raise RuntimeError(f"{json.loads(error.content)['message']}\n\n{describe(json.loads(error.content))}\n\nAbort one with: {me} --abort ID\nThen rerun this upload. List again with: {me} --list") from None
if status["state"] == "pending":
with args.file.open("rb") as source:
for number in range(state["next"], len(checksums) + 1):
diff --git a/test/direct-file-upload.test.ts b/test/direct-file-upload.test.ts
index 423b7f398..70747130e 100644
--- a/test/direct-file-upload.test.ts
+++ b/test/direct-file-upload.test.ts
@@ -25,12 +25,20 @@ function fixture() {
row.state = to;
return true;
},
- async extend(id, expiresAt) {
+ async touch(id, at) {
const row = rows.get(id);
- if (!row || row.state !== "pending") return false;
- row.expiresAt = expiresAt;
+ if (row?.state !== "pending") return false;
+ row.lastActivityAt = at;
return true;
},
+ async active(actorId, now) {
+ return [...rows.values()].filter(
+ (r) =>
+ r.actorId === actorId &&
+ !["complete", "aborted", "failed"].includes(r.state) &&
+ !(r.state === "pending" && r.expiresAt <= now),
+ );
+ },
async expired(now) {
return [...rows.values()].filter(
(r) => r.expiresAt <= now && r.state !== "complete" && r.state !== "aborted" && r.state !== "failed",
@@ -122,22 +130,22 @@ function fixture() {
};
}
-test("an idle pending upload expires after an hour; signing parts keeps it alive up to a day", async () => {
+test("idle uploads keep their slot until the 24h cap; signing records last activity", async () => {
const hour = 60 * 60 * 1000;
const f = fixture();
- const idle = await f.service.begin(f.input);
+ const row = await f.service.begin(f.input);
+ f.advance(23 * hour);
+ await f.service.sign(row.id, 1);
+ assert.equal((await f.store.get(row.id))!.lastActivityAt, row.createdAt + 23 * hour);
+ assert.deepEqual(
+ (await f.service.list("U1")).map((r) => r.id),
+ [row.id],
+ );
f.advance(hour);
- await assert.rejects(f.service.sign(idle.id, 1), /expired/);
+ await assert.rejects(f.service.sign(row.id, 1), /expired/);
+ assert.deepEqual(await f.service.list("U1"), []);
await f.service.sweep();
- assert.equal((await f.store.get(idle.id))!.state, "aborted");
-
- const busy = await f.service.begin(f.input);
- for (let i = 0; i < 24; i++) {
- await f.service.sign(busy.id, 1);
- f.advance(hour - 1);
- }
- await assert.rejects(f.service.sign(busy.id, 1), /expired/);
- assert.equal((await f.store.get(busy.id))!.expiresAt, busy.createdAt + 24 * hour);
+ assert.equal((await f.store.get(row.id))!.state, "aborted");
});
test("signed parts bind the exact size, checksum, upload and number; unpublished parts are invisible", async () => {
diff --git a/test/file-upload-client.test.ts b/test/file-upload-client.test.ts
index 25e038f95..832ad0aa5 100644
--- a/test/file-upload-client.test.ts
+++ b/test/file-upload-client.test.ts
@@ -230,3 +230,66 @@ test("publisher starts a fresh upload when the saved session was aborted or expi
}
}
});
+
+test("publisher shows what holds a full quota and can list and abort those uploads", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "qm-publisher-"));
+ const requests: string[] = [];
+ const stuck = "c".repeat(32);
+ const listing = {
+ uploads: [{ id: stuck, name: "stuck.bin", sizeBytes: 9, state: "pending", createdAt: 0, lastActivityAt: 60_000 }],
+ elsewhere: 2,
+ };
+ const server = createServer(async (request, response) => {
+ for await (const _ of request) void _;
+ requests.push(`${request.method} ${request.url}`);
+ response.setHeader("content-type", "application/json");
+ if (request.method === "DELETE") response.end(JSON.stringify({ ok: true }));
+ else if (request.method === "GET" && request.url === "/v1/files/uploads") response.end(JSON.stringify(listing));
+ else if (request.method === "POST" && request.url === "/v1/files/uploads")
+ response.writeHead(429).end(JSON.stringify({ error: "upload_quota", message: "quota is full", ...listing }));
+ else response.writeHead(404).end("{}");
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const address = server.address();
+ assert.ok(address && typeof address !== "string");
+ const origin = `http://127.0.0.1:${address.port}`;
+ const source = join(directory, "next.txt");
+ await writeFile(source, "abc");
+ const token =
+ Buffer.from(JSON.stringify({ actorId: "user", scopeId: "personal:user" })).toString("base64url") + ".signature";
+ const run = (...args: string[]) =>
+ new Promise<{ code: number | null; out: string }>((resolve, reject) => {
+ let out = "";
+ const child = spawn(
+ "python3",
+ [fileURLToPath(new URL("../src/files/upload-client.py", import.meta.url)), ...args],
+ {
+ env: { ...process.env, AGENT_API_URL: origin, AGENT_API_TOKEN: token },
+ },
+ );
+ child.stdout.on("data", (chunk) => (out += chunk));
+ child.stderr.on("data", (chunk) => (out += chunk));
+ child.on("error", reject);
+ child.on("exit", (code) => resolve({ code, out }));
+ });
+ try {
+ const refused = await run(source);
+ assert.equal(refused.code, 1);
+ assert.match(refused.out, /quota is full/);
+ assert.ok(refused.out.split("\n").some((line) => line.startsWith(stuck) && line.endsWith("stuck.bin")));
+ assert.match(refused.out, /1970-01-01 00:01/);
+ assert.match(refused.out, /2 more unfinished upload/);
+ assert.match(refused.out, /--abort ID/);
+ assert.equal(requests.filter((r) => r === "POST /v1/files/uploads").length, 1);
+
+ const listed = await run("--list");
+ assert.equal(listed.code, 0);
+ assert.match(listed.out, /stuck\.bin/);
+
+ assert.equal((await run("--abort", stuck)).code, 0);
+ assert.ok(requests.includes(`DELETE /v1/files/uploads/${stuck}`));
+ } finally {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ await rm(directory, { recursive: true, force: true });
+ }
+});
diff --git a/test/file-upload-routes.test.ts b/test/file-upload-routes.test.ts
index 23465ff22..54e472282 100644
--- a/test/file-upload-routes.test.ts
+++ b/test/file-upload-routes.test.ts
@@ -7,7 +7,7 @@ import { buildApp } from "./support/build-app.ts";
import { createServer } from "../src/api/server.ts";
import { mintCapabilityToken, CONTROL_PLANE_AUD } from "../src/auth/capability-token.ts";
import type { DirectFileUploads } from "../src/files/direct-file-upload.ts";
-import type { FileUpload } from "../src/files/file-upload-store.ts";
+import { FileUploadError, type FileUpload } from "../src/files/file-upload-store.ts";
import { scopeId } from "../src/types.ts";
import { testConfig } from "./support/test-config.ts";
@@ -27,6 +27,7 @@ const upload: FileUpload = {
state: "pending",
expiresAt: Date.now() + 60_000,
createdAt: Date.now(),
+ lastActivityAt: Date.now(),
};
let server: Server;
let base: string;
@@ -39,6 +40,9 @@ const fake: DirectFileUploads = {
async get(id) {
return id === upload.id ? upload : null;
},
+ async list(actorId) {
+ return [upload, { ...upload, id: "b".repeat(32), scopeId: channel }].filter((u) => u.actorId === actorId);
+ },
async sign() {
calls++;
return { url: "https://example.invalid/upload", headers: {}, expiresAt: Date.now() };
@@ -150,3 +154,61 @@ test("disabled initiation preserves existing session recovery", async () => {
await new Promise<void>((resolve) => recovery.close(() => resolve()));
}
});
+
+test("listing shows only the caller's unfinished uploads in the token scope and counts the rest", async () => {
+ type Listing = { uploads: FileUpload[]; elsewhere: number };
+ const body = async (cap: string) => (await (await call("/v1/files/uploads", cap)).json()) as Listing;
+ assert.deepEqual(await body(await token("U1")), {
+ uploads: [
+ {
+ id: upload.id,
+ name: upload.name,
+ sizeBytes: 1,
+ state: "pending",
+ createdAt: upload.createdAt,
+ lastActivityAt: upload.lastActivityAt,
+ expiresAt: upload.expiresAt,
+ },
+ ],
+ elsewhere: 1,
+ });
+ assert.deepEqual(
+ (await body(await token("U1", channel))).uploads.map((u) => u.id),
+ ["b".repeat(32)],
+ );
+ assert.deepEqual(await body(await token("U2", scopeId("personal", "U2"))), { uploads: [], elsewhere: 0 });
+});
+
+test("a quota refusal tells the caller which of its uploads hold the quota", async () => {
+ const built = buildApp(testConfig({ signingSecret: secret }));
+ built.app.belongsToScope = async () => true;
+ built.app.authorizesCapabilityScope = async () => true;
+ const full = createServer(built.app, {
+ signingSecret: secret,
+ filesDirectUploadsEnabled: true,
+ fileUploads: {
+ ...fake,
+ async begin() {
+ throw new FileUploadError("quota", 429, "upload_quota");
+ },
+ },
+ });
+ await new Promise<void>((resolve) => full.listen(0, resolve));
+ try {
+ const response = await fetch(`http://localhost:${(full.address() as AddressInfo).port}/v1/files/uploads`, {
+ method: "POST",
+ headers: { "x-agent-capability": await token("U1"), "content-type": "application/json" },
+ body: JSON.stringify({ name: "next.txt" }),
+ });
+ assert.equal(response.status, 429);
+ const result = (await response.json()) as { error: string; uploads: FileUpload[]; elsewhere: number };
+ assert.equal(result.error, "upload_quota");
+ assert.deepEqual(
+ result.uploads.map((u) => u.name),
+ ["private.txt"],
+ );
+ assert.equal(result.elsewhere, 1);
+ } finally {
+ await new Promise<void>((resolve) => full.close(() => resolve()));
+ }
+});
diff --git a/test/postgres-file-upload-store.test.ts b/test/postgres-file-upload-store.test.ts
index 3a392f28c..8ae9a84c8 100644
--- a/test/postgres-file-upload-store.test.ts
+++ b/test/postgres-file-upload-store.test.ts
@@ -30,6 +30,7 @@ test(
state: "pending",
expiresAt: Date.now() + 60_000,
createdAt: Date.now(),
+ lastActivityAt: Date.now(),
});
const uploads = Array.from({ length: MAX_ACTIVE_UPLOADS + 3 }, row);
const results = await Promise.allSettled(uploads.map((r, i) => (i % 2 ? first : second).insert(r)));
@@ -73,6 +74,7 @@ test("expired upload batches rotate durably without starving later rows", { skip
uploadId: "upload",
state: "completing",
createdAt: now,
+ lastActivityAt: now,
expiresAt: i,
});
}
@@ -106,6 +108,7 @@ test("terminal failed uploads release active quota", { skip: !url }, async () =>
uploadId: "upload",
state: "completing",
createdAt: Date.now(),
+ lastActivityAt: Date.now(),
expiresAt: Date.now(),
});
await store.transition(id, ["completing"], "failed");
@@ -113,30 +116,39 @@ test("terminal failed uploads release active quota", { skip: !url }, async () =>
assert.equal((await store.get(ids.at(-1)!))!.state, "failed");
});
-test("expired pending uploads stop holding quota; extend only moves pending rows", { skip: !url }, async () => {
- const store = createPostgresFileUploadStore(url!);
- const actorId = `idle-quota-${randomUUID()}`;
- const now = Date.now();
- const row = (expiresAt: number): FileUpload => ({
- id: randomUUID().replaceAll("-", ""),
- actorId,
- scopeId: scopeId("personal", actorId),
- name: "file",
- mimetype: "text/plain",
- sizeBytes: 1,
- partSize: 64 * 1024 * 1024,
- checksums: ["hash"],
- uploadId: "upload",
- state: "pending",
- createdAt: now,
- expiresAt,
- });
- const stale = Array.from({ length: MAX_ACTIVE_UPLOADS }, () => row(now - 1));
- for (const r of stale) await store.insert(r);
- const live = row(now + 60_000);
- await store.insert(live);
- assert.ok(await store.extend(live.id, now + 120_000));
- assert.equal((await store.get(live.id))!.expiresAt, now + 120_000);
- await store.transition(stale[0]!.id, ["pending"], "aborted");
- assert.equal(await store.extend(stale[0]!.id, now + 120_000), false);
-});
+test(
+ "active lists the actor's unfinished uploads that hold quota; touch records activity",
+ { skip: !url },
+ async () => {
+ const store = createPostgresFileUploadStore(url!);
+ const actorId = `active-uploads-${randomUUID()}`;
+ const now = Date.now();
+ const row = (expiresAt: number, owner = actorId): FileUpload => ({
+ id: randomUUID().replaceAll("-", ""),
+ actorId: owner,
+ scopeId: scopeId("personal", owner),
+ name: "file",
+ mimetype: "text/plain",
+ sizeBytes: 1,
+ partSize: 64 * 1024 * 1024,
+ checksums: ["hash"],
+ uploadId: "upload",
+ state: "pending",
+ createdAt: now,
+ lastActivityAt: now,
+ expiresAt,
+ });
+ const stale = Array.from({ length: MAX_ACTIVE_UPLOADS }, () => row(now - 1));
+ for (const r of stale) await store.insert(r);
+ const live = row(now + 60_000);
+ const aborted = row(now + 60_000);
+ await store.insert(live);
+ await store.insert(aborted);
+ await store.transition(aborted.id, ["pending"], "aborted");
+ await store.insert(row(now + 60_000, `other-${actorId}`));
+ assert.ok(await store.touch(live.id, now + 5_000));
+ assert.equal(await store.touch(aborted.id, now + 5_000), false);
+ assert.deepEqual(await store.active(actorId, now), [{ ...live, lastActivityAt: now + 5_000 }]);
+ assert.equal((await store.get(aborted.id))!.lastActivityAt, now);
+ },
+);