diff --git a/docs/architecture/sharing.md b/docs/architecture/sharing.md index a3e7981929..109a82f9a4 100644 --- a/docs/architecture/sharing.md +++ b/docs/architecture/sharing.md @@ -112,6 +112,22 @@ feature page). A client draws a conversation's saved state with one `conversation.saved_status` call, and a user erasure takes the user's conversation rows, saved ones included. +## Collection spend policy + +`collection.budget_set` lets a collection's admin change its rolling 24-hour USD cap, +its separate named-user cap and its budget warning inbox. An omitted field keeps its +stored value; a zero cap inherits the server default, and an empty inbox disables +warnings. A warning inbox must belong to the same collection. Personal, missing and +retired collections cannot be configured through this operation. + +The audited operation holds the directory-row claim from read through write and carries +every unrelated directory column forward. It changes no collection membership, tree, +visibility or login state. `namespace.register` continues to refuse collection names. +Budget status and admission guards read the same directory columns for collections as +for other namespaces; the operation changes no spend events or enforcement thresholds. +Both adjacent builds read the same stored fields, so the operation requires no schema +change. The Library's collection menu provides the same budget controls. + ## Identity A service in front of Loom (a chat app) signs a short-lived token for each request it diff --git a/docs/reference/operations.md b/docs/reference/operations.md index da9c8cdd75..4ddc1a139a 100644 --- a/docs/reference/operations.md +++ b/docs/reference/operations.md @@ -123,7 +123,7 @@ python scripts/codegen/docs_reference.py --check # exit 1 when a region is stal -375 operations in 43 groups. Every op is served at `POST /v1/` and as the MCP tool `loom_` (dots become underscores). +376 operations in 43 groups. Every op is served at `POST /v1/` and as the MCP tool `loom_` (dots become underscores). Columns: **Role** is the minimum role (`viewer` < `writer` < `admin` < `org_admin` < `platform_admin`); **Kind** is `read` (idempotent, viewer, unaudited, writes nothing — MCP `readOnlyHint`), `idempotent` (safe to retry) or `write`; **Listed under `all`** says whether an MCP connection on the `all` toolset lists the op in `tools/list` (`code.*` ops only with `LOOM_MCP_CODE_TOOLS=true`); an op marked `no` is still callable by name or through `loom_op`, unless it is hidden from MCP; **Audit** marks ops that leave an `audit_log` row. @@ -245,6 +245,7 @@ Fields for every `collection` op: [operations/collection.md](operations/collecti | Operation | Summary | Role | Kind | Listed under `all` | Audit | | --- | --- | --- | --- | --- | --- | +| [`collection.budget_set`](operations/collection.md#collectionbudget_set) | Change only a collection's spend caps and warning destination. | admin | idempotent | no | yes | | [`collection.create`](operations/collection.md#collectioncreate) | Create a collection: a namespace read and written only through grants. | viewer | idempotent | no | yes | | [`collection.delete`](operations/collection.md#collectiondelete) | Delete a collection with what it holds: a purging erasure of the namespace (documents, chunks, originals, memory leave the disk), then it leaves the directory and the tree, and its name is never used… | admin | idempotent | no | yes | | [`collection.list`](operations/collection.md#collectionlist) | List the collections the caller can read, by name. | viewer | read | no | | diff --git a/docs/reference/operations/collection.md b/docs/reference/operations/collection.md index c6923c62ae..e3e9d8619d 100644 --- a/docs/reference/operations/collection.md +++ b/docs/reference/operations/collection.md @@ -8,6 +8,28 @@ Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity +## `collection.budget_set` + +Change only a collection's spend caps and warning destination. + +`POST /v1/collection.budget_set` · MCP `loom_collection_budget_set` · role `admin` · idempotent · audited · not listed under the MCP `all` toolset + +| Input field | Type | Default | Meaning | +| --- | --- | --- | --- | +| `org` | `str` | required | The tenant (first element of the identity tuple). | +| `namespace` | `str` | required | The namespace the op reads or writes. | +| `daily_cost_cap_usd` | `float \| None` | `None` | Collection cap in USD per rolling 24 hours; 0 inherits the server default, omit keeps it. | +| `daily_user_cost_cap_usd` | `float \| None` | `None` | Named-user cap in USD per rolling 24 hours; 0 inherits the server default, omit keeps it. | +| `budget_alert_inbox` | `str \| None` | `None` | An existing task inbox owned by this collection; '' disables warnings, omit keeps it. | + +| Output field | Type | Meaning | +| --- | --- | --- | +| `namespace` | `str` | The namespace the op reads or writes. | +| `changed` | `bool` | | +| `daily_cost_cap_usd` | `float` | | +| `daily_user_cost_cap_usd` | `float` | | +| `budget_alert_inbox` | `str` | | + ## `collection.create` Create a collection: a namespace read and written only through grants. diff --git a/docs/reference/status.md b/docs/reference/status.md index 8071866f40..5136ca1df5 100644 --- a/docs/reference/status.md +++ b/docs/reference/status.md @@ -25,7 +25,7 @@ serves is in the [MCP reference](./mcp.md#toolsets). -375 operations, 261 of them experimental. +376 operations, 262 of them experimental. | Group | Stable | Experimental | | --- | --- | --- | @@ -36,7 +36,7 @@ serves is in the [MCP reference](./mcp.md#toolsets). | `blacklist` | 1 | [`blacklist.add`](operations/blacklist.md#blacklistadd), [`blacklist.remove`](operations/blacklist.md#blacklistremove), [`blacklist.sweep`](operations/blacklist.md#blacklistsweep) | | `calibration` | 0 | [`calibration.get`](operations/calibration.md#calibrationget) | | `code` | 28 | [`code.backport_gap`](operations/code.md#codebackport_gap), [`code.backport_gaps`](operations/code.md#codebackport_gaps), [`code.bisect_candidates`](operations/code.md#codebisect_candidates), [`code.blame_range`](operations/code.md#codeblame_range), [`code.callees`](operations/code.md#codecallees), [`code.conventions`](operations/code.md#codeconventions), [`code.coverage_claim`](operations/code.md#codecoverage_claim), [`code.examples`](operations/code.md#codeexamples), [`code.files`](operations/code.md#codefiles), [`code.first_build`](operations/code.md#codefirst_build), [`code.map`](operations/code.md#codemap), [`code.outline`](operations/code.md#codeoutline), [`code.path_guards`](operations/code.md#codepath_guards), [`code.pr_check`](operations/code.md#codepr_check), [`code.reindex`](operations/code.md#codereindex), [`code.repo.set_access`](operations/code.md#codereposet_access), [`code.repo.set_source`](operations/code.md#codereposet_source), [`code.review_brief`](operations/code.md#codereview_brief), [`code.setting_facts`](operations/code.md#codesetting_facts), [`code.symbol_history`](operations/code.md#codesymbol_history), [`code.test_gate`](operations/code.md#codetest_gate), [`code.test_home`](operations/code.md#codetest_home), [`code.tests_for`](operations/code.md#codetests_for), [`code.verify_citations`](operations/code.md#codeverify_citations) | -| `collection` | 0 | [`collection.create`](operations/collection.md#collectioncreate), [`collection.delete`](operations/collection.md#collectiondelete), [`collection.list`](operations/collection.md#collectionlist), [`collection.move`](operations/collection.md#collectionmove) | +| `collection` | 0 | [`collection.budget_set`](operations/collection.md#collectionbudget_set), [`collection.create`](operations/collection.md#collectioncreate), [`collection.delete`](operations/collection.md#collectiondelete), [`collection.list`](operations/collection.md#collectionlist), [`collection.move`](operations/collection.md#collectionmove) | | `conflicts` | 2 | [`conflicts.allowlist_list`](operations/conflicts.md#conflictsallowlist_list), [`conflicts.allowlist_remove`](operations/conflicts.md#conflictsallowlist_remove), [`conflicts.propose_revision`](operations/conflicts.md#conflictspropose_revision) | | `connection` | 0 | [`connection.disconnect`](operations/connection.md#connectiondisconnect), [`connection.list`](operations/connection.md#connectionlist) | | `consolidations` | 0 | [`consolidations.list`](operations/consolidations.md#consolidationslist) | diff --git a/frontend/src/api/collections.ts b/frontend/src/api/collections.ts index 025e51741f..4ebcc47d7e 100644 --- a/frontend/src/api/collections.ts +++ b/frontend/src/api/collections.ts @@ -7,6 +7,21 @@ import { COLLECTIONS_PAGE } from "../lib/collections"; // ===== Collections ===== +export interface CollectionBudgetPolicy { + daily_cost_cap_usd: number; + daily_user_cost_cap_usd: number; + budget_alert_inbox: string; +} + +/** Change only the explicitly supplied spend policy fields of an administered collection. */ +export async function setCollectionBudget( + org: string, + namespace: string, + patch: Partial, +): Promise { + return post("/v1/collection.budget_set", { ...patch, org, namespace }); +} + /** Mirrors `server/identity/api/models_collections.py::_CollectionEntry`. */ export interface CollectionEntry { namespace: string; diff --git a/frontend/src/flows/CollectionBudgetDialog.test.tsx b/frontend/src/flows/CollectionBudgetDialog.test.tsx new file mode 100644 index 0000000000..95ca59d7a0 --- /dev/null +++ b/frontend/src/flows/CollectionBudgetDialog.test.tsx @@ -0,0 +1,145 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { act, cleanup, fireEvent, render, screen, waitFor } from "../test/rtl"; +import * as api from "../api"; +import userEvent from "@testing-library/user-event"; +import { CollectionBudgetDialog } from "./CollectionBudgetDialog"; +import { Picker, entry, read } from "../test/libraryCollections"; +import { toast } from "../components/Toast"; + +vi.mock("../api", async (original) => ({ + ...(await original()), + getNamespace: vi.fn(), + setCollectionBudget: vi.fn(), +})); +vi.mock("../components/Toast", () => ({ toast: vi.fn(), toastError: vi.fn() })); + +beforeEach(() => { + vi.mocked(api.getNamespace).mockResolvedValue({ + namespace: "col-a", + daily_cost_cap_usd: 2, + daily_user_cost_cap_usd: 1, + budget_alert_inbox: "owned", + } as api.NamespaceInfo); + vi.mocked(api.setCollectionBudget).mockResolvedValue({ + namespace: "col-a", + changed: true, + daily_cost_cap_usd: 2, + daily_user_cost_cap_usd: 0.5, + budget_alert_inbox: "", + }); +}); +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); + +it("reads the collection policy and saves only changed budget fields to that collection", async () => { + const close = vi.fn(); + render(); + const field = await screen.findByLabelText("Daily cap per user (USD)"); + expect(api.getNamespace).toHaveBeenCalledWith( + { org: "o", namespace: "col-a" }, + expect.objectContaining({ signal: expect.any(AbortSignal) }), + ); + fireEvent.change(field, { target: { value: "0.5" } }); + fireEvent.change(screen.getByLabelText("Budget warning inbox"), { target: { value: "" } }); + await act(async () => fireEvent.click(screen.getByRole("button", { name: "Save budget" }))); + expect(api.setCollectionBudget).toHaveBeenCalledWith("o", "col-a", { + daily_user_cost_cap_usd: 0.5, + budget_alert_inbox: "", + }); + expect(close).toHaveBeenCalledTimes(1); +}); + +it("keeps a failed save open and sends no write before its policy read succeeds", async () => { + vi.mocked(api.getNamespace).mockRejectedValueOnce(new TypeError("Failed to fetch")); + const close = vi.fn(); + render(); + const error = await screen.findByRole("alert"); + expect(error).toHaveTextContent(/connection|reach|network/i); + expect(error).not.toHaveTextContent(/saved|committed|re-check|check before/i); + expect(screen.getByRole("button", { name: "Save budget" })).toBeDisabled(); + expect(api.setCollectionBudget).not.toHaveBeenCalled(); + expect(close).not.toHaveBeenCalled(); +}); + +it("retains the draft and the server refusal on a failed write", async () => { + vi.mocked(api.setCollectionBudget).mockRejectedValueOnce(new Error("Inbox belongs elsewhere")); + const close = vi.fn(); + render(); + fireEvent.change(await screen.findByLabelText("Budget warning inbox"), { target: { value: "foreign" } }); + await act(async () => fireEvent.click(screen.getByRole("button", { name: "Save budget" }))); + await screen.findByRole("alert"); + expect(screen.getByLabelText("Budget warning inbox")).toHaveValue("foreign"); + expect(close).not.toHaveBeenCalled(); +}); + +it("opens budget controls from the administered Library collection's actual menu", async () => { + const c = entry("col-a"); + const view = render(); + await userEvent.click(screen.getByRole("button", { name: "Actions for col-a" })); + await userEvent.click(await screen.findByRole("menuitem", { name: "Budget…" })); + await waitFor(() => expect(screen.getByRole("dialog", { name: "Budget · col-a" })).toBeInTheDocument()); + expect(await screen.findByLabelText("Daily cost cap (USD)")).toHaveValue(2); + const viewer = entry("col-a", { role: "viewer" }); + view.rerender(); + await waitFor(() => expect(screen.queryByRole("dialog", { name: "Budget · col-a" })).not.toBeInTheDocument()); +}); + +it("an old save cannot close a later collection dialog or discard its draft", async () => { + let finish!: (value: Awaited>) => void; + vi.mocked(api.setCollectionBudget).mockReturnValueOnce( + new Promise((resolve) => { + finish = resolve; + }), + ); + const a = entry("col-a"), + b = entry("col-b"); + const places = read([a, b]); + const view = render( + , + ); + await userEvent.click(screen.getByRole("button", { name: "Actions for col-a" })); + await userEvent.click(await screen.findByRole("menuitem", { name: "Budget…" })); + fireEvent.change(await screen.findByLabelText("Daily cost cap (USD)"), { target: { value: "3" } }); + await act(async () => fireEvent.click(screen.getByRole("button", { name: "Save budget" }))); + expect(api.setCollectionBudget).toHaveBeenCalledWith("o", "col-a", { daily_cost_cap_usd: 3 }); + view.rerender(); + await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()); + await userEvent.click(screen.getByRole("button", { name: "Actions for col-b" })); + await userEvent.click(await screen.findByRole("menuitem", { name: "Budget…" })); + const draft = await screen.findByLabelText("Daily cost cap (USD)"); + fireEvent.change(draft, { target: { value: "7" } }); + await act(async () => + finish({ + namespace: "col-a", + changed: true, + daily_cost_cap_usd: 3, + daily_user_cost_cap_usd: 1, + budget_alert_inbox: "owned", + }), + ); + expect(screen.getByRole("dialog", { name: "Budget · col-b" })).toBeInTheDocument(); + expect(screen.getByLabelText("Daily cost cap (USD)")).toHaveValue(7); + expect(toast).not.toHaveBeenCalled(); +}); + +it.each(["viewer", "writer"] as const)( + "the unavailable Budget action remains keyboard reachable for a %s without reading or writing policy", + async (role) => { + const c = entry("col-a", { role }); + render(); + const trigger = screen.getByRole("button", { name: "Actions for col-a" }); + trigger.focus(); + await userEvent.keyboard("{ArrowDown}"); + const budget = await screen.findByRole("menuitem", { name: "Budget…" }); + await waitFor(() => expect(budget).toHaveFocus()); + expect(budget).toHaveAttribute("aria-disabled", "true"); + expect(budget).toHaveAccessibleDescription("Needs admin on col-a. An admin of it can grant that."); + await userEvent.keyboard("{Enter} "); + await userEvent.click(budget); + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + expect(api.getNamespace).not.toHaveBeenCalled(); + expect(api.setCollectionBudget).not.toHaveBeenCalled(); + }, +); diff --git a/frontend/src/flows/CollectionBudgetDialog.tsx b/frontend/src/flows/CollectionBudgetDialog.tsx new file mode 100644 index 0000000000..9df56b8b61 --- /dev/null +++ b/frontend/src/flows/CollectionBudgetDialog.tsx @@ -0,0 +1,162 @@ +import { useState } from "react"; +import { Button } from "@clickhouse/click-ui/Button"; +import { NumberField } from "@clickhouse/click-ui/NumberField"; +import { TextField } from "@clickhouse/click-ui/TextField"; +import { getNamespace, setCollectionBudget, type CollectionBudgetPolicy, type CollectionEntry } from "../api"; +import { collectionTitle } from "../lib/collections"; +import { humanizeError } from "../lib/errorWords"; +import { useAbortableEffect, useMounted } from "../lib/hooks"; +import { invalidateShared } from "../lib/sharedReads"; +import { Modal, ModalFooter } from "../components/ui/Modal"; +import { Alert, Loading } from "../components/ui"; +import { toast } from "../components/Toast"; + +/** Mounted per collection and open session, so a draft cannot target another collection. */ +export function CollectionBudgetDialog({ + org, + collection, + onClose, +}: { + org: string; + collection: CollectionEntry; + onClose: () => void; +}) { + const mounted = useMounted(); + const [stored, setStored] = useState(null); + const [cap, setCap] = useState(""); + const [userCap, setUserCap] = useState(""); + const [inbox, setInbox] = useState(""); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + useAbortableEffect( + async (signal, live) => { + try { + const row = await getNamespace({ org, namespace: collection.namespace }, { signal }); + if (!live()) return; + if (!row) throw new Error("Collection settings not found"); + const policy = { + daily_cost_cap_usd: row.daily_cost_cap_usd ?? 0, + daily_user_cost_cap_usd: row.daily_user_cost_cap_usd ?? 0, + budget_alert_inbox: row.budget_alert_inbox ?? "", + }; + setStored(policy); + setCap(String(policy.daily_cost_cap_usd)); + setUserCap(String(policy.daily_user_cost_cap_usd)); + setInbox(policy.budget_alert_inbox); + } catch (e) { + if (live()) setError(humanizeError(e, { read: true })); + } + }, + [org, collection.namespace], + ); + + const submit = async () => { + if (!stored || busy) return; + const patch: Partial = {}; + const next = { + daily_cost_cap_usd: Number(cap), + daily_user_cost_cap_usd: Number(userCap), + budget_alert_inbox: inbox.trim(), + }; + if ( + !cap.trim() || + !userCap.trim() || + !Number.isFinite(next.daily_cost_cap_usd) || + next.daily_cost_cap_usd < 0 || + !Number.isFinite(next.daily_user_cost_cap_usd) || + next.daily_user_cost_cap_usd < 0 + ) { + setError("Caps must be finite, non-negative numbers"); + return; + } + if (next.daily_cost_cap_usd !== stored.daily_cost_cap_usd) patch.daily_cost_cap_usd = next.daily_cost_cap_usd; + if (next.daily_user_cost_cap_usd !== stored.daily_user_cost_cap_usd) + patch.daily_user_cost_cap_usd = next.daily_user_cost_cap_usd; + if (next.budget_alert_inbox !== stored.budget_alert_inbox) patch.budget_alert_inbox = next.budget_alert_inbox; + if (!Object.keys(patch).length) { + onClose(); + return; + } + setBusy(true); + setError(null); + try { + await setCollectionBudget(org, collection.namespace, patch); + invalidateShared(`budget:${org}/${collection.namespace}`); + if (!mounted.current) return; + toast("Budget settings saved", "ok"); + onClose(); + } catch (e) { + if (mounted.current) setError(humanizeError(e)); + } finally { + if (mounted.current) setBusy(false); + } + }; + return ( + !open && !busy && onClose()} + title={`Budget · ${collectionTitle(collection)}`} + className="w-full max-w-[480px]" + > +
{ + event.preventDefault(); + void submit(); + }} + > +
+ {!stored && !error && } + {stored && ( + <> +

+ Caps count spend over the last 24 hours. 0 inherits the server default. The collection cap also applies + to each named user. +

+ + + +

+ An existing task inbox owned by this collection. Leave blank to disable warnings. +

+ + )} + {error && } +
+ + + + +
+
+ ); +} diff --git a/frontend/src/flows/CreateCollectionDialog.tsx b/frontend/src/flows/CreateCollectionDialog.tsx index 25fbfec41a..7417dab2f8 100644 --- a/frontend/src/flows/CreateCollectionDialog.tsx +++ b/frontend/src/flows/CreateCollectionDialog.tsx @@ -1,4 +1,5 @@ import { useState } from "react"; +import { flushSync } from "react-dom"; import { Button } from "@clickhouse/click-ui/Button"; import { Checkbox } from "@clickhouse/click-ui/Checkbox"; import { Select } from "@clickhouse/click-ui/Select"; @@ -25,7 +26,8 @@ export type ClaimCreateVersion = () => number; * open when the answer lands waits for the new collection. The person is told whether it was * made or one of that title already sits there; `typed` is shown when the answer names none. */ export function announceCreated(r: CollectionCreated, typed: string, org: string): void { - invalidateSharedCollections({ name: r.namespace, org }); + // Match the opening reload's priority so a delayed refresh cannot start a second read. + flushSync(() => invalidateSharedCollections({ name: r.namespace, org })); const shown = r.title || typed || r.namespace; toast(r.created ? `Created ${shown}` : `${shown} already exists here`, r.created ? "ok" : "info"); } diff --git a/frontend/src/views/LibraryCollections.test.tsx b/frontend/src/views/LibraryCollections.test.tsx index 263a05f4bd..f8e13f7d07 100644 --- a/frontend/src/views/LibraryCollections.test.tsx +++ b/frontend/src/views/LibraryCollections.test.tsx @@ -1,5 +1,8 @@ // The place picker (a select, or the tree beside the page), the path and chips, the // collection's menu, New collection, and how the list is read again after a write. +import { startTransition } from "react"; +import { flushSync } from "react-dom"; +import { announceCreated } from "../flows/CreateCollectionDialog"; import { repeatedTitles } from "../lib/collections"; import { act, cleanup, fireEvent, render, screen, waitFor, within } from "../test/rtl"; import { entry, matchOnly, Picker, read, ROWS, settle } from "../test/libraryCollections"; @@ -141,9 +144,12 @@ describe("LibraryCollections", () => { expect(screen.getByRole("button", { name: "Actions for col-q3" })).toBeInTheDocument(); }); - it("gives a viewer no menu: its members are behind See who in the header", async () => { + it("gives a viewer the unavailable Budget action without Move or Delete", async () => { render( undefined} />); - expect(screen.queryByRole("button", { name: "Actions for col-plans" })).not.toBeInTheDocument(); + await userEvent.click(screen.getByRole("button", { name: "Actions for col-plans" })); + expect(await screen.findByRole("menuitem", { name: "Budget…" })).toHaveAttribute("aria-disabled", "true"); + expect(screen.queryByRole("menuitem", { name: "Move…" })).not.toBeInTheDocument(); + expect(screen.queryByRole("menuitem", { name: "Delete collection" })).not.toBeInTheDocument(); }); it("on a phone shows the path as one back button and leaves the collections inside to the select", () => { @@ -212,6 +218,44 @@ describe("useReadableCollections", () => { return

{c.rows === null ? "reading" : c.rows.map((r) => r.namespace).join(",")}

; } + it("starts only the latest collection read when earlier effects were replaced before running", async () => { + let latest: ReadableCollections | null = null; + function Holder() { + latest = useReadableCollections("acme"); + return null; + } + api.listCollections.mockResolvedValue({ collections: [entry("col-a")], next_cursor: null }); + render(); + // The deferred reads have not run yet: each reload supersedes the one before it. + act(() => latest?.reload()); + act(() => latest?.reload()); + await settle(); + expect(api.listCollections).toHaveBeenCalledTimes(1); + expect(api.listCollections.mock.calls[0][1].signal.aborted).toBe(false); + }); + + it("coalesces a lower-priority create announcement with its synchronous opening read", async () => { + let latest: ReadableCollections | null = null; + function Holder() { + latest = useReadableCollections("acme"); + return null; + } + api.listCollections.mockResolvedValue({ collections: [entry("col-a")], next_cursor: null }); + render(); + await settle(); + const made = { namespace: "col-new", parent: "", created: true, title: "New" }; + api.listCollections.mockResolvedValue({ collections: [entry("col-a"), entry(made.namespace)], next_cursor: null }); + const reads = api.listCollections.mock.calls.length; + await act(async () => { + // Opening uses flushSync: the announcement must not arrive later at a lower priority. + startTransition(() => announceCreated(made, "New", "acme")); + flushSync(() => latest?.reload(made.namespace)); + await Promise.resolve(); + }); + await settle(); + expect(api.listCollections.mock.calls.length - reads).toBe(1); + }); + it("requests document counts with every collection page", async () => { api.listCollections .mockResolvedValueOnce({ collections: [entry("col-a")], next_cursor: "col-a" }) @@ -1190,6 +1234,16 @@ describe("the Library on a collection", () => { }); describe("a create's answer, and the reads it starts", () => { + const readDetails = (from: number) => + JSON.stringify( + api.listCollections.mock.calls.slice(from).map(([org, options]) => ({ + org, + cursor: options?.cursor, + includeDocumentCounts: options?.includeDocumentCounts, + aborted: options?.signal?.aborted, + })), + ); + it("still opens it when a resize took the tree away", async () => { const narrow = resizable(); const answer = await createInTree(); @@ -1405,7 +1459,7 @@ describe("the Library on a collection", () => { const reads = api.listCollections.mock.calls.length; await answer(q4); await settle(); - expect(api.listCollections.mock.calls.length - reads).toBe(1); + expect(api.listCollections.mock.calls.length - reads, readDetails(reads)).toBe(1); expect(new URLSearchParams(location.search).get("collection")).toBe("col-q4"); }); @@ -1426,7 +1480,7 @@ describe("the Library on a collection", () => { const reads = api.listCollections.mock.calls.length; await act(async () => answer(q4)); await settle(); - expect(api.listCollections.mock.calls.length - reads).toBe(1); + expect(api.listCollections.mock.calls.length - reads, readDetails(reads)).toBe(1); expect(new URLSearchParams(location.search).get("collection")).toBe("col-q4"); }); @@ -1484,7 +1538,7 @@ describe("the Library on a collection", () => { fireEvent.click(screen.getByRole("button", { name: "Create" })); await settle(); expect(new URLSearchParams(location.search).get("collection")).toBe("col-q5"); - expect(api.listCollections.mock.calls.length - reads).toBe(1); + expect(api.listCollections.mock.calls.length - reads, readDetails(reads)).toBe(1); }); it("moves nothing once the page shows another org", async () => { diff --git a/frontend/src/views/LibraryCollections.tsx b/frontend/src/views/LibraryCollections.tsx index e9358e805a..73791616bf 100644 --- a/frontend/src/views/LibraryCollections.tsx +++ b/frontend/src/views/LibraryCollections.tsx @@ -10,6 +10,7 @@ import { confirmAction } from "../components/ConfirmDialog"; import { toast, toastError } from "../components/Toast"; import { type ClaimCreateVersion, CreateCollectionDialog } from "../flows/CreateCollectionDialog"; import { MoveCollectionDialog } from "../flows/MoveCollectionDialog"; +import { CollectionBudgetDialog } from "../flows/CollectionBudgetDialog"; import { CollectionBack, CollectionChips, CollectionPath, cycleStart } from "./LibraryHierarchy"; import { COLLECTIONS_LISTED, @@ -29,6 +30,7 @@ import { PHONE_QUERY, useMedia } from "../lib/useMedia"; import { PLACE_PICKER_LABEL } from "../lib/useTreeFocusHandoff"; import { invalidateSharedCollections, onCollectionsChanged } from "../lib/collectionPlaces"; import { ALL_DOCUMENTS } from "../lib/libraryPlace"; +import { needsRole } from "../lib/namespaceRole"; /** The select's value for the namespace picked in the header: an item cannot carry "". */ const NAMESPACE_SHELF = "__namespace__"; @@ -154,6 +156,8 @@ export function useReadableCollections(org: string, showing: string | null = nul const hold = answered && showing !== null && answer.rows.some((c) => c.namespace === showing) ? showing : ""; useAbortableEffect( (signal, live) => { + // A reload can replace this effect before its deferred callback runs. + if (!live()) return; setError(null); void (async () => { for (let attempt = 0; ; attempt++) { @@ -256,6 +260,7 @@ export function LibraryCollections({ }) { const all = place === ALL_DOCUMENTS; const [moving, setMoving] = useState(null); + const [budgeting, setBudgeting] = useState(null); const { rows, error } = collections; // New collection and Move belong to the place they opened in: a move to another // closes them, and coming back does not reopen them. The list answering (or read again) @@ -263,7 +268,11 @@ export function LibraryCollections({ useEffect(() => { setCreating(false); setMoving(null); + setBudgeting(null); }, [place]); + useEffect(() => { + setBudgeting(null); + }, [org, current?.namespace, current?.role]); // The select's order; beside the tree there is no select. const ordered = useMemo(() => (besideTree ? [] : treeOrder(rows ?? [])), [rows, besideTree]); // A phone gets the path as one back button in the select's row, and no chips. @@ -339,6 +348,13 @@ export function LibraryCollections({ const collection = current && !current.personal ? current : null; const items: RowMenuItem[] = []; if (collection) { + items.push({ + label: "Budget…", + reason: collection.role === "admin" ? null : needsRole("admin", collection.namespace), + onSelect: () => { + if (collection.role === "admin") setBudgeting(collection); + }, + }); if (collection.role === "admin") { items.push({ label: "Move…", icon: "arrow-right", onSelect: () => setMoving(collection) }); items.push({ @@ -461,6 +477,14 @@ export function LibraryCollections({

)} + {budgeting && ( + setBudgeting(null)} + /> + )} {moving && ( None: self._agent = agent + async def budget_set( + self, body: _ops.CollectionBudgetSetBody | None = None, /, **options: Any + ) -> _ops.CollectionBudgetSetOutput: + """`collection.budget_set`.""" + return cast( + "_ops.CollectionBudgetSetOutput", + await self._agent.call("collection.budget_set", body, **options), + ) + async def create( self, body: _ops.CollectionCreateBody | None = None, /, **options: Any ) -> _ops.CollectionCreateOutput: diff --git a/sdk/python/loom/ops.py b/sdk/python/loom/ops.py index fd1913dc09..ab565c4989 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -100,6 +100,7 @@ class OpSpec: "code.trace", "code.verify", "code.verify_citations", + "collection.budget_set", "collection.create", "collection.delete", "collection.list", @@ -478,6 +479,7 @@ class OpSpec: "code.trace", "code.verify", "code.verify_citations", + "collection.budget_set", "collection.create", "collection.delete", "collection.list", @@ -1527,6 +1529,18 @@ class OpSpec: False, True, ), + "collection.budget_set": OpSpec( + "collection.budget_set", + "CollectionBudgetSetInput", + "CollectionBudgetSetBody", + "CollectionBudgetSetOutput", + True, + "admin", + "experimental", + 80, + True, + False, + ), "collection.create": OpSpec( "collection.create", "CollectionCreateInput", @@ -8123,6 +8137,34 @@ class CodeVerifyCitationsOutput(TypedDict, total=False): trace_run_id: NotRequired[str] +class CollectionBudgetSetInput(TypedDict, total=False): + "Change only a collection's spend caps and warning destination." + + org: Required[str] + namespace: Required[str] + daily_cost_cap_usd: NotRequired[Optional[float]] + daily_user_cost_cap_usd: NotRequired[Optional[float]] + budget_alert_inbox: NotRequired[Optional[str]] + + +class CollectionBudgetSetBody(TypedDict, total=False): + "Change only a collection's spend caps and warning destination." + + org: NotRequired[str] + namespace: NotRequired[str] + daily_cost_cap_usd: NotRequired[Optional[float]] + daily_user_cost_cap_usd: NotRequired[Optional[float]] + budget_alert_inbox: NotRequired[Optional[str]] + + +class CollectionBudgetSetOutput(TypedDict, total=False): + namespace: Required[str] + changed: Required[bool] + daily_cost_cap_usd: Required[float] + daily_user_cost_cap_usd: Required[float] + budget_alert_inbox: Required[str] + + class CollectionCreateInput(TypedDict, total=False): "Create a collection: a namespace read and written only through grants." diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index ff302c5c8a..e67a83e242 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -1889,6 +1889,25 @@ export interface CodeVerifyCitationsOutput { trace_run_id?: string; } +export interface CollectionBudgetSetInput { + org: string; + namespace: string; + /** Collection cap in USD per rolling 24 hours; 0 inherits the server default, omit keeps it. */ + daily_cost_cap_usd?: number | null; + /** Named-user cap in USD per rolling 24 hours; 0 inherits the server default, omit keeps it. */ + daily_user_cost_cap_usd?: number | null; + /** An existing task inbox owned by this collection; '' disables warnings, omit keeps it. */ + budget_alert_inbox?: string | null; +} + +export interface CollectionBudgetSetOutput { + namespace: string; + changed: boolean; + daily_cost_cap_usd: number; + daily_user_cost_cap_usd: number; + budget_alert_inbox: string; +} + export interface CollectionCreateInput { org: string; /** The collection's name, also its namespace ('col-' then lowercase letters, digits and '-'), ignored with `derive_name`. */ @@ -10533,6 +10552,7 @@ export type OpName = | "code.trace" | "code.verify" | "code.verify_citations" + | "collection.budget_set" | "collection.create" | "collection.delete" | "collection.list" @@ -10911,6 +10931,7 @@ export interface OpMap { "code.trace": { input: CodeTraceInput; output: CodeTraceOutput }; "code.verify": { input: CodeVerifyInput; output: CodeVerifyOutput }; "code.verify_citations": { input: CodeVerifyCitationsInput; output: CodeVerifyCitationsOutput }; + "collection.budget_set": { input: CollectionBudgetSetInput; output: CollectionBudgetSetOutput }; "collection.create": { input: CollectionCreateInput; output: CollectionCreateOutput }; "collection.delete": { input: CollectionDeleteInput; output: CollectionDeleteOutput }; "collection.list": { input: CollectionListInput; output: CollectionListOutput }; @@ -11289,6 +11310,7 @@ export const OPS: readonly OpSpec[] = [ { name: "code.trace", group: "code", method: "trace", idempotent: true, role: "viewer", maturity: "stable", budgetP99Ms: 800, audit: false, readOnly: true }, { name: "code.verify", group: "code", method: "verify", idempotent: true, role: "viewer", maturity: "stable", budgetP99Ms: 1500, audit: false, readOnly: true }, { name: "code.verify_citations", group: "code", method: "verifyCitations", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 1500, audit: false, readOnly: true }, + { name: "collection.budget_set", group: "collection", method: "budgetSet", idempotent: true, role: "admin", maturity: "experimental", budgetP99Ms: 80, audit: true, readOnly: false }, { name: "collection.create", group: "collection", method: "create", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 80, audit: true, readOnly: false }, { name: "collection.delete", group: "collection", method: "delete", idempotent: true, role: "admin", maturity: "experimental", budgetP99Ms: 2000, audit: true, readOnly: false }, { name: "collection.list", group: "collection", method: "list", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 80, audit: false, readOnly: true }, @@ -11609,4 +11631,4 @@ export const OP_BY_NAME: Readonly> = Object.fromEntries( OPS.map((o) => [o.name, o]), ) as Readonly>; -export const GENERATED_OP_COUNT = 375; +export const GENERATED_OP_COUNT = 376; diff --git a/server/identity/api/models_collections.py b/server/identity/api/models_collections.py index fe28cf2a9f..7facf4686b 100644 --- a/server/identity/api/models_collections.py +++ b/server/identity/api/models_collections.py @@ -101,6 +101,41 @@ class CollectionMoveOutput(BaseModel): moved: bool # False when it already sat there +class CollectionBudgetSetInput(BaseModel): + """Change only a collection's spend caps and warning destination.""" + + org: str + namespace: str + daily_cost_cap_usd: float | None = Field( + default=None, + ge=0, + allow_inf_nan=False, + description="Collection cap in USD per rolling 24 hours; " + "0 inherits the server default, omit keeps it.", + ) + daily_user_cost_cap_usd: float | None = Field( + default=None, + ge=0, + allow_inf_nan=False, + description="Named-user cap in USD per rolling 24 hours; " + "0 inherits the server default, omit keeps it.", + ) + budget_alert_inbox: str | None = Field( + default=None, + max_length=128, + description="An existing task inbox owned by this collection; " + "'' disables warnings, omit keeps it.", + ) + + +class CollectionBudgetSetOutput(BaseModel): + namespace: str + changed: bool + daily_cost_cap_usd: float + daily_user_cost_cap_usd: float + budget_alert_inbox: str + + class CollectionListInput(BaseModel): """List the collections the caller can read, by name.""" diff --git a/server/identity/api/ops_collections.py b/server/identity/api/ops_collections.py index 5692574caa..88459f4091 100644 --- a/server/identity/api/ops_collections.py +++ b/server/identity/api/ops_collections.py @@ -3,6 +3,8 @@ from __future__ import annotations from server.identity.api.models_collections import ( + CollectionBudgetSetInput, + CollectionBudgetSetOutput, CollectionCreateInput, CollectionCreateOutput, CollectionDeleteInput, @@ -12,6 +14,7 @@ CollectionMoveInput, CollectionMoveOutput, ) +from server.identity.app.collection_budgets import handle_collection_budget_set from server.identity.app.collections import ( create_audit_namespace, create_audit_subject, @@ -53,6 +56,17 @@ audit=True, ) +collection_budget_set = Operation( + name="collection.budget_set", + maturity="experimental", + input_model=CollectionBudgetSetInput, + output_model=CollectionBudgetSetOutput, + handler=handle_collection_budget_set, + idempotent=True, + required_role=Role.ADMIN, + audit=True, +) + collection_list = Operation( name="collection.list", maturity="experimental", @@ -80,6 +94,7 @@ ) OPERATIONS: list[Operation] = [ + collection_budget_set, collection_create, collection_move, collection_list, diff --git a/server/identity/app/collection_budgets.py b/server/identity/app/collection_budgets.py new file mode 100644 index 0000000000..ab018bd324 --- /dev/null +++ b/server/identity/app/collection_budgets.py @@ -0,0 +1,58 @@ +"""Spend policy for grant-authorized collections, stored in their directory row.""" + +from __future__ import annotations + +from typing import Any + +from server.auth import sharing +from server.auth.authz import identity_write +from server.auth.grant_claims import account_change +from server.core.ch import get_client, own_write_reads +from server.core.datetimes import naive_utc_now_seconds +from server.core.errors import ValidationError +from server.identity.api.models_collections import ( + CollectionBudgetSetInput, + CollectionBudgetSetOutput, +) +from server.identity.store import collections as collections_repo +from server.identity.store import namespaces as namespaces_repo +from server.tasks.app.budget_notifications import inbox_owned_by + +_FIELDS = ("daily_cost_cap_usd", "daily_user_cost_cap_usd", "budget_alert_inbox") + + +def _patch(input: CollectionBudgetSetInput) -> dict[str, Any]: + patch = {key: getattr(input, key) for key in _FIELDS if key in input.model_fields_set} + if not patch or any(value is None for value in patch.values()): + raise ValidationError("supply at least one budget field; null does not change a policy") + return patch + + +async def handle_collection_budget_set( + input: CollectionBudgetSetInput, +) -> CollectionBudgetSetOutput: + """The transport checks ADMIN on this collection before its policy is read or changed.""" + org, namespace = input.org, input.namespace + patch = _patch(input) + if not sharing.is_collection(namespace) or sharing.is_personal(namespace): + raise ValidationError("budget settings require a non-personal collection") + ch = get_client() + async with account_change(org, namespace): + with own_write_reads(): + row = await namespaces_repo.fetch_row(org, namespace, ch=ch) + live = await collections_repo.fetch(org, namespace, ch=ch) + if not row or row.get("kind") != "collection" or not row.get("active") or not live: + raise ValidationError("budget settings require an active collection") + inbox = patch.get("budget_alert_inbox") + if inbox and not await inbox_owned_by(org, namespace, inbox): + raise ValidationError( + "budget_alert_inbox must name an existing task inbox owned by this collection" + ) + changed = any(row.get(key) != value for key, value in patch.items()) + if changed: + row = {**row, **patch, "updated_at": max(naive_utc_now_seconds(), row["updated_at"])} + with identity_write(): + await ch.insert("loom.namespaces", [row]) + return CollectionBudgetSetOutput( + namespace=namespace, changed=changed, **{key: row[key] for key in _FIELDS} + ) diff --git a/server/operations/reach_manifest.py b/server/operations/reach_manifest.py index 0ebff31d12..66ab1c8286 100644 --- a/server/operations/reach_manifest.py +++ b/server/operations/reach_manifest.py @@ -123,6 +123,7 @@ "code.trace": ("sdk_method",), "code.verify": ("sdk_method",), "code.verify_citations": ("sdk_method",), + "collection.budget_set": ("dashboard",), "collection.create": ("dashboard",), "collection.delete": ("dashboard",), "collection.list": ( diff --git a/server/settings/catalog.py b/server/settings/catalog.py index c2a2f43d87..89d2e31d83 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -6261,6 +6261,7 @@ class TrackerSettings(BaseModel): # (batched), items by number, one name lookup per qualified name # (<=8 gathered); the optional mirror leg is capped at 20 calls / 5 s "code.verify_citations": 1500, + "collection.budget_set": 80, "collection.create": 80, # It runs the purging erasure inline, as `erasure.request` does. "collection.delete": 2000, diff --git a/tests/integration/test_knowledge_sharing.py b/tests/integration/test_knowledge_sharing.py index a93dfcb4b8..30e378bf67 100644 --- a/tests/integration/test_knowledge_sharing.py +++ b/tests/integration/test_knowledge_sharing.py @@ -1109,3 +1109,70 @@ def test_a_document_says_which_agent_and_session_wrote_it_and_what_it_is(gw: Gat {"namespace": col, "source_uri": "x", "content": "y", "source_class": "observed"}, ) assert refused.status_code == 422, "a body only declares a downgrade" + + +def test_only_collection_admins_change_its_spend_policy_and_keep_other_settings( + gw: Gateway, +) -> None: + tag = uuid.uuid4().hex[:8] + collection = _collection(gw, "alice", f"col-budget-{tag}") + foreign = _collection(gw, "alice", f"col-foreign-{tag}") + for user, role in (("bob", "viewer"), ("carol", "writer")): + gw.ok( + "alice", + "grants.create", + {"namespace": collection, "subject": f"user:{user}", "role": role}, + ) + before = gw.ok("alice", "namespace.get", {"namespace": collection}) + original = { + field: before[field] + for field in ("daily_cost_cap_usd", "daily_user_cost_cap_usd", "budget_alert_inbox") + } + patch = {"namespace": collection, "daily_cost_cap_usd": 0.25, "daily_user_cost_cap_usd": 0.125} + for user in ("bob", "carol", "dan"): + assert gw.call(user, "collection.budget_set", patch).status_code == 403 + other_org = httpx.post( + f"{gw.base}/v1/collection.budget_set", + json={"org": gw.org, **patch}, + headers={"Authorization": f"Bearer {end_user_issuer.mint(gw.org + '-other', 'alice')}"}, + timeout=60, + ) + assert other_org.status_code == 403 + own_inbox, foreign_inbox = f"budget-{tag}", f"other-{tag}" + for namespace, inbox in ((collection, own_inbox), (foreign, foreign_inbox)): + gw.ok( + "alice", "inbox.register", {"namespace": namespace, "inbox": inbox, "owner_agent": "-"} + ) + rejected = gw.call( + "alice", "collection.budget_set", {**patch, "budget_alert_inbox": foreign_inbox} + ) + assert rejected.status_code == 422 and "owned by this collection" in rejected.text + assert gw.ok("alice", "namespace.get", {"namespace": collection}) == before + changed = gw.ok("alice", "collection.budget_set", {**patch, "budget_alert_inbox": own_inbox}) + assert changed["changed"] and changed["daily_cost_cap_usd"] == 0.25 + after = gw.ok("alice", "namespace.get", {"namespace": collection}) + expected = { + **before, + "daily_cost_cap_usd": 0.25, + "daily_user_cost_cap_usd": 0.125, + "budget_alert_inbox": own_inbox, + } + assert {key: value for key, value in after.items() if key != "updated_at"} == { + key: value for key, value in expected.items() if key != "updated_at" + } + status = gw.ok("alice", "cost.budget_status", {"namespace": collection}) + assert status["user_id"] == "alice" + assert status["cap_source"] == "namespace_user" and status["cap_usd"] == 0.125 + gw.ok("alice", "collection.budget_set", {"namespace": collection, **original}) + restored = gw.ok("alice", "namespace.get", {"namespace": collection}) + assert {key: value for key, value in restored.items() if key != "updated_at"} == { + key: value for key, value in before.items() if key != "updated_at" + } + wrong_route = gw.call( + "alice", + "namespace.register", + {"namespace": collection, "owner_email": "user:alice", "daily_cost_cap_usd": 1}, + ) + assert wrong_route.status_code == 403 + assert "namespace.register is not open to an end user" in wrong_route.text + assert gw.ok("alice", "namespace.get", {"namespace": collection}) == restored diff --git a/tests/unit/snapshots/sdk_public_api.json b/tests/unit/snapshots/sdk_public_api.json index 48adad0e03..4bd91bf90e 100644 --- a/tests/unit/snapshots/sdk_public_api.json +++ b/tests/unit/snapshots/sdk_public_api.json @@ -516,6 +516,10 @@ "collection": { "class": "CollectionOps", "methods": { + "budget_set": [ + "body", + "options" + ], "create": [ "body", "options" diff --git a/tests/unit/test_collection_budgets.py b/tests/unit/test_collection_budgets.py new file mode 100644 index 0000000000..339f275b9b --- /dev/null +++ b/tests/unit/test_collection_budgets.py @@ -0,0 +1,235 @@ +"""A collection's admins can change its spend policy without rewriting its identity.""" + +from __future__ import annotations + +from contextlib import asynccontextmanager +from datetime import datetime +from typing import Any + +import pydantic +import pytest + +from server.core.errors import ValidationError +from server.identity.api.models import NamespaceRegisterInput +from server.identity.api.models_collections import CollectionBudgetSetInput +from server.identity.app import collection_budgets as h +from server.identity.app.namespace import handle_namespace_register +from server.observability import budget +from server.operations.base import Role +from server.operations.registry import ALL_OPERATIONS + + +def test_a_collection_has_an_audited_admin_budget_operation() -> None: + ops = {op.name: op for op in ALL_OPERATIONS} + assert "collection.budget_set" in ops + op = ops["collection.budget_set"] + assert op.required_role == Role.ADMIN and op.audit and op.idempotent + assert not op.skip_namespace_authz and not op.deployment_scoped + + +class Store: + def __init__(self) -> None: + self.held = False + self.live = True + self.inbox_checks: list[tuple[str, str, str]] = [] + self.writes: list[dict[str, Any]] = [] + self.row: dict[str, Any] | None = { + "org": "o", + "namespace": "col-a", + "kind": "collection", + "active": True, + "daily_cost_cap_usd": 2.0, + "daily_user_cost_cap_usd": 1.0, + "budget_alert_inbox": "", + "updated_at": datetime(2026, 1, 2), + "created_at": datetime(2025, 1, 1), + "classification": "restricted", + "visibility": "private", + "title": "Plans", + "tags": ["a"], + "owner_email": "owner", + "password_hash": "hash", + "capture_generation_io": False, + "future_column": {"must": "remain"}, + } + + async def insert(self, table: str, rows: list[dict[str, Any]]) -> None: + assert self.held and table == "loom.namespaces" + [row] = rows + self.writes.append(dict(row)) + self.row = dict(row) + + async def query_one(self, sql: str, params: dict[str, Any]) -> dict[str, Any]: + assert params["org"] == "o" and params["ns"] == "col-a" + if "FROM loom.namespaces" in sql: + return dict(self.row or {}) + # Offline cost rows prove the existing guard consumes the new stored cap. + return {"spent": 0.5, "own": 0, "user_spent": 0.2, "user_own": 0} + + +@pytest.fixture +def store(monkeypatch: pytest.MonkeyPatch) -> Store: + s = Store() + + @asynccontextmanager + async def held(org: str, ns: str) -> Any: + assert (org, ns) == ("o", "col-a") and not s.held + s.held = True + try: + yield + finally: + s.held = False + + async def fetch(org: str, ns: str, **kw: Any) -> dict[str, Any] | None: + assert s.held and (org, ns) == ("o", "col-a") + return dict(s.row) if s.row else None + + async def live(org: str, ns: str, **kw: Any) -> dict[str, Any] | None: + assert s.held and (org, ns) == ("o", "col-a") + return {"namespace": ns} if s.live else None + + async def inbox(org: str, ns: str, name: str) -> bool: + s.inbox_checks.append((org, ns, name)) + return name == "owned" + + monkeypatch.setattr(h, "account_change", held) + monkeypatch.setattr(h.namespaces_repo, "fetch_row", fetch) + monkeypatch.setattr(h.collections_repo, "fetch", live) + monkeypatch.setattr(h, "inbox_owned_by", inbox) + monkeypatch.setattr(h, "get_client", lambda: s) + monkeypatch.setattr(h, "naive_utc_now_seconds", lambda: datetime(2026, 1, 1)) + return s + + +def request(**fields: Any) -> CollectionBudgetSetInput: + return CollectionBudgetSetInput(org="o", namespace="col-a", **fields) + + +async def test_patch_preserves_every_unrelated_column_and_never_moves_the_timestamp_back( + store: Store, +) -> None: + before = dict(store.row or {}) + out = await h.handle_collection_budget_set(request(daily_cost_cap_usd=0.25)) + assert out.changed and out.daily_cost_cap_usd == 0.25 + assert out.daily_user_cost_cap_usd == 1.0 and out.budget_alert_inbox == "" + assert store.row == {**before, "daily_cost_cap_usd": 0.25} + assert not store.held and len(store.writes) == 1 + + +async def test_user_cap_and_owned_inbox_can_be_changed_then_restored(store: Store) -> None: + before = dict(store.row or {}) + changed = await h.handle_collection_budget_set( + request(daily_user_cost_cap_usd=0.125, budget_alert_inbox="owned") + ) + assert changed.daily_cost_cap_usd == 2.0 and changed.daily_user_cost_cap_usd == 0.125 + assert store.inbox_checks == [("o", "col-a", "owned")] + await h.handle_collection_budget_set(request(daily_user_cost_cap_usd=1, budget_alert_inbox="")) + assert store.row == before + + +async def test_an_identical_patch_does_not_rewrite_the_directory(store: Store) -> None: + out = await h.handle_collection_budget_set(request(daily_cost_cap_usd=2)) + assert not out.changed and not store.writes + + +async def test_foreign_or_missing_inbox_is_refused_without_changing_policy(store: Store) -> None: + before = dict(store.row or {}) + with pytest.raises(ValidationError, match="owned by this collection"): + await h.handle_collection_budget_set( + request(daily_cost_cap_usd=0.25, budget_alert_inbox="foreign") + ) + assert store.inbox_checks == [("o", "col-a", "foreign")] + assert not store.writes and store.row == before + + +@pytest.mark.parametrize("state", ["missing", "inactive", "wrong_kind", "retired_tree"]) +async def test_missing_inactive_or_retired_collections_are_not_resurrected( + store: Store, state: str +) -> None: + if state == "missing": + store.row = None + elif state == "retired_tree": + store.live = False + else: + assert store.row + store.row["active" if state == "inactive" else "kind"] = ( + False if state == "inactive" else "agent" + ) + with pytest.raises(ValidationError, match="active collection"): + await h.handle_collection_budget_set(request(daily_cost_cap_usd=0.25)) + assert not store.writes + + +@pytest.mark.parametrize("ns", ["account", "col-me-12345678"]) +async def test_account_and_personal_names_cannot_enter_collection_policy_writes( + store: Store, ns: str +) -> None: + with pytest.raises(ValidationError, match="non-personal collection"): + await h.handle_collection_budget_set( + CollectionBudgetSetInput(org="o", namespace=ns, daily_cost_cap_usd=1) + ) + assert not store.writes + + +@pytest.mark.parametrize( + "patch", + [ + {}, + {"daily_cost_cap_usd": None}, + {"daily_user_cost_cap_usd": None}, + {"budget_alert_inbox": None}, + ], +) +async def test_empty_and_null_patches_do_not_silently_clear_policy( + store: Store, patch: dict[str, Any] +) -> None: + with pytest.raises(ValidationError, match="at least one budget field"): + await h.handle_collection_budget_set(request(**patch)) + assert not store.writes + + +@pytest.mark.parametrize("field", ["daily_cost_cap_usd", "daily_user_cost_cap_usd"]) +@pytest.mark.parametrize("value", [-1, float("inf"), float("-inf"), float("nan")]) +def test_caps_are_finite_nonnegative_dollar_values(field: str, value: float) -> None: + with pytest.raises(pydantic.ValidationError): + request(**{field: value}) + + +async def test_zero_restores_existing_default_semantics_and_positive_caps_reach_the_guard( + store: Store, monkeypatch: pytest.MonkeyPatch +) -> None: + from server.settings import settings + + monkeypatch.setattr(settings, "default_daily_cost_cap_usd", 3) + monkeypatch.setattr(settings, "default_daily_user_cost_cap_usd", 2) + await h.handle_collection_budget_set(request(daily_cost_cap_usd=0, daily_user_cost_cap_usd=0)) + snapshot = await budget.budget_snapshot("o", "col-a", user_id="named", ch=store) + assert (snapshot.cap, snapshot.cap_source, snapshot.user_cap, snapshot.user_cap_source) == ( + 3, + "global", + 2, + "global_user", + ) + assert not snapshot.over("named", "", 1) + await h.handle_collection_budget_set( + request(daily_cost_cap_usd=0.25, daily_user_cost_cap_usd=0.125) + ) + snapshot = await budget.budget_snapshot("o", "col-a", user_id="named", ch=store) + assert snapshot.over("named", "", 1) + assert (snapshot.cap_source, snapshot.user_cap_source) == ("namespace", "namespace_user") + + +async def test_namespace_register_still_refuses_the_original_collection_route( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr("server.identity.app.namespace.resolve_subject", lambda: "owner") + with pytest.raises(ValidationError, match="collection operations only"): + await handle_namespace_register( + NamespaceRegisterInput( + org="o", + namespace="col-a", + owner_email="owner", + daily_cost_cap_usd=0.05, + daily_user_cost_cap_usd=0.025, + ) + ) diff --git a/tests/unit/test_namespaces_writers_mirror_classification.py b/tests/unit/test_namespaces_writers_mirror_classification.py index c37854a720..548bfed05d 100644 --- a/tests/unit/test_namespaces_writers_mirror_classification.py +++ b/tests/unit/test_namespaces_writers_mirror_classification.py @@ -88,6 +88,7 @@ def test_every_literal_namespaces_insert_is_a_known_writer() -> None: "server/identity/app/conversation_logging.py", # SELECT * new version: set_logging "server/identity/app/claim_release.py", # SELECT * new version: release "server/identity/app/collections.py", # registry_row + full-row copy (title) + "server/identity/app/collection_budgets.py", # SELECT * via namespaces_repo.fetch_row } found = set() for path in (ROOT / "server").rglob("*.py"): diff --git a/tests/unit/test_op_scope_fields.py b/tests/unit/test_op_scope_fields.py index 338487d2c9..383b80aae5 100644 --- a/tests/unit/test_op_scope_fields.py +++ b/tests/unit/test_op_scope_fields.py @@ -39,6 +39,9 @@ # (op, field) -> the function that authorizes the field's value. AUTHORIZED: dict[tuple[str, str], str] = { + ("collection.budget_set", "budget_alert_inbox"): ( + "server.tasks.app.budget_notifications.inbox_owned_by" + ), ("namespace.register", "budget_alert_inbox"): ( "server.tasks.app.budget_notifications.inbox_owned_by" ), diff --git a/tests/unit/test_sdk_set_coalescer.py b/tests/unit/test_sdk_set_coalescer.py index 340dfe8b35..7d6b2c4ee1 100644 --- a/tests/unit/test_sdk_set_coalescer.py +++ b/tests/unit/test_sdk_set_coalescer.py @@ -513,7 +513,14 @@ async def test_flush_sets_sends_the_gathered_batch_now(agent: Agent) -> None: assert sum(1 for r in results if r.get("coalesced")) == 3 -async def test_close_flushes_before_the_pool_closes(agent: Agent) -> None: +async def test_close_flushes_before_the_pool_closes( + agent: Agent, monkeypatch: pytest.MonkeyPatch +) -> None: + from tests.unit.clock_fake import ManualClock + + loop = asyncio.get_running_loop() + clock = ManualClock(t=loop.time()) + monkeypatch.setattr(loop, "time", clock.monotonic) t: Any = agent.transport tasks = [asyncio.ensure_future(agent.memory.set(f"k{i}", i)) for i in range(4)] await asyncio.sleep(0)