From d48a59d73cb7dd76cbb5ad354251f83342131d23 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 04:45:07 +0200 Subject: [PATCH] fix: complete safe managed release upgrades --- .agents/repo.md | 3 + .github/ci-scope.yml | 4 + .github/release-candidate-contract.json | 3 + .github/release-notes/v0.5.79.md | 177 ++++++ .github/renovate.json | 11 + .github/workflows/cli.yml | 3 + .../admin/governance/data-subject-requests.md | 4 + .../admin/governance/policies-and-limits.md | 8 +- .../admin/governance/usage-attribution.md | 6 +- docs/de/platform/automations/concepts.md | 2 +- docs/de/self-hosted/operate/upgrades.md | 2 - .../admin/governance/data-subject-requests.md | 4 + .../admin/governance/policies-and-limits.md | 8 +- .../admin/governance/usage-attribution.md | 6 +- docs/en/platform/automations/concepts.md | 2 +- docs/en/self-hosted/operate/upgrades.md | 2 - .../admin/governance/data-subject-requests.md | 4 + .../admin/governance/policies-and-limits.md | 8 +- .../admin/governance/usage-attribution.md | 6 +- docs/fr/platform/automations/concepts.md | 2 +- docs/fr/self-hosted/operate/upgrades.md | 2 - .../hooks/use-delete-organization.ts | 14 +- .../request-detail-drawer.test.tsx | 35 +- .../request-detail-drawer.tsx | 12 +- .../backend/core/automations/ledger.ts | 4 +- .../backend/core/automations/llm_budget.ts | 11 + .../backend/core/automations/llm_call.test.ts | 187 ++++-- .../backend/core/automations/llm_call.ts | 188 +++++-- .../core/automations/stepper.ledger.test.ts | 6 + .../backend/core/automations/stepper.ts | 8 +- .../automations_builder/chat_wire.test.ts | 38 +- .../core/automations_builder/chat_wire.ts | 15 +- .../core/automations_builder/model_call.ts | 25 +- .../backend/core/chat/assistant_tools.ts | 8 +- .../core/governance/erasure_constants.ts | 4 + .../core/governance/erasure_counts.test.ts} | 2 +- .../core/governance/erasure_counts.ts} | 0 .../backend/core/lib/handler_names.ts | 3 +- .../sandbox/workspace_domain_tools.ts | 148 ++++- .../workspace_tools_bridge.task_reads.test.ts | 286 +++++++++- .../sandbox/workspace_tools_bridge.ts | 21 +- .../backend/core/sandbox/workspace_access.ts | 11 +- .../0164_immutable_budget_reservations.sql | 31 + .../platform/backend/domains/api_keys/spec.md | 6 +- .../legacy-protocol.integration.ts | 80 +++ .../domains/automations/llm-metering.test.ts | 324 ++++++----- .../domains/automations/llm-metering.ts | 200 ++++--- .../backend/domains/automations/shim.test.ts | 2 +- .../backend/domains/automations/shim.ts | 8 +- .../domains/chat/budget-admission.test.ts | 17 + .../backend/domains/chat/budget-admission.ts | 11 +- .../domains/chat/shim.knowledge-scope.test.ts | 175 +++++- .../platform/backend/domains/chat/shim.ts | 3 +- .../backend/domains/chat/store.test.ts | 26 +- .../platform/backend/domains/chat/store.ts | 6 +- .../backend/domains/chat/threads.test.ts | 202 ++++++- .../platform/backend/domains/chat/threads.ts | 74 ++- .../domains/erasure/receipt-status.test.ts | 8 + .../domains/erasure/service.lifecycle.test.ts | 225 +++++++- .../backend/domains/erasure/service.ts | 149 +++-- .../platform/backend/domains/erasure/spec.md | 23 +- .../backend/domains/governance/README.md | 23 +- .../governance/budget-reservations.test.ts | 14 +- .../domains/governance/budget-reservations.ts | 27 +- .../immutable-projects.integration.ts | 343 +++++++++++ .../governance/project-budget.integration.ts | 459 ++++++++++++++- .../backend/domains/governance/spec.md | 19 +- .../domains/model_api/retention.test.ts | 34 +- .../backend/domains/model_api/retention.ts | 36 +- .../domains/organizations/routes.test.ts | 11 + .../backend/domains/organizations/routes.ts | 10 + .../domains/organizations/service.test.ts | 27 + .../backend/domains/organizations/service.ts | 27 +- .../backend/domains/organizations/spec.md | 12 + .../domains/sandbox/image-generation.test.ts | 83 ++- .../domains/sandbox/image-generation.ts | 24 +- .../domains/sandbox/op-attribution.test.ts | 47 ++ .../backend/domains/sandbox/op-attribution.ts | 25 +- .../domains/sandbox/spend-settlement.test.ts | 165 +++++- .../domains/sandbox/spend-settlement.ts | 78 ++- .../domains/sandbox/turn-budget.test.ts | 31 +- .../backend/domains/sandbox/turn-budget.ts | 39 +- .../backend/domains/sandbox/watchdogs.test.ts | 12 +- .../domains/sandbox/workspace-write-shim.ts | 11 +- .../tasks/agent-read-tools.integration.ts | 217 +++++++ .../backend/domains/tasks/agent-runs.test.ts | 27 + .../backend/domains/tasks/agent-runs.ts | 3 + .../domains/tasks/agent-work-state.test.ts | 69 ++- .../backend/domains/tasks/agent-work-state.ts | 102 +++- .../backend/domains/tts/budget.integration.ts | 532 ++++++++++++++++++ .../tts/service.attempt-budget.test.ts | 283 ++++++++++ .../tts/service.project-budget.test.ts | 125 +++- .../domains/tts/service.reserve.test.ts | 163 +++++- .../platform/backend/domains/tts/service.ts | 191 +++++-- .../platform/backend/integration-check.ts | 17 +- .../jobs/automation-floor.integration.ts | 168 +++++- .../platform/backend/rest/error-codes.test.ts | 3 + services/platform/lib/chat/turn.test.ts | 1 + services/platform/lib/chat/turn.ts | 4 + .../platform/lib/engine/core/syntax/parse.ts | 90 +-- .../lib/engine/core/syntax/tokens.test.ts | 146 ++++- .../platform/lib/engine/core/syntax/tokens.ts | 15 +- services/platform/messages/de/governance.yml | 2 + services/platform/messages/de/settings.yml | 1 + services/platform/messages/en/governance.yml | 2 + services/platform/messages/en/settings.yml | 1 + services/platform/messages/fr/governance.yml | 2 + services/platform/messages/fr/settings.yml | 1 + .../tests/guards/turbo-inputs.guard.test.ts | 5 + .../tests/integration/container-smoke-test.ts | 34 ++ .../tests/manual/reference/automation.md | 18 +- .../reference/automation/automations.md | 3 +- .../tests/manual/reference/automation/chat.md | 1 + .../manual/reference/automation/settings.md | 4 + .../tests/manual/reference/error-codes.md | 1 + services/platform/turbo.json | 3 + services/proxy/docker-entrypoint.sh | 12 +- services/sandbox/README.md | 7 + services/sandbox/src/volume.test.ts | 56 +- services/sandbox/src/volume.ts | 6 +- tools/cli/README.md | 39 +- tools/cli/src/lib/actions/deploy.ts | 11 - .../compose/services/compose-parity.test.ts | 19 + .../cli/src/lib/config/platform-docs.test.ts | 35 ++ .../lib/deployment/acceptance-migrations.ts | 15 +- .../lib/deployment/automation-cutover-sql.ts | 67 +++ .../automation-cutover.integration.test.ts | 202 +++++++ .../lib/deployment/automation-cutover.test.ts | 436 ++++++++++++++ .../src/lib/deployment/automation-cutover.ts | 374 ++++++++++++ .../deployment/automation-protocol.test.ts | 68 +++ .../src/lib/deployment/automation-protocol.ts | 43 +- .../lib/deployment/automation-session.test.ts | 92 +++ .../src/lib/deployment/automation-session.ts | 139 +++++ tools/cli/src/lib/deployment/inputs.test.ts | 4 +- tools/cli/src/lib/deployment/runtime-apply.ts | 19 + .../cli/src/lib/deployment/runtime-command.ts | 4 + tools/cli/src/lib/deployment/runtime-model.ts | 7 + tools/cli/src/lib/deployment/sources.test.ts | 111 ++++ tools/cli/src/lib/deployment/sources.ts | 84 ++- .../lib/deployment/tag-automation-protocol.ts | 23 + .../docker/prune-superseded-images.test.ts | 200 ------- .../src/lib/docker/prune-superseded-images.ts | 144 ----- tools/cli/tests/fixtures/exec-bounded.ts | 4 +- 143 files changed, 7778 insertions(+), 1097 deletions(-) create mode 100644 .github/release-notes/v0.5.79.md create mode 100644 services/platform/backend/core/automations/llm_budget.ts rename services/platform/{app/features/settings/governance/data-subject-requests/breakdown-entries.test.ts => backend/core/governance/erasure_counts.test.ts} (96%) rename services/platform/{app/features/settings/governance/data-subject-requests/breakdown-entries.ts => backend/core/governance/erasure_counts.ts} (100%) create mode 100644 services/platform/backend/db/migrations/0164_immutable_budget_reservations.sql create mode 100644 services/platform/backend/domains/governance/immutable-projects.integration.ts create mode 100644 services/platform/backend/domains/tts/budget.integration.ts create mode 100644 services/platform/backend/domains/tts/service.attempt-budget.test.ts create mode 100644 tools/cli/src/lib/deployment/automation-cutover-sql.ts create mode 100644 tools/cli/src/lib/deployment/automation-cutover.integration.test.ts create mode 100644 tools/cli/src/lib/deployment/automation-cutover.test.ts create mode 100644 tools/cli/src/lib/deployment/automation-cutover.ts create mode 100644 tools/cli/src/lib/deployment/automation-session.test.ts create mode 100644 tools/cli/src/lib/deployment/automation-session.ts delete mode 100644 tools/cli/src/lib/docker/prune-superseded-images.test.ts delete mode 100644 tools/cli/src/lib/docker/prune-superseded-images.ts diff --git a/.agents/repo.md b/.agents/repo.md index d61348d886..913922e7fb 100644 --- a/.agents/repo.md +++ b/.agents/repo.md @@ -769,6 +769,9 @@ xlsx,odt}.ts`) still reach the catch-all as `failed` + `indexer_error` and are r that the old execution is retired, an authorized decision about unknown external effects, and a guarded release contract. Never clear the hold or manufacture node-attempt evidence merely because a stop was requested, a lease expired, or the old containers disappeared. + Erasure deletes other eligible subject runs and records the held runs separately on a partial + receipt; organization deletion returns an explicit conflict. These are containment, not a + retirement contract or a release of the holds. - **A run lease compares the clocks of the hosts it spans** — the stepper stamps and checks the 30 s lease with its own host's clock (`claimRun`, `heartbeatRun`, `sweepOverdueRuns`), and the read model's `stalled` compares it with the database's. Workers on hosts whose clocks differ by diff --git a/.github/ci-scope.yml b/.github/ci-scope.yml index 6439b749b4..789b605b6a 100644 --- a/.github/ci-scope.yml +++ b/.github/ci-scope.yml @@ -20,6 +20,7 @@ integration: - 'tools/cli/src/lib/deployment/acceptance-migrations.ts' - 'tools/cli/src/lib/deployment/migration-model.ts' - 'tools/cli/src/lib/deployment/automation-floor.ts' + - 'tools/cli/src/lib/deployment/automation-cutover-sql.ts' - 'tools/cli/src/lib/deployment/automation-model.ts' - 'tools/cli/src/lib/deployment/source-migrations.ts' - 'tools/cli/src/lib/deployment/runtime-command.ts' @@ -59,12 +60,15 @@ cli: - 'services/platform/backend/auth/oidc.ts' - 'services/platform/backend/db/sql.ts' - 'services/platform/backend/db/ssl.ts' + - 'services/platform/backend/domains/api_keys/owners.ts' + - 'services/platform/backend/domains/api_keys/retire.ts' - 'services/platform/backend/domains/audit_logs/**' - 'services/platform/backend/domains/sandbox/retirement-schedule.ts' - 'services/platform/backend/domains/two_factor/service.ts' - 'services/platform/backend/jobs/enqueue.ts' - 'services/platform/backend/jobs/tasks.ts' - 'services/platform/backend/lib/org-config.ts' + - 'services/platform/backend/realtime/outbox.ts' - 'services/platform/lib/**' - 'configs/platform/**' - 'packages/shared/**' diff --git a/.github/release-candidate-contract.json b/.github/release-candidate-contract.json index 46c574b039..9de1ef7f13 100644 --- a/.github/release-candidate-contract.json +++ b/.github/release-candidate-contract.json @@ -4506,12 +4506,15 @@ "services/platform/backend/auth/oidc.ts", "services/platform/backend/db/sql.ts", "services/platform/backend/db/ssl.ts", + "services/platform/backend/domains/api_keys/owners.ts", + "services/platform/backend/domains/api_keys/retire.ts", "services/platform/backend/domains/audit_logs/**", "services/platform/backend/domains/sandbox/retirement-schedule.ts", "services/platform/backend/domains/two_factor/service.ts", "services/platform/backend/jobs/enqueue.ts", "services/platform/backend/jobs/tasks.ts", "services/platform/backend/lib/org-config.ts", + "services/platform/backend/realtime/outbox.ts", "services/platform/lib/**", "configs/platform/**", "packages/shared/**", diff --git a/.github/release-notes/v0.5.79.md b/.github/release-notes/v0.5.79.md new file mode 100644 index 0000000000..4b4c724d90 --- /dev/null +++ b/.github/release-notes/v0.5.79.md @@ -0,0 +1,177 @@ +## Highlights + +- API-key creation offers a custom expiry option and previews the resulting expiry date. + The keys table now includes an **Expires** column. + [#4495](https://github.com/tale-project/tale/pull/4495) +- Owners and Admins can create an organization-bound API key for another eligible member, + a team, a project or the organization itself. A member's key follows that member's live + permissions; team, project and organization keys act with their own assigned role and keep + working when their creator leaves. + [#4501](https://github.com/tale-project/tale/pull/4501) +- A project's API key cannot read organization-wide knowledge entries through chat search, + listing or the user-keyed sandbox entry finder. Its scoped project document access remains + available. + [#4565](https://github.com/tale-project/tale/pull/4565) +- Project budget rules cap the project's chats, agent turns, automation model calls, voice + output and calls made with its own API keys, in addition to other applicable limits. Pending + work reserves its admitted usage, and moving a chat or changing an automation's project + installations does not move an existing reservation or its booking. Uncertain voice and + direct automation model outcomes retain a conservative usage estimate before retrying. + The refusal identifies a reached project limit; see the upgrade notes for accounting limits. + [#4505](https://github.com/tale-project/tale/pull/4505), + [#4507](https://github.com/tale-project/tale/pull/4507), + [#4565](https://github.com/tale-project/tale/pull/4565) +- Chat consistently checks attachment access across deferred sends, retries and regenerated + replies. Existing message history is not rewritten. +- Agent connector calls keep credentials in the platform process and avoid launching a + sandbox process for every call. Within each backend process, the bridge limits concurrent + calls for each session; a deadline signal stops further service requests after a short grace + period. + [#4544](https://github.com/tale-project/tale/pull/4544) +- Erasure requests can delete eligible automation runs while preserving runs held after an + upgrade. The receipt stays **Partial**, explains the execution hold, and counts deleted and + preserved runs separately. Its summary and detailed breakdown now agree for both stored + count formats. Deleting an organization with these holds returns an explanatory conflict. + [#4565](https://github.com/tale-project/tale/pull/4565) +- Automation template analysis reuses its whitespace scan when recovering from repeated + malformed expressions. Long shared whitespace suffixes no longer cause the same text to be + scanned and trimmed for each failed expression. Existing expression limits and quoted + delimiters keep their behavior. + [#4564](https://github.com/tale-project/tale/pull/4564), + [#4565](https://github.com/tale-project/tale/pull/4565) +- The public proxy refuses private deployment-control paths, including deployments under a URL + prefix. The CLI continues to use its local control connection for deployment operations. + [#4563](https://github.com/tale-project/tale/pull/4563), + [#4565](https://github.com/tale-project/tale/pull/4565) +- Project agents can request a compact `task_get` occupancy view that returns the newest run + beside an explicitly requested historical run. It omits large discussions and review files + when the caller only needs a run observation. The default full response remains available; + a read does not reserve capacity or authorize a start or review decision. + [#4569](https://github.com/tale-project/tale/pull/4569) +- Idle sandbox spawners avoid loading unused Kubernetes and error-reporting integrations. + Capacity checks and cleanup reuse bounded Docker inventory reads, reducing repeated process + launches while retaining resource and ownership checks. + [#4542](https://github.com/tale-project/tale/pull/4542) +- Sandbox cache permission repairs use a digest-pinned BusyBox helper image. First use still + needs registry access if the image is not cached. + [#4565](https://github.com/tale-project/tale/pull/4565) +- Sandbox cleanup briefly rereads an empty process environment so it can find owned processes + caught while starting another executable. The existing scan deadline and process-ownership + checks remain in force. + [#4531](https://github.com/tale-project/tale/pull/4531) +- Knowledge databases store embeddings in separate tables for each supported vector width. + Organizations sharing a database can choose different widths. Saving a different width in + Data residency queues already indexed documents that lack vectors at that width. + [#4445](https://github.com/tale-project/tale/pull/4445) +- Failed Git commands during CLI source acquisition identify the source type, Git stage and + validated exit status when available, with bounded hints for disk, DNS, timeout and + output-limit failures. Private Git output and credentials remain hidden. These hints help + investigate a failure; they do not establish its cause or trigger an automatic retry. + [#4573](https://github.com/tale-project/tale/pull/4573) + +## Upgrade notes + +- v0.5.78 publication was stopped after source defects were confirmed. Its existing tag and + package publications remain immutable. Use this release's CLI and matching runtime images + for the complete forward upgrade. Do not rebuild or retag v0.5.78. Its retained + [authored notes](https://github.com/tale-project/tale/blob/4d60debc9263784f98bd74b36d3a4e8576125126/.github/release-notes/v0.5.78.md) + describe the preceding feature changes and remaining known limitations when upgrading from + v0.5.77; they are not evidence that v0.5.78 finished publishing or deploying. +- Back up the application and knowledge databases, configuration, keys and external stores + before deployment. The first upgrade from v0.5.77 applies application migrations + `0154` (API-key ownership), `0155` (project usage) and `0160`–`0163` (automation leases, + recovery history, per-step call records and the protocol-2 writer fence), plus `0164` + (captured budget projects and pending voice estimates). A configuration-only + update does not install these runtime changes. +- Existing personal API keys retain their behavior. Older images refuse the new + organization-bound keys, so finish the runtime rollout before moving an integration to one. + Agents and automations started by a project's key retain their own permissions and tool + access, which may reach beyond the project. Revoking a key blocks future calls but + does not stop work already admitted. See [API keys](https://docs.tale.dev/platform/admin/api-keys). +- Project usage starts with bookings made by the new runtime; migration `0155` does not backfill + earlier spend, and older images do not write the new project buckets during a mixed-version + rollout. Budget periods spanning the upgrade can therefore undercount project usage. Finish + retiring older admission processes before relying on the new reservations for every request. + Legacy pending rows without project stamps retain their prior lookup behavior; an unknown + historical voice price is not reconstructed. Project budgets exclude transcription and do + not send advance warnings. See + [Policies and limits](https://docs.tale.dev/platform/admin/governance/policies-and-limits). +- Direct automation `llm` calls require catalog pricing before admission. They reserve the + estimated prompt and permitted output, plus one request; these are estimates, not a + provider-enforced monetary ceiling. Unknown outcomes book that saved estimate once. A + reserved voice attempt that fails, times out or is replaced also books its saved estimate + and one request, including failures before dispatch. This may conservatively count an + attempt the provider did not charge. Retries must fit the remaining budget after that + booking. Authorized history retention and privacy erasure still delete their covered data; + the repair neither reconstructs erased usage nor guarantees caps across that deletion. +- Knowledge migrations `private_knowledge/15` and `public_web/16` copy existing vectors and build + indexes while retaining the legacy vector column for compatibility. Allow disk space for both + copies and time for the corpus-sized migration. Supported widths are 256, 384, 512, 768, 1024, + 1536, 2048, 3072 and 4096; widths above 2000 use sequential vector scans. An unsupported + existing width requires selecting a supported model and indexing again. Changing width + re-embeds documents through the configured provider and can incur provider usage. Keep the + existing width during a mixed-version rollout: the older image can search newly indexed data + only at its legacy column's declared width. Same-width model changes do not automatically + re-embed the corpus. See [Data residency](https://docs.tale.dev/self-hosted/configuration/data-residency). +- The managed upgrade first requires zero unfinished automation runs across every organization. + For the supported legacy runtime `b4931db4`, the CLI verifies the complete migration inventory, + holds a database lock against new admissions and claims, and gracefully stops the recorded + backend API and worker containers before migration `0163`. The initial census and compatibility + checks run before any backend stop. A failed stop or changed identity leaves cutover pending. + Existing protocol-1 tag deployments must use this managed upgrade first. Keep the bundle and + cutover receipt if a stop or readback fails; the + CLI starts no replacements until its recovery checks pass. This barrier does not establish + the outcome of historical external effects or cancel independent project agents. + [#4579](https://github.com/tale-project/tale/pull/4579), + [#4565](https://github.com/tale-project/tale/pull/4565) +- Migration `0163` retains a fallback for older queued, running and waiting automation runs + still present at cutover: they become **On hold**. Their + earlier progress and unknown external outcomes remain protected, and they do not resume + automatically. Already-admitted external work may still finish. Check the external service + before taking further action. **Request stop** records an acknowledgement and requests owned + session cancellation; it does not prove termination, undo effects or release the hold. + There is currently no supported retirement action that releases these legacy holds. Their + tasks remain excluded from replacement runs, erasure stays partial, and organization deletion + is refused while a hold remains. Plan the cutover around this limitation. +- After migration, repair forward with a compatible runtime and this release's CLI. The CLI + checks the installed database floor and target image before deployment or rollback. An + already-created protocol-2 backend also requires a compatible target, even while stopped or + before its migration commits. Older CLIs and manual Docker commands do not implement this + guard, and a snapshot cannot undo external effects. The guard currently supports the bundled + application database: an explicit + `DATABASE_URL`, custom `APP_DB_NAME` or installed backend pointing elsewhere is refused. + It does not start a stopped database to inspect it. Keep the existing runtime and repair the + readback when compatibility cannot be established. A successful cutover is only one part of + release acceptance: verify the completed rollout, serving identities, migration inventories + and native configuration readback for every deployment. See + [Upgrades](https://docs.tale.dev/self-hosted/operate/upgrades). +- Custom Compose configurations need at least `30s` stop grace for `backend-api` and `120s` for + `backend-worker`. `SHUTDOWN_DRAIN_MS` defaults to `15000` for the API and `90000` for a worker; + keep stop grace at least 15 seconds above a longer drain setting. The matching CLI generates + these values. `AUTOMATION_ORG_CONCURRENCY` defaults to `8` steps per organization across + workers; `0` disables that limit. Synchronize clocks across worker hosts. +- Update clients that exhaustively handle automation states and failure codes for REST/OpenAPI + contract `3.22.0`, including held runs, stop requests, resumption fields, `waitingFor: in_doubt`, + `engine_incompatible` and `effect_in_doubt`. An uncertain individual write is decided in the + app, separately from a legacy run's stop request. No notification is sent for an in-doubt wait. + Clients must also accept `GET /api/v1/me`'s `key.owner`, an empty `user.email` for a key that + is not a person, and `data.scope: project` on a `429 BUDGET_EXCEEDED` response. A project's + key receives `403 API_KEY_SCOPE_FORBIDDEN` outside its permitted routes. +- The inherited MCP authoring changes include issue locations, analysis and inferred types in + validation results, save warnings, and capability output schemas. Revalidate custom + automations: agent `files` contribute dependencies and `ITEM_WITHOUT_FOREACH` is an error. + Expressions and `transform` bodies have analysis limits of 8192 UTF-16 code units, 512 + JavaScript tokens and 64 nesting levels. Whitespace around a template expression is excluded + from its size; whitespace inside a `transform` body counts. Shorten or split oversized code. + See [Automation concepts](https://docs.tale.dev/platform/automations/concepts). +- Before using compact occupancy reads, require `output.view` to equal `occupancy`. Older + runtimes can return the full view without binding `requestedRunId`; do not treat that as a + supported compact result. Missing or failed reads leave occupancy unknown. Workflow holds + still block replacement even when their run is not live, and normal start/retry limits apply. +- When upgrading from v0.5.76 or earlier, also follow the + [v0.5.77 upgrade notes](https://github.com/tale-project/tale/releases/tag/v0.5.77), including + the Bun 1.4.2 runtime, serving-identity proxy header, pinned contract-digest review and + `task_delegate_review` runtime prerequisite. The built-in **Triage GitHub issues** and + **Review GitHub pull requests** schedules still require their missing repository inputs + (`owner` and `repo`); editor validation reports `TRIGGER_INPUT_MISMATCH` but does not repair + those schedules. diff --git a/.github/renovate.json b/.github/renovate.json index 9049c1dfd5..c061b4809a 100644 --- a/.github/renovate.json +++ b/.github/renovate.json @@ -21,6 +21,17 @@ "labels": ["dependencies", "security"] }, "osvVulnerabilityAlerts": true, + "customManagers": [ + { + "customType": "regex", + "managerFilePatterns": ["/^services/sandbox/src/volume\\.ts$/"], + "matchStrings": [ + "CACHE_PERMISSION_IMAGE\\s*=\\s*'(?busybox):(?[^'@\\s]+)@(?sha256:[a-f0-9]{64})'" + ], + "datasourceTemplate": "docker", + "versioningTemplate": "docker" + } + ], "packageRules": [ { "description": "Patch updates: 30 day stabilization, grouped", diff --git a/.github/workflows/cli.yml b/.github/workflows/cli.yml index 17b0d82ed9..f09816750d 100644 --- a/.github/workflows/cli.yml +++ b/.github/workflows/cli.yml @@ -25,12 +25,15 @@ on: - 'services/platform/backend/auth/oidc.ts' - 'services/platform/backend/db/sql.ts' - 'services/platform/backend/db/ssl.ts' + - 'services/platform/backend/domains/api_keys/owners.ts' + - 'services/platform/backend/domains/api_keys/retire.ts' - 'services/platform/backend/domains/audit_logs/**' - 'services/platform/backend/domains/sandbox/retirement-schedule.ts' - 'services/platform/backend/domains/two_factor/service.ts' - 'services/platform/backend/jobs/enqueue.ts' - 'services/platform/backend/jobs/tasks.ts' - 'services/platform/backend/lib/org-config.ts' + - 'services/platform/backend/realtime/outbox.ts' - 'services/platform/lib/**' - 'configs/platform/**' - 'packages/shared/**' diff --git a/docs/de/platform/admin/governance/data-subject-requests.md b/docs/de/platform/admin/governance/data-subject-requests.md index d9ffbb4e9a..cc72fcc91a 100644 --- a/docs/de/platform/admin/governance/data-subject-requests.md +++ b/docs/de/platform/admin/governance/data-subject-requests.md @@ -20,6 +20,8 @@ Als Admin oder Inhaber bearbeitest du unter **Einstellungen > Richtlinien > Anfr Die Löschung entfernt betroffene Daten endgültig; sie verschiebt sie nicht in den Papierkorb. Der Beleg erfasst Kategorien und Anzahlen, darunter Chats, Dokumente und Uploads, Einstellungen, Feedback, Benachrichtigungen, Nutzung und das Bereinigen von Personenkennungen im Audit-Protokoll. Die Löschung entfernt außerdem die getrennten Sandbox-Arbeitsbereiche der [Agentenläufe, die die Person gestartet hat](/de/platform/projects/tasks#agentenlaeufe-die-ein-mitglied-startet), auch wenn darin noch Arbeit läuft; der Beleg zählt sie unter **Sandbox-Arbeitsbereiche**. Ein Arbeitsbereich zählt erst, wenn der Sandbox-Dienst seine Dateien gelöscht hat, was bei einem großen eine Weile dauern kann. Bis dahin, oder solange das Löschen wiederholt fehlschlägt, lautet der Beleg **Teilweise** und nennt `sandboxWorkspaces` unter den fehlgeschlagenen Durchläufen; wähle später **Erneut versuchen**, und die Löschung wird abgeschlossen, sobald die Dateien entfernt sind. Unter Kubernetes zählt ein Arbeitsbereich, sobald sein Volume an den Storage-Provisioner des Clusters übergeben ist; mit einer StorageClass, deren `reclaimPolicy` `Retain` ist, bleiben die Dateien des Volumes, bis ein Operator das Volume entfernt, obwohl der Beleg den Arbeitsbereich zählt. Ein Sandbox-Dienst oder Gerät, das noch nicht auf diese Version aktualisiert ist, kann die Löschung nicht bestätigen; der Beleg bleibt dann **Teilweise**, bis es aktualisiert ist. +Die Kategorie **Modellanfragen** umfasst Anfragen an die Modell-API und direkte Modellaufrufe in Automationen. Abgerechnete Anfragen werden entfernt. Eine noch laufende Anfrage behält die Daten, die für ihre Abrechnung nötig sind; die Identität der Person wird durch ein Pseudonym ersetzt. Spätere Nutzung wird unter diesem Pseudonym verbucht. Schlägt das Entfernen des Automationslaufs oder der Identität fehl, bleibt der Beleg **Teilweise** und die davon abhängige Bereinigung der Nutzungsdaten wartet auf einen neuen Versuch. + Aufgaben, die die Person als **Reviewer** nennen, verlieren diese Zuweisung. Eine Prüfanfrage, die noch auf sie wartet, geht an die erste berechtigte Person der Ersatzfolge: den Ersteller der Aufgabe oder des Projekts. Diese Person wird benachrichtigt. Bei einer archivierten Aufgabe geht die Prüfanfrage ohne Benachrichtigung weiter. Prüfentscheidungen, die die Person bereits getroffen hat, bleiben ohne ihren Namen erhalten. ## Vorher die Richtlinie prüfen @@ -46,6 +48,8 @@ Nur der Inhaber kann diese Richtlinie ändern. Strengere Schutzmaßnahmen gelten Ein offener Beleg kann eine zweite Anfrage für dieselbe Person verhindern. Arbeite mit diesem Beleg weiter. War die Anfrage schon bei der Einreichung blockiert, muss ein neuer Versuch erneut die aktuelle Freigabe- und Wartezeitregel erfüllen. Ein Beleg, der auf Freigabe wartet, behält die bei der Einreichung festgehaltene Freigabepflicht: Schaltest du das Vier-Augen-Prinzip später aus, gibt ihn das nicht frei. +Automationsläufe, die bei einem Upgrade zurückgehalten wurden, bleiben erhalten, solange ihre früheren externen Aktionen nicht überprüft sind. Die Löschung entfernt weiterhin die anderen geeigneten Automationsläufe der Person und weist gelöschte und aufbewahrte Läufe getrennt aus. Der Beleg bleibt teilweise abgeschlossen. Diese Ausführungssperren sind von Legal Holds unabhängig und können derzeit nicht aufgehoben werden. Eine Stopp-Anfrage oder ein erneuter Löschversuch hebt sie nicht auf. Eine Organisation mit solchen Sperren kann ebenfalls nicht gelöscht werden. + ## Die Frist verwalten Die Liste zeigt die erfasste Frist und mögliche Überschreitungen. Nutze **Frist verlängern** für eine begründete Verlängerung, solange die Aktion verfügbar ist. Die Anwendung erlaubt eine Verlängerung vor Ablauf der ursprünglichen Frist und protokolliert Grund und Admin. diff --git a/docs/de/platform/admin/governance/policies-and-limits.md b/docs/de/platform/admin/governance/policies-and-limits.md index 04096e4d02..7a47445542 100644 --- a/docs/de/platform/admin/governance/policies-and-limits.md +++ b/docs/de/platform/admin/governance/policies-and-limits.md @@ -25,11 +25,17 @@ Eine Regel bleibt in der Tabelle, auch wenn ihr API-Schlüssel nicht mehr funkti Budgets gelten für neue kostenpflichtige Arbeit, einschließlich Chat, Sprachausgabe, verwalteter Agentenläufe, der `llm`-Schritte von Automatisierungen, der Bilder, die Agenten erstellen, und der Aufrufe der Modell-Endpunkte. Tale prüft jede Chat-Anfrage, bevor sie läuft — eine gesendete Nachricht, eine neu erzeugte oder bearbeitete Antwort, beide Seiten eines Modellvergleichs, eine Nachricht, die auf einen Anhang wartet, und ein Senden über die REST-API — und lehnt sie ab, sobald eine zutreffende Grenze erreicht ist. Die Ablehnung nennt die Grenze und wann sie zurückgesetzt wird. Antworten, die noch geschrieben werden, halten fest, was sie verbrauchen können, damit gleichzeitig gesendete Anfragen eine fast erreichte Grenze nicht gemeinsam überschreiten. Die Bildanfrage eines Agenten wird ebenso geprüft, bevor das Bildmodell aufgerufen wird: Solange ihre Bilder entstehen, hält sie geschätzte Kosten fest, und die Prüfung zählt auch mit, was der eigene Lauf des Agenten noch für sein Modell ausgeben kann. Jedes Bild zählt als eine Anfrage. Die Bildgenerierung braucht Kosten- oder Anfragelimits, weil ihre Nutzung nicht in Text-Tokens gemessen wird. Ein Tokenlimit zählt Eingabe- und Ausgabetokens, und zur Eingabe gehört auch der Teil eines Prompts, den ein Anbieter aus seinem Cache gelesen oder dort abgelegt hat. Dieser Teil wird anders berechnet als die übrige Eingabe, deshalb kann ein Agent, der einen langen Prompt wiederverwendet, ein Tokenlimit erreichen, während seine Kosten niedrig bleiben. Untersuche Warnungen in der [Nutzungsanalyse](/de/platform/admin/governance/usage-analytics). +Sprachausgabe reserviert während eines laufenden Versuchs die geschätzten Kosten und eine Anfrage. Der `llm`-Schritt einer Automatisierung reserviert die geschätzte Eingabe und die erlaubte Ausgabe zum Katalogpreis sowie eine Anfrage. Diese Reservierungen zählen zusammen mit Chats und verwalteten Agenten gegen die jeweils geltenden Limits. Es sind Schätzwerte, keine Garantie für die endgültige Abrechnung des Anbieters. + +Scheitert ein bereits reservierter Sprachversuch oder bleibt sein Ergebnis unbekannt, erfasst Tale den gespeicherten Schätzwert und eine Anfrage genau einmal, auch wenn der Fehler vor dem Anbieteraufruf auftrat. Für einen direkten Modellaufruf einer Automatisierung mit unbekanntem Ergebnis bucht Tale ebenfalls den reservierten Schätzwert. Diese vorsichtige Abrechnung bestätigt keine tatsächliche Belastung durch den Anbieter. Ein erneuter Versuch braucht eine neue Reservierung und muss einschließlich des vorherigen Schätzwerts ins Budget passen. + ## Verstehen, welche Grenzen gelten Persönliche Limits werden für jede Größe aus der spezifischsten Regel ermittelt, die sie festlegt: zuerst Person, dann Team, Rolle und Standard. Gehört jemand mehreren Teams mit einer Regel an, gilt für die Person die strengste dieser Grenzen. Organisationslimits gelten zusätzlich. Ein Teambudget begrenzt auch die gemeinsame Nutzung der aktuellen Teammitglieder, selbst wenn ein Mitglied eine spezifischere persönliche Regel hat: Die Nutzung eines neuen Mitglieds im laufenden Zeitraum zählt sofort, die eines ausgetretenen Mitglieds nicht mehr. API-Schlüssellimits begrenzen unabhängig die mit diesem Schlüssel authentifizierten Anfragen, deren Nutzung dem Schlüssel angerechnet wird, nicht andere Arbeit in der Oberfläche. Der eigene Schlüssel eines Teams, eines Projekts oder der Organisation ist keine Person: Für ihn gilt keine Personen-, Rollen- oder Standardregel. Die Limits der Organisation und ihre API-Schlüsselregeln gelten, der Schlüssel eines Teams zählt für das Budget seines Teams und wird von ihm begrenzt, und der Schlüssel eines Projekts ebenso für das Budget seines Projekts. -Ein Projektbudget begrenzt alles, was in einem Projekt ausgegeben wird, egal von wem: die Chats des Projekts mit ihren Titeln, den vorgelesenen Antworten und den Tool-Aufrufen des Assistenten; die Läufe seiner Agenten und die Agenten- und `llm`-Schritte der Automatisierungen, die darin laufen, mit den Bildern, die sie erstellen; und die Aufrufe mit den eigenen API-Schlüsseln des Projekts. Es gilt zusätzlich zu den Limits dessen, der die Arbeit angestoßen hat, auch für Läufe, die ein Zeitplan gestartet hat, und nie für Arbeit außerhalb des Projekts. Chatantworten und Agentenzüge, die im Projekt noch laufen, halten auch im Projektbudget fest, was sie verbrauchen können, damit gleichzeitig gesendete Anfragen ein fast erreichtes Projektbudget nicht gemeinsam überschreiten. Lehnt es eine Chatnachricht ab, sagt Tale, dass das Limit des Projekts erreicht ist. Transkribierte Aufnahmen zählen nicht für ein Projekt, und ein Projektbudget warnt niemanden, bevor es erreicht ist. Eine Automatisierung zählt für das Projekt, in dem sie läuft. Ein Lauf ohne eigenes Projekt, von einer Automatisierung, die in mehreren Projekten installiert ist, zählt für jedes davon und muss in jedes Projektbudget passen, so wie die Nutzung eines Mitglieds für jedes seiner Teams zählt; eine Automatisierung, die in keinem Projekt installiert ist, zählt nur für die Organisation. +Ein Projektbudget begrenzt alles, was in einem Projekt ausgegeben wird, egal von wem: die Chats des Projekts mit ihren Titeln, den vorgelesenen Antworten und den Tool-Aufrufen des Assistenten; die Läufe seiner Agenten und die Agenten- und `llm`-Schritte der Automatisierungen, die darin laufen, mit den Bildern, die sie erstellen; und die Aufrufe mit den eigenen API-Schlüsseln des Projekts. Es gilt zusätzlich zu den Limits dessen, der die Arbeit angestoßen hat, auch für Läufe, die ein Zeitplan gestartet hat, und nie für Arbeit außerhalb des Projekts. Laufende Chatantworten, Agentenzüge, Sprachversuche und Modellaufrufe von Automatisierungen reservieren ihre zugelassene Nutzung auch im Projektbudget, sodass gleichzeitige Anfragen diese Reservierungen berücksichtigen. Lehnt es eine Chatnachricht ab, sagt Tale, dass das Limit des Projekts erreicht ist. Transkribierte Aufnahmen zählen nicht für ein Projekt, und ein Projektbudget warnt niemanden, bevor es erreicht ist. Eine Automatisierung zählt für das Projekt, in dem sie läuft. Ein Lauf ohne eigenes Projekt, von einer Automatisierung, die in mehreren Projekten installiert ist, zählt für jedes davon und muss in jedes Projektbudget passen, so wie die Nutzung eines Mitglieds für jedes seiner Teams zählt; eine Automatisierung, die in keinem Projekt installiert ist, zählt nur für die Organisation. + +Chatantworten, Sprachversuche und Modellaufrufe von Automatisierungen behalten die Projekte, die bei ihrer Zulassung erfasst wurden. Verschiebst du den Chat oder änderst du während der Ausführung die Projektinstallationen einer Automatisierung, bleiben Reservierung und spätere Buchung den ursprünglichen Projekten zugeordnet. Ein Versuch, der ohne Projekt zugelassen wurde, bleibt außerhalb der Projektbudgets. diff --git a/docs/de/platform/admin/governance/usage-attribution.md b/docs/de/platform/admin/governance/usage-attribution.md index 0b09cb3a44..54da628599 100644 --- a/docs/de/platform/admin/governance/usage-attribution.md +++ b/docs/de/platform/admin/governance/usage-attribution.md @@ -29,6 +29,8 @@ Ein erneuter Versuch eines Agentenlaufs führt den Lauf fort, den sein Starter a Arbeit in einem Projekt zählt zusätzlich für dieses Projekt, egal wer sie angestoßen hat: die Chats des Projekts mit ihren Titeln, den vorgelesenen Antworten und den Tool-Aufrufen des Assistenten; die Läufe seiner Agenten und die Agenten- und `llm`-Schritte der Automatisierungen, die darin laufen, mit den Bildern, die sie erstellen; und die Aufrufe mit den eigenen API-Schlüsseln des Projekts. Ein Lauf ohne eigenes Projekt, von einer Automatisierung, die in mehreren Projekten installiert ist, zählt für jedes davon; eine Automatisierung, die in keinem Projekt installiert ist, zählt nur für die Organisation. Eine Transkription zählt nicht für ein Projekt. +Chatantworten, Sprachversuche und Modellaufrufe von Automatisierungen behalten die Projekte, die bei ihrer Zulassung erfasst wurden. Verschiebst du den Chat oder änderst du während der Ausführung die Projektinstallationen einer Automatisierung, bleiben Reservierung und spätere Buchung den ursprünglichen Projekten zugeordnet. Ein Versuch, der ohne Projekt zugelassen wurde, bleibt außerhalb der Projektbudgets. + Ein API-Schlüssel, den ein Admin für ein Mitglied erstellt hat, zählt für dieses Mitglied, wie dessen eigener Schlüssel. Ein Schlüssel, der einem Team, einem Projekt oder der Organisation gehört ([API-Schlüssel](/de/platform/admin/api-keys#create-a-key-for-someone-else)), ist keine Person: Was er anstößt, zählt für den Schlüssel selbst. Die Nutzungsanalyse zeigt ihn als eigene Zeile unter **Nutzung pro Benutzer**, unter dem Namen des Schlüssels mit seinem Team, seinem Projekt oder der Organisation darunter, und zählt ihn nie als aktive Person. Der Schlüssel eines Teams zählt zusätzlich für die Nutzung seines Teams. ## Welche Limits gelten @@ -38,7 +40,9 @@ Ein API-Schlüssel, den ein Admin für ein Mitglied erstellt hat, zählt für di - **API-Schlüssellimits** binden die Anfragen, die mit diesem Schlüssel authentifiziert wurden: die damit gesendeten Chatnachrichten, die damit gestellten Aufrufe der Modell-Endpunkte und die damit gestarteten Läufe. - **Projektlimits** binden die Arbeit in diesem Projekt, egal wer sie angestoßen hat, auch die Läufe eines Triggers. -Ist ein Limit erreicht, lehnt Tale die nächste Anfrage vor der Ausführung ab und nennt das Limit. Ein Zug eines verwalteten Agenten wird beim Start abgelehnt; ein bereits laufender Zug behält den Rahmen, den er bekommen hat. Ein Bild, das der Agent während seines Zugs anfordert, wird eigens geprüft, bevor das Bildmodell aufgerufen wird: Ist ein Limit erreicht, lehnt Tale das Bild ab, und der Zug läuft weiter. Das Bild zehrt außerdem vom Rahmen des Zugs, der es angefordert hat. Der `llm`-Schritt einer Automatisierung wird vor jedem Modellaufruf geprüft: Lehnt ein Limit den Aufruf ab, schlägt der Schritt mit `budget_exceeded` fehl, und sein Fehler nennt das Limit; der Lauf schlägt mit ihm fehl, außer das `onError` des Schritts ist `continue`. Der Schritt hält nichts fest, während sein Aufruf läuft; gleichzeitig gestartete Läufe können ein fast erreichtes Limit deshalb gemeinsam überschreiten. [So werden Regeln kombiniert](/de/platform/admin/governance/policies-and-limits#how-rules-combine) beschreibt den Fall, dass mehrere Regeln für eine Person gelten. +Ist ein Limit erreicht, lehnt Tale die nächste Anfrage vor der Ausführung ab und nennt das Limit. Ein Zug eines verwalteten Agenten wird beim Start abgelehnt; ein bereits laufender Zug behält den Rahmen, den er bekommen hat. Ein Bild, das der Agent während seines Zugs anfordert, wird eigens geprüft, bevor das Bildmodell aufgerufen wird: Ist ein Limit erreicht, lehnt Tale das Bild ab, und der Zug läuft weiter. Das Bild zehrt außerdem vom Rahmen des Zugs, der es angefordert hat. Der `llm`-Schritt einer Automatisierung wird vor jedem Modellaufruf geprüft: Lehnt ein Limit den Aufruf ab, schlägt der Schritt mit `budget_exceeded` fehl, und sein Fehler nennt das Limit; der Lauf schlägt mit ihm fehl, außer das `onError` des Schritts ist `continue`. Der Schritt reserviert die geschätzte Eingabe und die erlaubte Ausgabe zum Katalogpreis sowie eine Anfrage bis zur Abrechnung. Gleichzeitig laufende Aufrufe berücksichtigen dadurch die Reservierungen der anderen. Bleibt das Ergebnis des Anbieters unbekannt, bucht Tale den gespeicherten Schätzwert einmal, statt ihn stillschweigend freizugeben; ein erneuter Versuch wird neu geprüft. [So werden Regeln kombiniert](/de/platform/admin/governance/policies-and-limits#how-rules-combine) beschreibt den Fall, dass mehrere Regeln für eine Person gelten. + +Sprachausgabe reserviert während eines laufenden Versuchs die geschätzten Kosten und eine Anfrage. Scheitert ein bereits reservierter Versuch oder bleibt sein Ergebnis unbekannt, wird dieser Schätzwert einmal erfasst, auch bei Fehlern vor dem Anbieteraufruf. Diese vorsichtige Abrechnung bestätigt keine tatsächliche Belastung. Bei einem erneuten Versuch zählt der vorherige Schätzwert bei der Prüfung des verbleibenden Budgets mit. ## Drei Situationen, die du kennen solltest diff --git a/docs/de/platform/automations/concepts.md b/docs/de/platform/automations/concepts.md index bcd721d5c7..7d1fda8a9e 100644 --- a/docs/de/platform/automations/concepts.md +++ b/docs/de/platform/automations/concepts.md @@ -68,7 +68,7 @@ Vier Typen sind eingebaut, und jede Connector-Aktion sowie jede Plattformfunktio **`transform`** führt reines JavaScript aus, um Daten umzuformen. Ohne Netzwerk und ohne Imports: Der Rumpf liest die aufgelöste `input` der Node und muss einen Wert zurückgeben. -**`llm`** ruft ein Sprachmodell mit einem Prompt-Template auf. `model` ist Pflicht und immer ausdrücklich — eine Automatisierung wählt nie eines für dich (das Auto der Chat-Eingabezeile ist eine reine Chat-Sache). Die Ausgabe ist `{text}` oder das Objekt in Form des Schemas, wenn die Node ein `outputSchema` deklariert. Jeder Aufruf in einem Live-Lauf ist Nutzung des Laufs: Er wird vorher gegen die [Budgetlimits](/de/platform/admin/governance/policies-and-limits) geprüft, und ein Aufruf, den ein Limit ablehnt, lässt die Node mit `budget_exceeded` fehlschlagen, was den Lauf abbricht, außer ihr `onError` ist `continue`. +**`llm`** ruft ein Sprachmodell mit einem Prompt-Template auf. `model` ist Pflicht und immer ausdrücklich — eine Automatisierung wählt nie eines für dich (das Auto der Chat-Eingabezeile ist eine reine Chat-Sache). Die Ausgabe ist `{text}` oder das Objekt in Form des Schemas, wenn die Node ein `outputSchema` deklariert. Jeder Aufruf in einem Live-Lauf ist Nutzung des Laufs: Er wird vorher gegen die [Budgetlimits](/de/platform/admin/governance/policies-and-limits) geprüft, und ein Aufruf, den ein Limit ablehnt, lässt die Node mit `budget_exceeded` fehlschlagen, was den Lauf abbricht, außer ihr `onError` ist `continue`. Vor dem Anbieteraufruf reserviert jeder Versuch die geschätzten Prompt-Kosten und das maximale Antwortbudget in allen für diesen Versuch berücksichtigten Projekten. Dafür braucht das Modell Katalogpreise. Sobald der Aufruf endet, ersetzt die gemeldete Nutzung die Reservierung. Bleiben die Kosten wegen einer Zeitüberschreitung, einer unterbrochenen Verbindung oder fehlender Nutzungsdaten unbekannt, bleibt die Reservierung bis zur Anfragefrist bestehen und wird danach als reservierter Schätzwert verbucht; das ist eine Schätzung, keine Anbieterrechnung. Änderungen an Projektzuordnungen während des Aufrufs verschieben dessen Verbrauch nicht. **`agent`** führt einen Agent-Turn eines Coding-Agents (Claude Code, Codex und die übrigen Agent-Laufzeiten) in der Sandbox aus. Er liest bereitgestellte `files`, nutzt `skills`, vermittelte `connectors`, gewährte Plattform-`tools` und eingespielte `secrets` und gibt `{text, files, status}` zurück; `model` ist Pflicht. Hat ein Admin die [Bildgenerierung](/de/platform/admin/governance/content-models#let-agents-generate-images) eingeschaltet, kann er auch Bilder erstellen, die unter seinen `files` zurückkommen. Greif zu `llm`, wenn eine einmalige Completion reicht, und zu `agent` nur, wenn der Schritt Werkzeuge, Dateien oder mehrere Turns braucht — eine live geschaltete Agent-Node läuft als asynchroner Turn, sitzt daher auf der obersten Ebene statt in einer `subautomation` und iteriert nicht mit `forEach`. diff --git a/docs/de/self-hosted/operate/upgrades.md b/docs/de/self-hosted/operate/upgrades.md index 5db8d84f53..d75985996f 100644 --- a/docs/de/self-hosted/operate/upgrades.md +++ b/docs/de/self-hosted/operate/upgrades.md @@ -63,8 +63,6 @@ Beide Farben verwenden das Volume `static-assets` der Bereitstellung. Bevor eine Ein offener Tab arbeitet bei der Übergabe normalerweise weiter. Ist ein benötigter Teil nicht mehr verfügbar, wartet Tale, bis API und Datenbank antworten, und lädt dann einmal neu. Lässt sich der Teil weiterhin nicht laden, zeigt Tale **Eine neue Version ist verfügbar** mit der Aktion **Neu laden**, statt erneut automatisch zu laden. Während eines Ausfalls bleibt der Verbindungshinweis sichtbar. Fehlgeschlagene Leseanfragen werden nach der Wiederverbindung aktualisiert; fehlgeschlagene Schreibanfragen werden nicht automatisch erneut gesendet. -Sobald die Dienste aktualisiert sind, entfernt die CLI die Tale-Images aller Versionen, die älter sind als die neue Version und das gespeicherte Rollback-Ziel. Der Host behält so die Images von zwei Releases statt von jedem Release, das je lief. Erzwungen wird nichts: Ein Image, das ein Container noch nutzt, etwa ein Dienst, der auf einer älteren Version weiterläuft, oder eine Sandbox-Sitzung, die vor dem Deployment startete, bleibt, bis ein späteres Deployment es frei vorfindet. Images, die du für eine spätere Version vorab geladen hast, bleiben ebenfalls. - Wird die neue Gruppe nicht innerhalb von `HEALTH_CHECK_TIMEOUT` gesund, schließt die CLI den Wechsel nicht ab. Prüfe gespeicherten Bereitstellungszustand und Protokolle vor einem erneuten Versuch. Ein unterbrochener Rollout kann beide Gruppen oder eine ausstehende Übergabe hinterlassen. Folge den Wiederherstellungshinweisen der CLI, statt Container oder Zustandsdateien von Hand zu löschen. ## Migrationen und Nutzerergebnis prüfen diff --git a/docs/en/platform/admin/governance/data-subject-requests.md b/docs/en/platform/admin/governance/data-subject-requests.md index 029a302cd6..ed11bfed66 100644 --- a/docs/en/platform/admin/governance/data-subject-requests.md +++ b/docs/en/platform/admin/governance/data-subject-requests.md @@ -20,6 +20,8 @@ Use **Settings > Governance > Data subject requests** as an Admin or Owner to pr Erasure permanently removes covered data; it is not a move to Trash. The receipt records the affected categories and counts, including chats, documents and uploads, preferences, feedback, notifications, usage, and audit-identifier scrubbing. The erasure also deletes the separate sandbox workspaces of the [agent runs the person started](/platform/projects/tasks#agent-runs-a-member-starts), even while work still runs in them, and the receipt counts them under **Sandbox workspaces**. A workspace counts only once the sandbox service has deleted its files, which can take a while for a large one. Until then, or while deleting them keeps failing, the receipt reads **Partial** with `sandboxWorkspaces` among its failed passes; choose **Retry** later, and the erasure completes once the files are gone. On Kubernetes, a workspace counts once its volume is handed to the cluster's storage provisioner; with a StorageClass whose `reclaimPolicy` is `Retain`, the volume's files stay until an operator removes the volume, although the receipt counts the workspace. A sandbox service or device that is not yet updated to this version cannot confirm the deletion, so the receipt stays **Partial** until it is updated. +The **Model requests** category covers requests to the model API and direct model calls in automations. Settled requests are removed; a request still in progress keeps the information needed to finish accounting, with the person’s identity replaced by a pseudonym. Later usage is recorded under that pseudonym. If retiring the automation run or removing the identity fails, the receipt stays **Partial** and the dependent usage cleanup waits for a retry. + Tasks that name the person as **Reviewer** lose that designation. A task review still waiting on them moves to the first eligible human fallback, the task creator or project creator, and that person is notified. On an archived task the review moves without a notification. Review decisions the person already made stay on record without their name. ## Check the policy before filing @@ -46,6 +48,8 @@ Only the Owner can change this policy. Stronger safeguards apply immediately; we An open receipt for a subject can prevent a duplicate filing. Work from that receipt rather than creating repeated requests. A retry blocked at initial filing must satisfy the current approval and waiting-period policy again. A receipt awaiting approval keeps the approval requirement captured when it was filed: turning dual approval off later does not release it. +Automation runs held during an upgrade are preserved while their earlier external actions remain unverified. An erasure still deletes the person's other eligible automation runs and reports erased and preserved counts separately. The receipt stays partial. These execution holds are separate from legal holds, and currently have no release action. Requesting a stop or retrying erasure does not clear them. An organization containing these holds also cannot be deleted. + ## Manage the deadline The list shows the tracked deadline and whether it is overdue. Use **Extend deadline** for a justified extension while it is still available: the application permits one extension before the original deadline expires and records the reason and admin. diff --git a/docs/en/platform/admin/governance/policies-and-limits.md b/docs/en/platform/admin/governance/policies-and-limits.md index 6ffba3fd39..2de125410f 100644 --- a/docs/en/platform/admin/governance/policies-and-limits.md +++ b/docs/en/platform/admin/governance/policies-and-limits.md @@ -25,11 +25,17 @@ A rule stays in the table after its API key stops working. **Target** still name Budgets apply to new billable work, including chat, voice output, managed agent runs, the `llm` steps of automations, the images agents generate, and calls to the model endpoints. Tale checks every chat request before it runs — a sent message, a regenerated or edited reply, both sides of a model comparison, a message waiting for an attachment, and a send through the REST API — and refuses it once a cap that applies is reached, naming the cap and when it resets. Replies still being written hold what they may spend, so requests sent at the same moment cannot pass a nearly reached cap together. An agent's image request is checked the same way before the image model is called: while its images are being made it holds an estimated cost, and the check also counts what the agent's own run may still spend on its model. Each image counts as one request. Image generation needs cost or request limits because its usage is not measured as text tokens. A token limit counts input and output tokens, and input includes the part of a prompt that a provider read from or wrote to its cache. That part is priced differently from other input, so an agent that reuses a long prompt can reach a token limit while its cost stays low. Investigate warnings in [Usage analytics](/platform/admin/governance/usage-analytics). +Voice output reserves its estimated cost and one request while the attempt is pending. An automation’s `llm` step reserves the estimated prompt and permitted output at the catalog price, plus one request. These reservations share the applicable caps with chat and managed agent work. They are estimates, not a guarantee of the provider’s final charge. + +If a reserved voice attempt fails or its outcome is unknown, Tale records its saved estimate and one request once, even when the failure happened before the provider call. A direct automation model call with an unknown outcome similarly records its reserved estimate. This conservative accounting does not confirm a provider charge. A retry needs a new reservation and must fit the budget including the earlier estimate. + ## Understand which caps apply Personal limits resolve each dimension from the most specific rule that defines it: user, then team, role, and default. When someone belongs to several teams with a rule, the strictest of those caps applies to them personally. Organization limits apply in addition. A team budget also caps the combined usage of the team's current members, even when a member has a more specific personal rule: a new member's usage in the current period counts at once, and someone who leaves no longer counts. API-key limits independently cap requests authenticated with that key, and those requests' usage counts toward the key; they do not cap unrelated in-app work. A team's, a project's, or the organization's own key is not a person: no user, role, or default rule applies to it. The organization's limits and its API-key rules do, a team's key counts toward, and is held to, its team's budget, and a project's key its project's. -A project budget caps everything spent in one project, whoever spends it: the project's chats, with their titles, the answers read aloud, and the assistant's tool calls; the runs of its agents and the agent and `llm` steps of the automations run in it, with the images they generate; and the calls made with the project's own API keys. It applies on top of the limits of whoever asked for the work, including runs a schedule started, and never to work outside the project. Chat replies and agent turns still running in the project hold what they may spend against its budget too, so two sent at the same moment cannot pass a nearly reached project budget together. A chat message it refuses says the project's limit was reached. Transcribed recordings are not counted toward a project, and a project budget warns no one before it is reached. An automation counts toward the project it runs in. A run that names no project, of an automation installed in several projects, counts toward each of them and must fit each one's budget, as a member's spend counts toward each of their teams; an automation installed in no project counts toward the organization alone. +A project budget caps everything spent in one project, whoever spends it: the project's chats, with their titles, the answers read aloud, and the assistant's tool calls; the runs of its agents and the agent and `llm` steps of the automations run in it, with the images they generate; and the calls made with the project's own API keys. It applies on top of the limits of whoever asked for the work, including runs a schedule started, and never to work outside the project. Pending chat replies, agent turns, voice attempts and automation model calls also hold their admitted usage against the project budget, so concurrent requests see those reservations. A chat message it refuses says the project's limit was reached. Transcribed recordings are not counted toward a project, and a project budget warns no one before it is reached. An automation counts toward the project it runs in. A run that names no project, of an automation installed in several projects, counts toward each of them and must fit each one's budget, as a member's spend counts toward each of their teams; an automation installed in no project counts toward the organization alone. + +Chat turns, voice attempts and automation model calls keep the projects recorded when admitted. Moving the chat or changing an automation’s project installations while work is running does not move its reservation or eventual booking. An attempt admitted without a project stays outside project budgets. diff --git a/docs/en/platform/admin/governance/usage-attribution.md b/docs/en/platform/admin/governance/usage-attribution.md index a226bcab94..ffc7e17641 100644 --- a/docs/en/platform/admin/governance/usage-attribution.md +++ b/docs/en/platform/admin/governance/usage-attribution.md @@ -29,6 +29,8 @@ A retry of an agent run continues the run its starter kicked off, so its usage s Work in a project also counts toward that project, whoever asked for it: the project's chats, with their titles, the answers read aloud, and the assistant's tool calls; the runs of its agents and the agent and `llm` steps of automations run in it, with the images they generate; and the calls made with the project's own API keys. A run that names no project, of an automation installed in several projects, counts toward each of them; an automation installed in no project counts toward the organization alone. A transcription is not counted toward a project. +Chat turns, voice attempts and automation model calls keep the projects recorded when admitted. Moving the chat or changing an automation’s project installations while work is running does not move its reservation or eventual booking. An attempt admitted without a project stays outside project budgets. + An API key an Admin made for a member counts against that member, like the member's own key. A key that belongs to a team, a project, or the organization ([API keys](/platform/admin/api-keys#create-a-key-for-someone-else)) is not a person: what it asks for counts against the key itself. Usage analytics shows it as a row of its own under **Per-user usage**, under the key's name with its team, project, or organization beneath, and never counts it as an active user. A team's key also counts toward its team's usage. ## Which limits apply @@ -38,7 +40,9 @@ An API key an Admin made for a member counts against that member, like the membe - **API-key limits** bind the requests authenticated with that key: the chat messages it sent, its model endpoint calls, and the runs it started. - **Project limits** bind the work in that project, whoever asked for it, including runs a trigger started. -When a limit is reached, Tale refuses the next request before it runs and names the limit. A managed agent turn is refused at its start; a turn already running keeps the allowance it was given. An image the agent asks for during its turn is checked on its own before the image model is called, so a reached limit refuses the image while the turn continues. The image also draws on the allowance of the turn that asked for it. An automation's `llm` step is checked before each model call: a call a limit refuses fails the step with `budget_exceeded`, and its error names the limit; the run fails with it unless the step's `onError` is `continue`. The step holds nothing while its call runs, so runs started at the same moment can pass a nearly reached limit together. [How rules combine](/platform/admin/governance/policies-and-limits#how-rules-combine) covers the case of several rules applying to one person. +When a limit is reached, Tale refuses the next request before it runs and names the limit. A managed agent turn is refused at its start; a turn already running keeps the allowance it was given. An image the agent asks for during its turn is checked on its own before the image model is called, so a reached limit refuses the image while the turn continues. The image also draws on the allowance of the turn that asked for it. An automation's `llm` step is checked before each model call: a call a limit refuses fails the step with `budget_exceeded`, and its error names the limit; the run fails with it unless the step's `onError` is `continue`. The step reserves its estimated prompt and permitted output at the catalog price, plus one request, until settlement. Concurrent calls therefore see each other’s reservations. If the provider’s outcome is unknown, Tale books the saved estimate once instead of silently freeing it; a retry is a new admission. [How rules combine](/platform/admin/governance/policies-and-limits#how-rules-combine) covers the case of several rules applying to one person. + +Voice output holds its estimated cost and one request while pending. A reserved attempt that fails or has an unknown outcome records that estimate once, including failures before the provider call; this is conservative accounting, not confirmation of a charge. A retry includes the earlier estimate when checking the remaining budget. ## Three situations worth knowing diff --git a/docs/en/platform/automations/concepts.md b/docs/en/platform/automations/concepts.md index c139c1df64..452acb5930 100644 --- a/docs/en/platform/automations/concepts.md +++ b/docs/en/platform/automations/concepts.md @@ -68,7 +68,7 @@ Four types are built in, and every connector action and platform native — know **`transform`** runs pure JavaScript to reshape data. It has no network and no imports: the body reads the node's resolved `input` and must return a value. -**`llm`** calls a language model with a templated prompt. `model` is required and always explicit — an automation never picks one on your behalf (the chat composer's Auto is a chat-only affordance). The output is `{text}`, or the schema-shaped object when the node declares an `outputSchema`. Each live call is usage of the run: it is checked against the [budget limits](/platform/admin/governance/policies-and-limits) before it is made, and a call a limit refuses fails the node with `budget_exceeded`, which halts the run unless its `onError` is `continue`. +**`llm`** calls a language model with a templated prompt. `model` is required and always explicit — an automation never picks one on your behalf (the chat composer's Auto is a chat-only affordance). The output is `{text}`, or the schema-shaped object when the node declares an `outputSchema`. Each live call is usage of the run: it is checked against the [budget limits](/platform/admin/governance/policies-and-limits) before it is made, and a call a limit refuses fails the node with `budget_exceeded`, which halts the run unless its `onError` is `continue`. Before calling the provider, each attempt reserves the estimated prompt cost and the maximum reply allowance in every project admitted for that attempt. The model needs catalog pricing. Reported usage replaces the hold when the call finishes. If a timeout, lost connection or missing usage leaves the cost unknown, the hold remains until the request deadline and is then booked as the reserved estimate; this is an estimate, not a provider bill. Changing project bindings during the call does not move its spend. **`agent`** runs one turn of a coding agent (Claude Code, Codex, and the other agent runtimes) in the sandbox. It reads staged `files`, uses `skills`, brokered `connectors`, granted platform `tools`, and injected `secrets`, and returns `{text, files, status}`; `model` is required. When an admin has turned on [image generation](/platform/admin/governance/content-models#let-agents-generate-images), it can also create images, which come back among its `files`. Reach for `llm` when a one-shot completion is enough, and for `agent` only when the step needs tools, files, or several turns — a live agent node runs as an asynchronous turn, so it sits at the top level rather than inside a `subautomation` and does not iterate with `forEach`. diff --git a/docs/en/self-hosted/operate/upgrades.md b/docs/en/self-hosted/operate/upgrades.md index b84c632782..394a1961da 100644 --- a/docs/en/self-hosted/operate/upgrades.md +++ b/docs/en/self-hosted/operate/upgrades.md @@ -63,8 +63,6 @@ Both colours mount the deployment's `static-assets` volume. Before a web replica An open tab normally keeps working across the handover. If a required part is no longer available, Tale waits until its API and database answer, then reloads once. If the part still cannot load, it shows **A new version is available** with a **Reload** action instead of repeating the reload. During an outage, the connection notice stays visible. Failed reads refresh when connectivity returns; failed writes are not submitted again automatically. -Once the services are updated, the CLI removes Tale's images of versions older than both the new version and the recorded rollback target, so the host keeps two releases of images rather than every release it ever ran. It never forces a removal: an image a container still uses, such as a service left running on an older version or a sandbox session that started before the deploy, stays until a later deploy finds it free. Images loaded ahead for a later version stay as well. - If the new group does not become healthy within `HEALTH_CHECK_TIMEOUT`, the deploy does not complete the flip. Inspect the recorded deployment state and logs before retrying. An interrupted rollout can leave both groups or pending handover state; use the CLI's recovery output rather than deleting containers or state files by hand. ## Check migrations and the user outcome diff --git a/docs/fr/platform/admin/governance/data-subject-requests.md b/docs/fr/platform/admin/governance/data-subject-requests.md index 062af1cc6c..abadeb5e41 100644 --- a/docs/fr/platform/admin/governance/data-subject-requests.md +++ b/docs/fr/platform/admin/governance/data-subject-requests.md @@ -20,6 +20,8 @@ En tant qu’admin ou propriétaire, utilise **Paramètres > Gouvernance > Perso L’effacement supprime définitivement les données couvertes ; il ne les déplace pas vers la corbeille. Le reçu indique les catégories et les nombres concernés : chats, documents et imports, préférences, retours, notifications, usage et nettoyage des identifiants personnels dans l’audit. L’effacement supprime aussi les espaces de travail de sandbox propres aux [exécutions d’agent que la personne a démarrées](/fr/platform/projects/tasks#executions-demarrees-par-un-membre), même si du travail s’y exécute encore ; le reçu les compte sous **Espaces de travail de sandbox**. Un espace de travail n’est compté qu’une fois ses fichiers supprimés par le service de sandbox, ce qui peut prendre un moment pour un grand espace. D’ici là, ou tant que leur suppression échoue, le reçu indique **Partiel** et cite `sandboxWorkspaces` parmi les passes échouées ; choisis plus tard **Réessayer**, et l’effacement se termine dès que les fichiers ont disparu. Sous Kubernetes, un espace est compté une fois son volume remis au provisionneur de stockage du cluster ; avec une StorageClass dont la `reclaimPolicy` est `Retain`, les fichiers du volume restent jusqu’à ce qu’un opérateur supprime le volume, même si le reçu compte l’espace. Un service de sandbox ou un appareil qui n’est pas encore passé à cette version ne peut pas confirmer la suppression ; le reçu reste alors **Partiel** jusqu’à sa mise à jour. +La catégorie **Requêtes aux modèles** couvre les requêtes à l’API des modèles et les appels directs aux modèles dans les automatisations. Les requêtes déjà comptabilisées sont supprimées. Une requête encore en cours conserve les données nécessaires à sa comptabilisation, avec un pseudonyme à la place de l’identité de la personne. L’usage reçu plus tard est enregistré sous ce pseudonyme. Si la suppression de l’exécution d’automatisation ou de l’identité échoue, le reçu reste **Partiel** et le nettoyage des données d’usage qui en dépend attend une nouvelle tentative. + Les tâches qui désignent la personne comme **Relecteur** perdent cette désignation. Une demande de revue qui l’attend encore passe à la première personne autorisée parmi celle qui a créé la tâche, puis celle qui a créé le projet. Cette personne reçoit une notification. Pour une tâche archivée, la demande passe sans notification. Les décisions de revue que la personne a déjà prises restent enregistrées sans son nom. ## Vérifier la règle avant le dépôt @@ -46,6 +48,8 @@ Seul le propriétaire peut modifier cette règle. Les protections renforcées s Un reçu ouvert peut empêcher un second dépôt pour la même personne. Reprends ce reçu au lieu de multiplier les demandes. Une demande bloquée dès le dépôt doit à nouveau respecter la règle actuelle d’approbation et d’attente lors d’un nouvel essai. Un reçu en attente d’approbation conserve l’exigence d’approbation fixée à son dépôt : désactiver la double approbation ensuite ne le libère pas. +Les exécutions d’automatisation suspendues lors d’une mise à niveau sont conservées tant que leurs actions externes antérieures restent non vérifiées. L’effacement supprime les autres exécutions admissibles de la personne et compte séparément celles qui ont été effacées et celles qui ont été conservées. Le reçu reste partiel. Ces blocages d’exécution sont distincts des conservations légales et aucune action ne permet actuellement de les lever. Une demande d’arrêt ou une nouvelle tentative d’effacement ne les lève pas. Une organisation contenant ces blocages ne peut pas non plus être supprimée. + ## Gérer l’échéance La liste montre le délai suivi et les éventuels retards. Utilise **Prolonger le délai** pour une prolongation justifiée tant que l’action est disponible. L’application autorise une prolongation avant l’expiration du délai initial et enregistre le motif ainsi que l’admin. diff --git a/docs/fr/platform/admin/governance/policies-and-limits.md b/docs/fr/platform/admin/governance/policies-and-limits.md index 9a2477f3c0..300ed7762e 100644 --- a/docs/fr/platform/admin/governance/policies-and-limits.md +++ b/docs/fr/platform/admin/governance/policies-and-limits.md @@ -25,11 +25,17 @@ Une règle reste dans le tableau même quand sa clé API ne fonctionne plus. **C Les budgets concernent les nouveaux travaux facturables, dont le chat, la sortie vocale, les exécutions d’agents gérés, les étapes `llm` des automatisations, les images que créent les agents et les appels aux endpoints de modèles. Tale vérifie chaque requête de chat avant son exécution — un message envoyé, une réponse régénérée ou modifiée, les deux côtés d’une comparaison de modèles, un message en attente d’une pièce jointe et un envoi par l’API REST — et la refuse dès qu’un plafond applicable est atteint, en indiquant ce plafond et le moment de sa réinitialisation. Les réponses en cours de rédaction réservent ce qu’elles peuvent dépenser, afin que des requêtes envoyées au même moment ne franchissent pas ensemble un plafond presque atteint. La demande d’image d’un agent est vérifiée de la même façon avant l’appel au modèle d’images : pendant que ses images sont créées, elle réserve un coût estimé, et la vérification compte aussi ce que l’exécution de l’agent peut encore dépenser pour son modèle. Chaque image compte pour une requête. La génération d’images a besoin de limites de coût ou de requêtes, car son usage ne se mesure pas en tokens de texte. Une limite de tokens compte les tokens d’entrée et de sortie, et l’entrée comprend la partie d’un prompt qu’un fournisseur a lue dans son cache ou y a écrite. Cette partie est facturée autrement que le reste de l’entrée : un agent qui réutilise un long prompt peut donc atteindre une limite de tokens alors que son coût reste faible. Examine les alertes dans l’[analyse de l’usage](/fr/platform/admin/governance/usage-analytics). +La sortie vocale réserve son coût estimé et une requête tant que la tentative est en cours. L’étape `llm` d’une automatisation réserve l’entrée estimée et la sortie autorisée au tarif du catalogue, ainsi qu’une requête. Ces réservations partagent les plafonds applicables avec le chat et les agents gérés. Ce sont des estimations, pas une garantie du montant finalement facturé par le fournisseur. + +Si une tentative vocale déjà réservée échoue ou si son résultat reste inconnu, Tale comptabilise une seule fois l’estimation enregistrée et une requête, même si l’échec précède l’appel au fournisseur. Un appel direct de modèle d’automatisation dont le résultat est inconnu est lui aussi comptabilisé selon l’estimation réservée. Cette comptabilisation prudente ne confirme pas une facturation par le fournisseur. Une nouvelle tentative nécessite une nouvelle réservation et doit tenir dans le budget en comptant l’estimation précédente. + ## Comprendre les plafonds applicables Pour chaque dimension, la limite personnelle vient de la règle la plus précise qui la définit : personne, équipe, rôle, puis valeur par défaut. Si une personne appartient à plusieurs équipes dotées d’une règle, le plafond le plus strict s’applique à elle. Les plafonds de l’organisation s’ajoutent. Un budget d’équipe plafonne aussi l’usage cumulé des membres actuels de l’équipe, même si un membre a une règle personnelle plus précise : l’usage d’un nouveau membre sur la période en cours compte aussitôt, et celui d’un membre parti ne compte plus. Les limites de clé API plafonnent séparément les requêtes authentifiées par cette clé, dont l’usage est imputé à la clé, pas les autres actions dans l’interface. La clé propre d’une équipe, d’un projet ou de l’organisation n’est pas une personne : aucune règle de personne, de rôle ou par défaut ne s’applique à elle. Les limites de l’organisation et ses règles de clé API s’appliquent, la clé d’une équipe compte pour le budget de son équipe, qui la plafonne, et la clé d’un projet de même pour le budget de son projet. -Un budget de projet plafonne tout ce qui est dépensé dans un projet, quelle que soit la personne qui dépense : les chats du projet, avec leurs titres, les réponses lues à voix haute et les appels d’outils de l’assistant ; les exécutions de ses agents et les étapes d’agent et `llm` des automatisations qui y tournent, avec les images qu’elles créent ; et les appels faits avec les propres clés API du projet. Il s’ajoute aux limites de la personne qui a demandé le travail, y compris pour les exécutions lancées par une planification, et ne s’applique jamais au travail hors du projet. Les réponses de chat et les tours d’agent encore en cours dans le projet réservent aussi sur son budget ce qu’ils peuvent encore dépenser, pour que des requêtes envoyées en même temps ne franchissent pas ensemble un budget de projet presque atteint. Quand il refuse un message de chat, Tale indique que la limite du projet est atteinte. Les enregistrements transcrits ne comptent pas pour un projet, et un budget de projet n’avertit personne avant d’être atteint. Une automatisation compte pour le projet dans lequel elle tourne. Une exécution qui ne nomme aucun projet, d’une automatisation installée dans plusieurs projets, compte pour chacun d’eux et doit tenir dans le budget de chacun, comme l’usage d’un membre compte pour chacune de ses équipes ; une automatisation installée dans aucun projet ne compte que pour l’organisation. +Un budget de projet plafonne tout ce qui est dépensé dans un projet, quelle que soit la personne qui dépense : les chats du projet, avec leurs titres, les réponses lues à voix haute et les appels d’outils de l’assistant ; les exécutions de ses agents et les étapes d’agent et `llm` des automatisations qui y tournent, avec les images qu’elles créent ; et les appels faits avec les propres clés API du projet. Il s’ajoute aux limites de la personne qui a demandé le travail, y compris pour les exécutions lancées par une planification, et ne s’applique jamais au travail hors du projet. Les réponses de chat, les tours d’agent, les tentatives vocales et les appels de modèles d’automatisation en cours réservent aussi leur usage admis sur le budget du projet, afin que les requêtes simultanées tiennent compte de ces réservations. Quand il refuse un message de chat, Tale indique que la limite du projet est atteinte. Les enregistrements transcrits ne comptent pas pour un projet, et un budget de projet n’avertit personne avant d’être atteint. Une automatisation compte pour le projet dans lequel elle tourne. Une exécution qui ne nomme aucun projet, d’une automatisation installée dans plusieurs projets, compte pour chacun d’eux et doit tenir dans le budget de chacun, comme l’usage d’un membre compte pour chacune de ses équipes ; une automatisation installée dans aucun projet ne compte que pour l’organisation. + +Les tours de chat, les tentatives vocales et les appels de modèles d’automatisation conservent les projets enregistrés lors de leur admission. Déplacer le chat ou modifier les installations d’une automatisation dans des projets pendant son exécution ne déplace ni sa réservation ni son usage comptabilisé ensuite. Une tentative admise sans projet reste hors des budgets de projet. diff --git a/docs/fr/platform/admin/governance/usage-attribution.md b/docs/fr/platform/admin/governance/usage-attribution.md index 8412b08eb9..c67107fb6e 100644 --- a/docs/fr/platform/admin/governance/usage-attribution.md +++ b/docs/fr/platform/admin/governance/usage-attribution.md @@ -29,6 +29,8 @@ Une nouvelle tentative d’une exécution d’agent poursuit l’exécution lanc Le travail dans un projet compte aussi pour ce projet, quelle que soit la personne qui l’a demandé : les chats du projet, avec leurs titres, les réponses lues à voix haute et les appels d’outils de l’assistant ; les exécutions de ses agents et les étapes d’agent et `llm` des automatisations qui y tournent, avec les images qu’elles créent ; et les appels faits avec les propres clés API du projet. Une exécution qui ne nomme aucun projet, d’une automatisation installée dans plusieurs projets, compte pour chacun d’eux ; une automatisation installée dans aucun projet ne compte que pour l’organisation. Une transcription ne compte pas pour un projet. +Les tours de chat, les tentatives vocales et les appels de modèles d’automatisation conservent les projets enregistrés lors de leur admission. Déplacer le chat ou modifier les installations d’une automatisation dans des projets pendant son exécution ne déplace ni sa réservation ni son usage comptabilisé ensuite. Une tentative admise sans projet reste hors des budgets de projet. + Une clé API qu’un admin a créée pour un membre compte pour ce membre, comme sa propre clé. Une clé qui appartient à une équipe, à un projet ou à l’organisation ([Clés API](/fr/platform/admin/api-keys#create-a-key-for-someone-else)) n’est pas une personne : ce qu’elle demande compte pour la clé elle-même. L’analyse de l’usage la présente sur sa propre ligne sous **Utilisation par utilisateur**, sous le nom de la clé avec son équipe, son projet ou l’organisation en dessous, et ne la compte jamais comme utilisateur actif. La clé d’une équipe compte aussi dans l’usage de son équipe. ## Quelles limites s’appliquent @@ -38,7 +40,9 @@ Une clé API qu’un admin a créée pour un membre compte pour ce membre, comme - **Les limites de clé API** s’appliquent aux requêtes authentifiées par cette clé : les messages de chat qu’elle a envoyés, ses appels aux endpoints de modèles et les exécutions qu’elle a lancées. - **Les limites de projet** s’appliquent au travail dans ce projet, quelle que soit la personne qui l’a demandé, y compris aux exécutions lancées par un déclencheur. -Quand une limite est atteinte, Tale refuse la requête suivante avant de l’exécuter et nomme la limite. Un tour d’agent géré est refusé à son démarrage ; un tour déjà en cours conserve l’enveloppe qui lui a été accordée. Une image que l’agent demande pendant son tour est vérifiée à part, avant l’appel au modèle d’images : si une limite est atteinte, Tale refuse l’image et le tour continue. L’image puise aussi dans l’enveloppe du tour qui l’a demandée. L’étape `llm` d’une automatisation est vérifiée avant chaque appel de modèle : si une limite refuse l’appel, l’étape échoue avec `budget_exceeded` et son erreur nomme la limite ; l’exécution échoue avec elle, sauf si le `onError` de l’étape vaut `continue`. L’étape ne réserve rien pendant son appel ; des exécutions lancées au même moment peuvent donc franchir ensemble une limite presque atteinte. [Comment les règles se combinent](/fr/platform/admin/governance/policies-and-limits#how-rules-combine) traite le cas où plusieurs règles visent la même personne. +Quand une limite est atteinte, Tale refuse la requête suivante avant de l’exécuter et nomme la limite. Un tour d’agent géré est refusé à son démarrage ; un tour déjà en cours conserve l’enveloppe qui lui a été accordée. Une image que l’agent demande pendant son tour est vérifiée à part, avant l’appel au modèle d’images : si une limite est atteinte, Tale refuse l’image et le tour continue. L’image puise aussi dans l’enveloppe du tour qui l’a demandée. L’étape `llm` d’une automatisation est vérifiée avant chaque appel de modèle : si une limite refuse l’appel, l’étape échoue avec `budget_exceeded` et son erreur nomme la limite ; l’exécution échoue avec elle, sauf si le `onError` de l’étape vaut `continue`. L’étape réserve l’entrée estimée et la sortie autorisée au tarif du catalogue, ainsi qu’une requête, jusqu’à la comptabilisation. Les appels simultanés tiennent donc compte de leurs réservations respectives. Si le résultat du fournisseur reste inconnu, Tale comptabilise une seule fois l’estimation enregistrée au lieu de la libérer silencieusement ; une nouvelle tentative passe par une nouvelle admission. [Comment les règles se combinent](/fr/platform/admin/governance/policies-and-limits#how-rules-combine) traite le cas où plusieurs règles visent la même personne. + +La sortie vocale réserve son coût estimé et une requête tant que la tentative est en cours. Une tentative déjà réservée qui échoue ou dont le résultat reste inconnu est comptabilisée une seule fois selon cette estimation, y compris si l’échec précède l’appel au fournisseur. Cette comptabilisation prudente ne confirme pas une facturation. Une nouvelle tentative tient compte de l’estimation précédente lors de la vérification du budget restant. ## Trois situations à connaître diff --git a/docs/fr/platform/automations/concepts.md b/docs/fr/platform/automations/concepts.md index 3a6a224564..151b6fcd4b 100644 --- a/docs/fr/platform/automations/concepts.md +++ b/docs/fr/platform/automations/concepts.md @@ -68,7 +68,7 @@ Quatre types sont intégrés, et chaque action de connector comme chaque capacit **`transform`** exécute du JavaScript pur pour remettre des données en forme. Sans réseau ni imports : le corps lit l’`input` résolue du nœud et doit retourner une valeur. -**`llm`** appelle un modèle de langage avec un prompt en template. `model` est obligatoire et toujours explicite — une automatisation n’en choisit jamais un à ta place (l’Auto du composer est une affaire de chat, et de chat seulement). La sortie est `{text}`, ou l’objet à la forme du schéma quand le nœud déclare un `outputSchema`. Chaque appel d’une exécution réelle est un usage de l’exécution : il est vérifié par rapport aux [limites de budget](/fr/platform/admin/governance/policies-and-limits) avant d’être fait, et un appel refusé par une limite fait échouer le nœud avec `budget_exceeded`, ce qui arrête l’exécution, sauf si son `onError` vaut `continue`. +**`llm`** appelle un modèle de langage avec un prompt en template. `model` est obligatoire et toujours explicite — une automatisation n’en choisit jamais un à ta place (l’Auto du composer est une affaire de chat, et de chat seulement). La sortie est `{text}`, ou l’objet à la forme du schéma quand le nœud déclare un `outputSchema`. Chaque appel d’une exécution réelle est un usage de l’exécution : il est vérifié par rapport aux [limites de budget](/fr/platform/admin/governance/policies-and-limits) avant d’être fait, et un appel refusé par une limite fait échouer le nœud avec `budget_exceeded`, ce qui arrête l’exécution, sauf si son `onError` vaut `continue`. Avant l’appel au fournisseur, chaque tentative réserve le coût estimé du prompt et le budget maximal de réponse dans tous les projets retenus pour cette tentative. Le modèle doit disposer de tarifs dans le catalogue. L’usage déclaré remplace la réservation à la fin de l’appel. Si un délai dépassé, une connexion interrompue ou l’absence de données d’usage laisse le coût inconnu, la réservation reste en place jusqu’à l’échéance de la requête, puis son montant estimé est comptabilisé ; il s’agit d’une estimation, pas d’une facture du fournisseur. Modifier les associations aux projets pendant l’appel ne déplace pas sa consommation. **`agent`** exécute un tour d’un agent de code (Claude Code, Codex et les autres environnements d’agent) dans la sandbox. Il lit les `files` mis en place, utilise des `skills`, des `connectors` relayés, des `tools` de plateforme accordés et des `secrets` injectés, et renvoie `{text, files, status}` ; `model` est obligatoire. Si un admin a activé la [génération d’images](/fr/platform/admin/governance/content-models#let-agents-generate-images), il peut aussi créer des images, qui reviennent parmi ses `files`. Prends `llm` quand une complétion unique suffit, et `agent` seulement quand l’étape a besoin d’outils, de fichiers ou de plusieurs tours — un nœud agent en service s’exécute comme un tour asynchrone, il siège donc au niveau supérieur plutôt que dans une `subautomation` et n’itère pas avec `forEach`. diff --git a/docs/fr/self-hosted/operate/upgrades.md b/docs/fr/self-hosted/operate/upgrades.md index 959d5e78ec..58aa876f17 100644 --- a/docs/fr/self-hosted/operate/upgrades.md +++ b/docs/fr/self-hosted/operate/upgrades.md @@ -63,8 +63,6 @@ Les deux couleurs montent le volume `static-assets` du déploiement. Avant qu’ Un onglet ouvert continue normalement à fonctionner pendant la bascule. Si une partie nécessaire n’est plus disponible, Tale attend que son API et sa base de données répondent, puis recharge la page une fois. Si cette partie ne se charge toujours pas, Tale affiche **Une nouvelle version est disponible** avec l’action **Recharger**, sans répéter le rechargement automatique. Pendant une panne, l’avis de connexion reste visible. Les lectures ayant échoué sont actualisées quand la connexion revient ; les écritures ayant échoué ne sont pas renvoyées automatiquement. -Une fois les services mis à jour, la CLI supprime les images Tale des versions antérieures à la fois à la nouvelle version et à la cible de retour arrière enregistrée. L’hôte garde ainsi les images de deux versions plutôt que de chaque version qu’il a exécutée. Elle ne force jamais une suppression : une image qu’un conteneur utilise encore, comme un service laissé en marche sur une version antérieure ou une session sandbox démarrée avant le déploiement, reste jusqu’à ce qu’un déploiement ultérieur la trouve libre. Les images chargées à l’avance pour une version ultérieure restent aussi. - Si le nouveau groupe ne devient pas sain avant `HEALTH_CHECK_TIMEOUT`, la CLI ne termine pas la bascule. Examine l’état enregistré et les journaux avant de réessayer. Un déploiement interrompu peut laisser les deux groupes ou un transfert en attente. Suis les indications de reprise de la CLI plutôt que de supprimer manuellement conteneurs ou fichiers d’état. ## Vérifier les migrations et le résultat utilisateur diff --git a/services/platform/app/features/organization/hooks/use-delete-organization.ts b/services/platform/app/features/organization/hooks/use-delete-organization.ts index e69137dd18..7e958f712f 100644 --- a/services/platform/app/features/organization/hooks/use-delete-organization.ts +++ b/services/platform/app/features/organization/hooks/use-delete-organization.ts @@ -96,12 +96,14 @@ export function useDeleteOrganization() { const description = code === 'LEGAL_HOLD_ACTIVE' ? tSettings('organization.deleteBlockedByLegalHold') - : code === 'ORG_CONFIRM_NAME_MISMATCH' - ? tSettings('organization.deleteConfirmNameMismatch') - : backendErrorMessage( - err, - err instanceof Error ? err.message : '', - ); + : code === 'ORG_LEGACY_AUTOMATION_HELD' + ? tSettings('organization.deleteBlockedByLegacyAutomation') + : code === 'ORG_CONFIRM_NAME_MISMATCH' + ? tSettings('organization.deleteConfirmNameMismatch') + : backendErrorMessage( + err, + err instanceof Error ? err.message : '', + ); toast({ title: tSettings('organization.deleteFailed'), ...(description !== '' ? { description } : {}), diff --git a/services/platform/app/features/settings/governance/data-subject-requests/request-detail-drawer.test.tsx b/services/platform/app/features/settings/governance/data-subject-requests/request-detail-drawer.test.tsx index 6ee2ee37d3..21405d7603 100644 --- a/services/platform/app/features/settings/governance/data-subject-requests/request-detail-drawer.test.tsx +++ b/services/platform/app/features/settings/governance/data-subject-requests/request-detail-drawer.test.tsx @@ -8,6 +8,9 @@ const state = vi.hoisted(() => ({ userId: 'second-admin', status: 'pending', effectiveAt: undefined as number | undefined, + errorMessage: undefined as string | undefined, + wfExecutionsErased: undefined as number | undefined, + perCategorySnapshot: undefined as Record | undefined, holdBlock: undefined as | { orgHeld: boolean; userCustodianHeld: boolean; active: boolean } | undefined, @@ -55,7 +58,10 @@ vi.mock('./hooks/queries', () => ({ status: state.status, approvalId: 'approval-a', effectiveAt: state.effectiveAt, - errorMessage: state.status === 'blocked' ? 'org_hold' : undefined, + errorMessage: + state.status === 'blocked' ? 'org_hold' : state.errorMessage, + perCategorySnapshot: state.perCategorySnapshot, + wfExecutionsErased: state.wfExecutionsErased, holdBlock: state.holdBlock, targetUserId: 'subject-a', targetUserName: 'Test subject', @@ -83,6 +89,9 @@ beforeEach(() => { state.userId = 'second-admin'; state.status = 'pending'; state.effectiveAt = undefined; + state.errorMessage = undefined; + state.wfExecutionsErased = undefined; + state.perCategorySnapshot = undefined; state.holdBlock = undefined; decide.mockResolvedValue(null); cancel.mockResolvedValue(null); @@ -98,6 +107,30 @@ const show = () => ); describe('DSAR receipt decisions', () => { + it('explains a preserved legacy run without calling it erased or a legal hold', async () => { + state.status = 'partial'; + state.errorMessage = 'legacy_automation_hold'; + state.wfExecutionsErased = 1; + state.perCategorySnapshot = { + automationRuns: { rows: 1, skippedByHold: 2 }, + }; + const { user } = show(); + expect( + screen.getByText('Automation runs erased').parentElement, + ).toHaveTextContent('Automation runs erased1'); + expect( + screen.getByText(/earlier external actions have not been verified/), + ).toBeInTheDocument(); + expect( + screen.queryByText('legacy_automation_hold'), + ).not.toBeInTheDocument(); + await user.click( + screen.getByText('Full breakdown across all data categories'), + ); + expect( + screen.getByText('1 erased · 2 skipped by hold'), + ).toBeInTheDocument(); + }); it.each([ ['Approve request', 'executing'], ['Reject request', 'rejected'], diff --git a/services/platform/app/features/settings/governance/data-subject-requests/request-detail-drawer.tsx b/services/platform/app/features/settings/governance/data-subject-requests/request-detail-drawer.tsx index 86108f4831..e91edc0089 100644 --- a/services/platform/app/features/settings/governance/data-subject-requests/request-detail-drawer.tsx +++ b/services/platform/app/features/settings/governance/data-subject-requests/request-detail-drawer.tsx @@ -13,9 +13,10 @@ import { Text } from '@tale/ui/text'; import { AlertTriangle, Ban, Clock, RefreshCcw, X } from 'lucide-react'; import { useState } from 'react'; +import { ERASURE_LEGACY_AUTOMATION_HOLD } from '@/backend/core/governance/erasure_constants'; +import { foldBreakdownEntries } from '@/backend/core/governance/erasure_counts'; import { useT } from '@/lib/i18n/client'; -import { foldBreakdownEntries } from './breakdown-entries.ts'; import { CancelDialog } from './cancel-dialog'; import { ErasureApprovalActions } from './erasure-approval-actions'; import { ExtendDeadlineDialog } from './extend-deadline-dialog'; @@ -377,7 +378,14 @@ function DrawerBody({ {request.errorMessage && !isBlocked && ( + reason === ERASURE_LEGACY_AUTOMATION_HOLD + ? t('dataSubjectRequests.drawer.legacyAutomationHold') + : reason, + ) + .join('; ')} multiline /> )} diff --git a/services/platform/backend/core/automations/ledger.ts b/services/platform/backend/core/automations/ledger.ts index de39477c36..f20376222e 100644 --- a/services/platform/backend/core/automations/ledger.ts +++ b/services/platform/backend/core/automations/ledger.ts @@ -165,7 +165,7 @@ function failureSentence(error: unknown): string { export async function callThroughLedger( ledger: RunLedger, call: LedgerCall, - make: () => Promise, + make: (attempt: number) => Promise, signal?: AbortSignal, ): Promise { const address: CallAddress = { @@ -209,7 +209,7 @@ export async function callThroughLedger( } let output: unknown; try { - output = await make(); + output = await make(begun.attempt); } catch (error) { if (signal?.aborted === true) throw error; await ledger diff --git a/services/platform/backend/core/automations/llm_budget.ts b/services/platform/backend/core/automations/llm_budget.ts new file mode 100644 index 0000000000..34b137cb55 --- /dev/null +++ b/services/platform/backend/core/automations/llm_budget.ts @@ -0,0 +1,11 @@ +/** A direct call is bounded independently of the worker that owns it. */ +export const AUTOMATION_LLM_OP_KIND = 'automation-llm'; +export const AUTOMATION_LLM_LIFETIME_MS = 180_000; + +/** The durable effect attempt, including nested/repeated node addresses. */ +export interface LlmAttemptAddress { + nodeId: string; + itemIndex: number; + pass: number; + attempt: number; +} diff --git a/services/platform/backend/core/automations/llm_call.test.ts b/services/platform/backend/core/automations/llm_call.test.ts index 3e0908c867..0265112f67 100644 --- a/services/platform/backend/core/automations/llm_call.test.ts +++ b/services/platform/backend/core/automations/llm_call.test.ts @@ -39,13 +39,23 @@ vi.mock('../lib/providers/org_providers', () => ({ })); import { - automationLlmCall, + automationLlmCall as actualAutomationLlmCall, extractJsonValue, resolveServingTarget, schemaViolations, walkLlmServing, } from './llm_call'; +const ATTEMPT = { nodeId: 'model', itemIndex: 0, pass: 0, attempt: 1 }; +const PRICING = { inputCentsPerMillion: 100, outputCentsPerMillion: 200 }; +function automationLlmCall( + ...args: Parameters +) { + const call = actualAutomationLlmCall(...args); + return (request: Parameters[0]) => + call({ attempt: ATTEMPT, ...request }); +} + const ORG = 'org_llm'; const RUN = 'run_llm'; @@ -54,16 +64,16 @@ let credentials: Record; /** What the run's budget check answers. */ let admission: unknown; -const runQuery = vi.fn((ref: unknown, args: { providerSlug: string }) => +const runQuery = vi.fn((_ref: unknown, args: { providerSlug: string }) => + Promise.resolve(credentials[args.providerSlug] ?? null), +); +const runMutation = vi.fn((ref: unknown, _args: unknown) => Promise.resolve( - functionRefName(ref) === 'automations/queries:checkLlmStepBudget' + functionRefName(ref) === 'automations/mutations:reserveLlmStepBudget' ? admission - : (credentials[args.providerSlug] ?? null), + : null, ), ); -const runMutation = vi.fn((_ref: unknown, _args: unknown) => - Promise.resolve(null), -); const ctx = { runQuery, runMutation } as unknown as ActionCtx; /** The bookings the door asked for, by their arguments. */ @@ -80,8 +90,9 @@ const DIRECT = { status: 'active', authMethod: 'api-key' }; beforeEach(() => { vi.clearAllMocks(); + Reflect.deleteProperty(builderModel, 'prepare'); credentials = {}; - admission = { allowed: true }; + admission = { allowed: true, sessionId: 'session', execId: 'exec' }; resolveConnectors.mockResolvedValue([ { name: 'first', catalog: { source: 'static' } }, { name: 'second', catalog: { source: 'static' } }, @@ -158,7 +169,7 @@ describe('automationLlmCall', () => { (connector: { name: string }): Promise> => Promise.resolve( connector.name === 'second' - ? [{ id: 'vendor/small-1', tags: ['chat'] }] + ? [{ id: 'vendor/small-1', tags: ['chat'], pricing: PRICING }] : [], ), ); @@ -197,7 +208,7 @@ describe('automationLlmCall', () => { second: { ...DIRECT, modelAllowlist: ['other/model'] }, }; getProviderCatalog.mockResolvedValue([ - { id: 'vendor/small-1', tags: ['chat'] }, + { id: 'vendor/small-1', tags: ['chat'], pricing: PRICING }, ]); await expect( @@ -216,7 +227,7 @@ describe('automationLlmCall', () => { ]); credentials = { openrouter: DIRECT }; getProviderCatalog.mockResolvedValue([ - { id: 'anthropic/claude-haiku-4.5', tags: ['chat'] }, + { id: 'anthropic/claude-haiku-4.5', tags: ['chat'], pricing: PRICING }, ]); await automationLlmCall( @@ -245,7 +256,7 @@ describe('automationLlmCall', () => { ]); credentials = { anthropic: DIRECT }; getProviderCatalog.mockResolvedValue([ - { id: 'claude-haiku-4-5', tags: ['chat'] }, + { id: 'claude-haiku-4-5', tags: ['chat'], pricing: PRICING }, ]); await automationLlmCall( @@ -279,7 +290,7 @@ describe('automationLlmCall', () => { }, }; getProviderCatalog.mockResolvedValue([ - { id: 'anthropic/claude-haiku-4.5', tags: ['chat'] }, + { id: 'anthropic/claude-haiku-4.5', tags: ['chat'], pricing: PRICING }, ]); await automationLlmCall( @@ -318,7 +329,7 @@ describe('automationLlmCall', () => { it("hands the turn's signal to the model, so a stopping server cuts the request", async () => { credentials = { first: DIRECT }; getProviderCatalog.mockResolvedValue([ - { id: 'vendor/small-1', tags: ['chat'] }, + { id: 'vendor/small-1', tags: ['chat'], pricing: PRICING }, ]); const stop = new AbortController(); @@ -336,14 +347,16 @@ describe('automationLlmCall', () => { it('resolves each model once per door, not once per call', async () => { credentials = { first: DIRECT }; getProviderCatalog.mockResolvedValue([ - { id: 'vendor/small-1', tags: ['chat'] }, + { id: 'vendor/small-1', tags: ['chat'], pricing: PRICING }, ]); const door = automationLlmCall(ctx, ORG, RUN); await door({ model: 'vendor/small-1', prompt: 'one' }); + const initialLookups = resolveConnectors.mock.calls.length; await door({ model: 'vendor/small-1', prompt: 'two' }); - expect(resolveConnectors).toHaveBeenCalledTimes(1); + expect(initialLookups).toBe(2); + expect(resolveConnectors).toHaveBeenCalledTimes(initialLookups); expect(createBuilderModel).toHaveBeenCalledTimes(1); expect(builderModel).toHaveBeenCalledTimes(2); }); @@ -351,7 +364,7 @@ describe('automationLlmCall', () => { it('asks for the schema in the system prompt and returns the parsed data', async () => { credentials = { first: DIRECT }; getProviderCatalog.mockResolvedValue([ - { id: 'vendor/small-1', tags: ['chat'] }, + { id: 'vendor/small-1', tags: ['chat'], pricing: PRICING }, ]); builderModel.mockResolvedValue({ content: '```json\n{"score": 7}\n```' }); const outputSchema = { @@ -381,7 +394,7 @@ describe('automationLlmCall', () => { it('fails the call, naming the problem, when the reply defies the schema', async () => { credentials = { first: DIRECT }; getProviderCatalog.mockResolvedValue([ - { id: 'vendor/small-1', tags: ['chat'] }, + { id: 'vendor/small-1', tags: ['chat'], pricing: PRICING }, ]); const outputSchema = { type: 'object', @@ -406,14 +419,14 @@ describe('automationLlmCall and the run’s budgets', () => { beforeEach(() => { credentials = { first: DIRECT }; getProviderCatalog.mockResolvedValue([ - { id: 'vendor/small-1', tags: ['chat'] }, + { id: 'vendor/small-1', tags: ['chat'], pricing: PRICING }, ]); }); it('books each call’s tokens to its run, priced under the serving connector [GOV-R14]', async () => { builderModel.mockResolvedValue({ content: 'a fine sentence', - usage: { prompt: 120, completion: 30 }, + usage: { prompt: 120, completion: 30, reported: true }, }); await automationLlmCall( @@ -422,18 +435,21 @@ describe('automationLlmCall and the run’s budgets', () => { RUN, )({ model: 'vendor/small-1', prompt: 'Summarize.' }); - expect(runQuery).toHaveBeenCalledWith(expect.anything(), { - organizationId: ORG, - runId: RUN, - }); + expect(runMutation).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + organizationId: ORG, + runId: RUN, + attempt: ATTEMPT, + reserveTokens: expect.any(Number), + }), + ); expect(bookings()).toEqual([ { organizationId: ORG, - runId: RUN, - provider: 'first', - model: 'vendor/small-1', - inputTokens: 120, - outputTokens: 30, + sessionId: 'session', + execId: 'exec', + usage: { inputTokens: 120, outputTokens: 30, cents: 0.018 }, }, ]); }); @@ -475,7 +491,7 @@ describe('automationLlmCall and the run’s budgets', () => { it('books a reply with no text before the step fails on it', async () => { builderModel.mockRejectedValue( - new EmptyReplyError({ prompt: 40, completion: 8000 }), + new EmptyReplyError({ prompt: 40, completion: 8000, reported: true }), ); await expect( @@ -486,14 +502,16 @@ describe('automationLlmCall and the run’s budgets', () => { )({ model: 'vendor/small-1', prompt: 'x' }), ).rejects.toThrow(/no text content/); expect(bookings()).toEqual([ - expect.objectContaining({ inputTokens: 40, outputTokens: 8000 }), + expect.objectContaining({ + usage: expect.objectContaining({ inputTokens: 40, outputTokens: 8000 }), + }), ]); }); it('books a reply that defies the node’s schema — the call was made', async () => { builderModel.mockResolvedValue({ content: 'about a seven', - usage: { prompt: 10, completion: 4 }, + usage: { prompt: 10, completion: 4, reported: true }, }); await expect( @@ -508,30 +526,107 @@ describe('automationLlmCall and the run’s budgets', () => { }), ).rejects.toMatchObject({ code: 'llm_output_invalid' }); expect(bookings()).toEqual([ - expect.objectContaining({ inputTokens: 10, outputTokens: 4 }), + expect.objectContaining({ + usage: expect.objectContaining({ inputTokens: 10, outputTokens: 4 }), + }), ]); }); - it('keeps the reply when its booking fails, and says so', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + it('fails visibly when terminal facts cannot be persisted, preserving the server hold', async () => { builderModel.mockResolvedValue({ - content: 'a fine sentence', - usage: { prompt: 1, completion: 1 }, + content: 'answer', + usage: { prompt: 1, completion: 1, reported: true }, }); - runMutation.mockRejectedValueOnce(new Error('connection reset')); + runMutation + .mockResolvedValueOnce(admission) + .mockRejectedValueOnce(new Error('connection reset')); + await expect( + automationLlmCall( + ctx, + ORG, + RUN, + )({ model: 'vendor/small-1', prompt: 'x' }), + ).rejects.toThrow('connection reset'); + expect(builderModel).toHaveBeenCalledTimes(1); + }); + it.each([ + undefined, + { prompt: 0, completion: 0 }, + { prompt: NaN, completion: 2, reported: true }, + ])( + 'retains unknown provider usage instead of booking zero', + async (usage) => { + builderModel.mockResolvedValue({ content: 'answer', usage }); + await automationLlmCall( + ctx, + ORG, + RUN, + )({ model: 'vendor/small-1', prompt: 'x' }); + expect(bookings()).toEqual([expect.objectContaining({ usage: null })]); + }, + ); + + it('records an unknown outcome before returning a transport failure', async () => { + builderModel.mockRejectedValueOnce(new Error('timeout')); await expect( automationLlmCall( ctx, ORG, RUN, )({ model: 'vendor/small-1', prompt: 'x' }), - ).resolves.toEqual({ text: 'a fine sentence' }); - expect(warn).toHaveBeenCalledWith( - expect.stringContaining(`run ${RUN}: booking an llm call`), - expect.any(Error), - ); - warn.mockRestore(); + ).rejects.toThrow('timeout'); + expect(bookings()).toEqual([expect.objectContaining({ usage: null })]); + }); + + it('resolves credentials before reserving paid work', async () => { + Object.assign(builderModel, { + prepare: vi.fn().mockRejectedValue(new Error('credential absent')), + }); + await expect( + automationLlmCall( + ctx, + ORG, + RUN, + )({ model: 'vendor/small-1', prompt: 'x' }), + ).rejects.toThrow('credential absent'); + expect(runMutation).not.toHaveBeenCalled(); + expect(builderModel).not.toHaveBeenCalled(); + }); + + it('closes a proven pre-dispatch cancellation at zero without calling the provider', async () => { + const stop = new AbortController(); + runMutation.mockImplementationOnce(async () => { + stop.abort(); + return admission; + }); + await expect( + automationLlmCall(ctx, ORG, RUN, { signal: stop.signal })({ + model: 'vendor/small-1', + prompt: 'x', + }), + ).rejects.toThrow(); + expect(builderModel).not.toHaveBeenCalled(); + expect(bookings()).toEqual([ + expect.objectContaining({ + usage: { inputTokens: 0, outputTokens: 0, cents: 0 }, + }), + ]); + }); + + it('refuses absent catalog prices before reserving or calling', async () => { + getProviderCatalog.mockResolvedValue([ + { id: 'vendor/small-1', tags: ['chat'] }, + ]); + await expect( + automationLlmCall( + ctx, + ORG, + RUN, + )({ model: 'vendor/small-1', prompt: 'x' }), + ).rejects.toThrow('catalog pricing'); + expect(runMutation).not.toHaveBeenCalled(); + expect(builderModel).not.toHaveBeenCalled(); }); it('fails loudly on a budget answer it cannot read', async () => { @@ -554,7 +649,7 @@ describe('resolveServingTarget', () => { it('walks connectors in order and serves from the first match', async () => { credentials = { first: DIRECT, second: DIRECT }; getProviderCatalog.mockResolvedValue([ - { id: 'vendor/shared', tags: ['chat'] }, + { id: 'vendor/shared', tags: ['chat'], pricing: PRICING }, ]); await expect( @@ -569,7 +664,7 @@ describe('walkLlmServing', () => { it('answers the serving connector, or no target with the catalogs it could not read', async () => { credentials = { first: DIRECT, second: DIRECT }; getProviderCatalog.mockResolvedValue([ - { id: 'vendor/shared', tags: ['chat'] }, + { id: 'vendor/shared', tags: ['chat'], pricing: PRICING }, ]); await expect( walkLlmServing(ctx, ORG, 'vendor/shared'), diff --git a/services/platform/backend/core/automations/llm_call.ts b/services/platform/backend/core/automations/llm_call.ts index 27d43ec1a0..331517c732 100644 --- a/services/platform/backend/core/automations/llm_call.ts +++ b/services/platform/backend/core/automations/llm_call.ts @@ -20,8 +20,13 @@ * one wire for thread titles and llm nodes. */ -import type { HarnessGatewayWire } from '@tale/shared/schemas/providers'; +import type { + HarnessGatewayWire, + ModelCatalogEntry, +} from '@tale/shared/schemas/providers'; +import { estimateCostCents } from '../../../lib/chat/turn'; +import { estimateTokens } from '../../../lib/chat/types'; import { compileSchema } from '../../../lib/engine/core/validate/schema'; import { EmptyReplyError } from '../automations_builder/chat_wire'; import { @@ -37,13 +42,19 @@ import { walkDirectServing, type DirectServingWalk, } from '../lib/providers/agent_serving'; +import { getProviderCatalog } from '../lib/providers/catalog_fetch'; import { resolveProvidersForOrgId } from '../lib/providers/org_providers'; import { NodeFailure } from './failure'; +import { + AUTOMATION_LLM_LIFETIME_MS, + type LlmAttemptAddress, +} from './llm_budget'; /** What one llm node asks for — the engine seam's shape, minus nothing. */ export interface AutomationLlmRequest { model: string; prompt: string; + attempt?: LlmAttemptAddress; system?: string; outputSchema?: Record; } @@ -203,19 +214,35 @@ function schemaInstruction(schema: Record): string { } /** The budget check's answer, read off the untyped ctx seam. */ -type LlmStepAdmission = { allowed: true } | { allowed: false; reason: string }; +type LlmStepAdmission = + | { allowed: true; sessionId: string; execId: string } + | { allowed: false; reason: string }; function readLlmStepAdmission(value: unknown): LlmStepAdmission { if (typeof value === 'object' && value !== null) { // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- narrowed field by field below - const record = value as { allowed?: unknown; reason?: unknown }; - if (record.allowed === true) return { allowed: true }; + const record = value as { + allowed?: unknown; + reason?: unknown; + sessionId?: unknown; + execId?: unknown; + }; + if ( + record.allowed === true && + typeof record.sessionId === 'string' && + typeof record.execId === 'string' + ) + return { + allowed: true, + sessionId: record.sessionId, + execId: record.execId, + }; if (record.allowed === false && typeof record.reason === 'string') { return { allowed: false, reason: record.reason }; } } throw new Error( - 'checkLlmStepBudget answered with an unexpected shape — the llm call cannot be admitted', + 'reserveLlmStepBudget answered with an unexpected shape — the llm call cannot be admitted', ); } @@ -224,6 +251,7 @@ function readLlmStepAdmission(value: unknown): LlmStepAdmission { interface ServedModel { target: BuilderModelTarget; call: BuilderModel; + pricing: NonNullable; } /** @@ -252,57 +280,44 @@ export function automationLlmCall( const existing = models.get(modelId); if (existing) return existing; const created = resolveServingTarget(ctx, organizationId, modelId).then( - (target) => ({ - target, - call: createBuilderModel(ctx, { - organizationId, + async (target) => { + const connector = ( + await resolveProvidersForOrgId(ctx, organizationId) + ).find((entry) => entry.name === target.providerSlug); + const pricing = + connector === undefined + ? undefined + : (await getProviderCatalog(connector)).find( + (entry) => entry.id === target.modelId, + )?.pricing; + if (pricing === undefined) + throw new Error( + 'The LLM model needs catalog pricing before its budget can be reserved', + ); + return { target, - maxTokens: LLM_NODE_MAX_TOKENS, - ...(options.signal !== undefined && { signal: options.signal }), - }), - }), + pricing, + call: createBuilderModel(ctx, { + organizationId, + target, + maxTokens: LLM_NODE_MAX_TOKENS, + ...(options.signal !== undefined && { signal: options.signal }), + }), + }; + }, ); models.set(modelId, created); return created; }; - const book = async ( - target: BuilderModelTarget, - usage: { prompt: number; completion: number }, - ): Promise => { - try { - await ctx.runMutation(internal.automations.mutations.recordLlmStepUsage, { - organizationId, - runId, - provider: target.providerSlug, - model: target.modelId, - inputTokens: usage.prompt, - outputTokens: usage.completion, - }); - } catch (error) { - // The step has its reply, and the spend happened either way: a - // ledger write that failed must not fail the run. - console.warn( - `[automations] run ${runId}: booking an llm call to ${target.providerSlug}/${target.modelId} failed:`, - error, - ); - } - }; - return async (request) => { + if (request.attempt === undefined) + throw new Error('An LLM call requires its durable effect attempt'); + options.signal?.throwIfAborted(); const model = await modelFor(request.model); - const admission = readLlmStepAdmission( - await ctx.runQuery(internal.automations.queries.checkLlmStepBudget, { - organizationId, - runId, - }), - ); - if (!admission.allowed) { - throw new NodeFailure( - 'budget_exceeded', - `the llm call was refused: ${admission.reason}`, - 'wait until the limit resets, or ask an administrator to raise it', - ); - } + // Missing credentials/endpoints are a proven pre-dispatch failure: + // resolve them before holding anything that could later be estimated. + await model.call.prepare?.(); + options.signal?.throwIfAborted(); const system = [ ...(request.system !== undefined && request.system !== '' ? [request.system] @@ -315,22 +330,85 @@ export function automationLlmCall( ...(system === '' ? [] : [{ role: 'system', content: system } as const]), { role: 'user', content: request.prompt } as const, ]; + // Include schema/system instructions and framing in the same prompt estimate. + const inputReserve = messages.reduce( + (total, message) => total + estimateTokens(message.content) + 4, + 3, + ); + // Start the request clock before admission, so recovery's server-side + // started_at deadline never precedes this call's cancellation deadline. + const deadline = AbortSignal.timeout(AUTOMATION_LLM_LIFETIME_MS); + const admission = readLlmStepAdmission( + await ctx.runMutation( + internal.automations.mutations.reserveLlmStepBudget, + { + organizationId, + runId, + attempt: request.attempt, + provider: model.target.providerSlug, + model: model.target.modelId, + reserveCents: estimateCostCents( + inputReserve, + LLM_NODE_MAX_TOKENS, + model.pricing, + ), + reserveTokens: inputReserve + LLM_NODE_MAX_TOKENS, + }, + ), + ); + if (!admission.allowed) + throw new NodeFailure( + 'budget_exceeded', + `the llm call was refused: ${admission.reason}`, + 'wait until the limit resets, or ask an administrator to raise it', + ); + const book = async ( + usage: Awaited>['usage'], + ): Promise => { + const reported = + usage?.reported === true && + Number.isSafeInteger(usage.prompt) && + usage.prompt >= 0 && + Number.isSafeInteger(usage.completion) && + usage.completion >= 0; + await ctx.runMutation(internal.automations.mutations.recordLlmStepUsage, { + organizationId, + sessionId: admission.sessionId, + execId: admission.execId, + usage: reported + ? { + inputTokens: usage.prompt, + outputTokens: usage.completion, + cents: estimateCostCents( + usage.prompt, + usage.completion, + model.pricing, + ), + } + : null, + }); + }; + if (options.signal?.aborted || deadline.aborted) { + // Local proof of no dispatch: close this hold at known zero rather + // than treating a cancellation before the call as unknown spend. + await book({ prompt: 0, completion: 0, reported: true }); + options.signal?.throwIfAborted(); + deadline.throwIfAborted(); + } let reply: Awaited>; try { reply = await model.call({ messages, temperature: LLM_NODE_TEMPERATURE, turn: 1, + signal: deadline, }); } catch (error) { - // A reply with no text — a model that spent its budget reasoning — - // was still billed. - if (error instanceof EmptyReplyError) { - await book(model.target, error.usage); - } + await book(error instanceof EmptyReplyError ? error.usage : undefined); throw error; } - if (reply.usage !== undefined) await book(model.target, reply.usage); + // Persist before parsing/schema validation: unusable output was still paid. + await book(reply.usage); if (request.outputSchema === undefined) { return { text: reply.content }; } diff --git a/services/platform/backend/core/automations/stepper.ledger.test.ts b/services/platform/backend/core/automations/stepper.ledger.test.ts index 46d4950912..36b3360846 100644 --- a/services/platform/backend/core/automations/stepper.ledger.test.ts +++ b/services/platform/backend/core/automations/stepper.ledger.test.ts @@ -411,6 +411,12 @@ describe('the stepper and the effect ledger', () => { }, }); expect(model.calls).toHaveLength(1); + expect(model.calls[0]?.attempt).toEqual({ + nodeId: 'summary', + itemIndex: 0, + pass: 0, + attempt: 2, + }); expect(started.finished[0]?.output).toEqual({ text: 'a fresh summary' }); const finished = fakeStepperWorld({ diff --git a/services/platform/backend/core/automations/stepper.ts b/services/platform/backend/core/automations/stepper.ts index fd3dfd4969..738d593b73 100644 --- a/services/platform/backend/core/automations/stepper.ts +++ b/services/platform/backend/core/automations/stepper.ts @@ -543,8 +543,14 @@ async function runNodeBody(args: BodyArgs): Promise { input: llmInput, recallable: true, }, - async () => { + async (attempt) => { const reply = await run.llm({ + attempt: { + nodeId: args.path, + itemIndex: args.itemIndex, + pass: args.pass, + attempt, + }, model, prompt, ...(system !== undefined && { system }), diff --git a/services/platform/backend/core/automations_builder/chat_wire.test.ts b/services/platform/backend/core/automations_builder/chat_wire.test.ts index f67c8716ef..611659222a 100644 --- a/services/platform/backend/core/automations_builder/chat_wire.test.ts +++ b/services/platform/backend/core/automations_builder/chat_wire.test.ts @@ -49,7 +49,7 @@ describe('the OpenAI-compatible shape', () => { }), ).toEqual({ content: 'yaml action', - usage: { prompt: 120, completion: 30 }, + usage: { prompt: 120, completion: 30, reported: true }, }); }); }); @@ -87,7 +87,7 @@ describe('the Anthropic shape', () => { ).toEqual({ content: 'CAUSE: the node had no code.\n```yaml\nmethod: run_automation\n```', - usage: { prompt: 900, completion: 210 }, + usage: { prompt: 900, completion: 210, reported: true }, }); }); }); @@ -980,3 +980,37 @@ describe('the Responses API shape', () => { } }); }); + +describe('reported usage validity', () => { + it.each([ + undefined, + {}, + { prompt_tokens: -1, completion_tokens: 2 }, + { prompt_tokens: NaN, completion_tokens: 2 }, + { prompt_tokens: 1.2, completion_tokens: 2 }, + ])( + 'keeps missing or invalid counts distinguishable from reported zero', + (usage) => { + expect( + parseChatReply('openai', { + choices: [{ message: { content: 'answer' } }], + usage, + }).usage.reported, + ).toBe(false); + }, + ); + it('recognizes explicit reported zero on both direct wires', () => { + expect( + parseChatReply('openai', { + choices: [{ message: { content: 'answer' } }], + usage: { prompt_tokens: 0, completion_tokens: 0 }, + }).usage.reported, + ).toBe(true); + expect( + parseChatReply('anthropic', { + content: [{ text: 'answer' }], + usage: { input_tokens: 0, output_tokens: 0 }, + }).usage.reported, + ).toBe(true); + }); +}); diff --git a/services/platform/backend/core/automations_builder/chat_wire.ts b/services/platform/backend/core/automations_builder/chat_wire.ts index b682b8399c..3336981fc3 100644 --- a/services/platform/backend/core/automations_builder/chat_wire.ts +++ b/services/platform/backend/core/automations_builder/chat_wire.ts @@ -36,7 +36,7 @@ export interface ChatWireRequest { export interface ChatWireReply { content: string; - usage: { prompt: number; completion: number }; + usage: { prompt: number; completion: number; reported?: boolean }; } /** @@ -609,6 +609,17 @@ function tokenCount(usage: unknown, key: string): number { return typeof value === 'number' ? value : 0; } +/** Missing/invalid counts must remain distinguishable from reported zero. */ +function usageReported(usage: unknown, input: string, output: string): boolean { + return ( + isRecord(usage) && + [usage[input], usage[output]].every( + (value) => + typeof value === 'number' && Number.isSafeInteger(value) && value >= 0, + ) + ); +} + /** Join the text parts of a content value that may be a string or blocks. */ function textOf(content: unknown): string { if (typeof content === 'string') return content; @@ -638,6 +649,7 @@ export function parseChatReply( const usage = { prompt: tokenCount(root.usage, 'input_tokens'), completion: tokenCount(root.usage, 'output_tokens'), + reported: usageReported(root.usage, 'input_tokens', 'output_tokens'), }; const content = textOf(root.content); if (!content) { @@ -654,6 +666,7 @@ export function parseChatReply( const usage = { prompt: tokenCount(root.usage, 'prompt_tokens'), completion: tokenCount(root.usage, 'completion_tokens'), + reported: usageReported(root.usage, 'prompt_tokens', 'completion_tokens'), }; const content = textOf(message?.content); if (!content) { diff --git a/services/platform/backend/core/automations_builder/model_call.ts b/services/platform/backend/core/automations_builder/model_call.ts index 4fe1ad9017..9c52bb9eef 100644 --- a/services/platform/backend/core/automations_builder/model_call.ts +++ b/services/platform/backend/core/automations_builder/model_call.ts @@ -39,14 +39,18 @@ export interface BuilderMessage { } /** A direct text-model call with an explicit provider and model. */ -export type BuilderModel = (request: { +export type BuilderModel = ((request: { messages: BuilderMessage[]; temperature: number; turn: number; + signal?: AbortSignal; }) => Promise<{ content: string; - usage?: { prompt: number; completion: number }; -}>; + usage?: { prompt: number; completion: number; reported?: boolean }; +}>) & { + /** Resolve local credentials/catalog before a caller reserves paid work. */ + prepare?: () => Promise; +}; /** A model, named the way the platform names models everywhere else. */ export interface BuilderModelTarget { @@ -173,7 +177,7 @@ export function createBuilderModel( ): BuilderModel { let wire: WireTarget | null = null; - return async ({ messages, temperature }) => { + const call: BuilderModel = async ({ messages, temperature, signal }) => { wire ??= await resolveWireTarget(ctx, args.organizationId, args.target); const request = buildChatRequest({ apiFormat: wire.apiFormat, @@ -204,7 +208,14 @@ export function createBuilderModel( body: request.body, timeoutMs: REQUEST_TIMEOUT_MS, maxResponseBytes: MAX_RESPONSE_BYTES, - ...(args.signal !== undefined ? { signal: args.signal } : {}), + ...(args.signal !== undefined || signal !== undefined + ? { + signal: AbortSignal.any([ + ...(args.signal ? [args.signal] : []), + ...(signal ? [signal] : []), + ]), + } + : {}), }); } catch (error) { if (error instanceof SafeFetchError) { @@ -233,4 +244,8 @@ export function createBuilderModel( } return parseChatReply(wire.apiFormat, payload); }; + call.prepare = async () => { + wire ??= await resolveWireTarget(ctx, args.organizationId, args.target); + }; + return call; } diff --git a/services/platform/backend/core/chat/assistant_tools.ts b/services/platform/backend/core/chat/assistant_tools.ts index 7ee8448188..2f556c8d4e 100644 --- a/services/platform/backend/core/chat/assistant_tools.ts +++ b/services/platform/backend/core/chat/assistant_tools.ts @@ -518,7 +518,7 @@ const LIST_READ_SUBJECTS: Record = { // its conversation is, so the role that gates the inbox gates its files. 'mail-attachment': 'conversations', 'web-page': 'websites', - 'knowledge-entry': 'documents', + 'knowledge-entry': 'knowledge_entries', contact: 'contacts', product: 'products', website: 'websites', @@ -1010,6 +1010,7 @@ export function createChatToolExecutor( const [ documentsAllowed, + knowledgeEntriesAllowed, contactsAllowed, productsAllowed, websitesAllowed, @@ -1018,6 +1019,7 @@ export function createChatToolExecutor( conversationsAllowed, ] = await Promise.all([ readAllowed('documents'), + readAllowed('knowledge_entries'), readAllowed('contacts'), readAllowed('products'), readAllowed('websites'), @@ -1230,9 +1232,9 @@ export function createChatToolExecutor( // concatenated list, which would let document hits starve an exact // contact or product match out of the results entirely. - // Leg 2 — knowledge entries (Convex rows; lexical topic match). + // Leg 2 — organization-wide knowledge entries (lexical topic match). if (runLeg('knowledge-entry')) { - if (documentsAllowed) { + if (knowledgeEntriesAllowed) { const entries = await ctx.runQuery( internal.knowledge_entries.internal_queries.listEntriesForAgent, { diff --git a/services/platform/backend/core/governance/erasure_constants.ts b/services/platform/backend/core/governance/erasure_constants.ts index 4abefecba6..ec12dc758a 100644 --- a/services/platform/backend/core/governance/erasure_constants.ts +++ b/services/platform/backend/core/governance/erasure_constants.ts @@ -48,3 +48,7 @@ export type ErasureStatus = (typeof ERASURE_STATUSES)[number]; */ export const ERASURE_WATCHDOG_TIMEOUT_MESSAGE = 'Erasure timed out and was stopped by the watchdog. File a new request.' as const; + +/** Persisted partial-receipt reason, distinct from a legal hold or a failed + * pass. The drawer translates this exact token; a retry cannot clear it. */ +export const ERASURE_LEGACY_AUTOMATION_HOLD = 'legacy_automation_hold'; diff --git a/services/platform/app/features/settings/governance/data-subject-requests/breakdown-entries.test.ts b/services/platform/backend/core/governance/erasure_counts.test.ts similarity index 96% rename from services/platform/app/features/settings/governance/data-subject-requests/breakdown-entries.test.ts rename to services/platform/backend/core/governance/erasure_counts.test.ts index 449d4f6a88..371e8e4b1d 100644 --- a/services/platform/app/features/settings/governance/data-subject-requests/breakdown-entries.test.ts +++ b/services/platform/backend/core/governance/erasure_counts.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from 'vitest'; -import { foldBreakdownEntries } from './breakdown-entries.ts'; +import { foldBreakdownEntries } from './erasure_counts.ts'; describe('foldBreakdownEntries', () => { test('reads the plain-count shape a pass records', () => { diff --git a/services/platform/app/features/settings/governance/data-subject-requests/breakdown-entries.ts b/services/platform/backend/core/governance/erasure_counts.ts similarity index 100% rename from services/platform/app/features/settings/governance/data-subject-requests/breakdown-entries.ts rename to services/platform/backend/core/governance/erasure_counts.ts diff --git a/services/platform/backend/core/lib/handler_names.ts b/services/platform/backend/core/lib/handler_names.ts index 8eb1aba641..991a76697b 100644 --- a/services/platform/backend/core/lib/handler_names.ts +++ b/services/platform/backend/core/lib/handler_names.ts @@ -65,12 +65,12 @@ interface HandlerNames { heartbeatRun: FunctionRef; recordAgentTurnSettled: FunctionRef; recordLlmStepUsage: FunctionRef; + reserveLlmStepBudget: FunctionRef; recordProgress: FunctionRef; stampAgentTurnLaunch: FunctionRef; suspendRun: FunctionRef; }; queries: FunctionRef & { - checkLlmStepBudget: FunctionRef; getRunLanguageContext: FunctionRef; getRunProjectContext: FunctionRef; getRunProjectId: FunctionRef; @@ -369,6 +369,7 @@ interface HandlerNames { getTaskByIdInternal: FunctionRef; getTaskContextForAgent: FunctionRef; getTaskWorkStateForAgent: FunctionRef; + getTaskOccupancyForAgent: FunctionRef; getTaskReviewFilesForAgent: FunctionRef; listTasksForAgent: FunctionRef; }; diff --git a/services/platform/backend/core/node_only/sandbox/workspace_domain_tools.ts b/services/platform/backend/core/node_only/sandbox/workspace_domain_tools.ts index 7c21051d4e..cd3fc81df4 100644 --- a/services/platform/backend/core/node_only/sandbox/workspace_domain_tools.ts +++ b/services/platform/backend/core/node_only/sandbox/workspace_domain_tools.ts @@ -31,6 +31,7 @@ import { * creates no labels, and it neither syncs external items nor saves project * documents. */ +import { z } from 'zod'; import { AppError } from '../../../../lib/shared/errors/app-error'; import { extractExtension } from '../../../../lib/shared/file-types'; @@ -271,6 +272,53 @@ interface AgentRunAnswer { feedbackTruncated: boolean; } +// Compact mode is a new wire contract: malformed/missing state is unknown, +// never a successful empty observation. Zod strips fields this view omits. +const occupancyTimestampSchema = z + .number() + .finite() + .refine((value) => modelTimestamp(value) !== undefined); +const occupancyRunSchema = z.object({ + id: z.string().min(1).max(200), + agentId: z.string().min(1).max(200), + status: z.enum(['queued', 'running', 'settled', 'failed', 'cancelled']), + startedAt: occupancyTimestampSchema, + launchedAt: occupancyTimestampSchema.nullable(), + settledAt: occupancyTimestampSchema.nullable(), + waitingForCapacity: z.boolean(), + failureCode: z.string().max(200).nullable(), + retryPending: z.boolean(), +}); +const occupancySchema = z.object({ + currentRun: occupancyRunSchema.nullable(), + requestedRun: occupancyRunSchema.optional(), + workflowRun: z + .object({ + runId: z.string().min(1).max(200), + status: z.enum([ + 'queued', + 'running', + 'waiting', + 'success', + 'failed', + 'cancelled', + 'quarantined', + ]), + live: z.boolean(), + waitingFor: z + .enum(['approval', 'ask', 'in_doubt', 'agent', 'room', 'repeat']) + .optional(), + }) + .nullable(), +}); +const occupancyTaskSchema = z.object({ + taskId: z.string().min(1).max(200), + projectId: z.string().min(1).max(200), + status: z.enum(TASK_STATUSES), + assigneeType: z.string().max(100).nullish(), + assigneeId: z.string().max(200).nullish(), +}); + interface WorkflowRunAnswer { runId: string; automation: string; @@ -331,7 +379,12 @@ function agentComment(comment: { /** One project-agent run of the task: `live` while it is queued or running — * the platform starts no other run on the task until it is not. Terminal * runs carry `settledAt`; a failed one its `failureCode` when classified. */ -function agentRunView(run: AgentRunAnswer): Record { +function agentRunOccupancyView( + run: Omit< + AgentRunAnswer, + 'seq' | 'trigger' | 'feedback' | 'feedbackTruncated' + >, +): Record { const startedAt = modelTimestamp(run.startedAt); const launchedAt = modelTimestamp(run.launchedAt ?? undefined); const settledAt = modelTimestamp(run.settledAt ?? undefined); @@ -340,7 +393,6 @@ function agentRunView(run: AgentRunAnswer): Record { agentId: run.agentId, status: run.status, live: run.status === 'queued' || run.status === 'running', - ...(run.trigger !== null ? { trigger: run.trigger } : {}), ...(startedAt !== undefined ? { startedAt } : {}), ...(launchedAt !== undefined ? { launchedAt } : {}), ...(settledAt !== undefined ? { settledAt } : {}), @@ -349,8 +401,14 @@ function agentRunView(run: AgentRunAnswer): Record { ...(typeof run.retryPending === 'boolean' ? { retryPending: run.retryPending } : {}), - // What the start asked the run to address first — a person's comment, - // or the message of the agent that restarted it. + }; +} + +function agentRunView(run: AgentRunAnswer): Record { + return { + ...agentRunOccupancyView(run), + ...(run.trigger !== null ? { trigger: run.trigger } : {}), + // The full view retains the bounded start-message excerpt. ...(run.feedback !== null ? { feedback: run.feedback } : {}), ...(run.feedbackTruncated ? { feedbackTruncated: true } : {}), }; @@ -1035,6 +1093,31 @@ export async function runTaskTool( message: 'task_get needs a "taskId" string.', }; } + const occupancy = callArgs.view === 'occupancy'; + const requestedRunId = readString(callArgs.requestedRunId); + if ( + (callArgs.view !== undefined && !occupancy) || + (occupancy && taskId.length > 200) || + (callArgs.requestedRunId !== undefined && + (!occupancy || + requestedRunId === undefined || + requestedRunId.length > 200)) || + (occupancy && + [ + 'commentLimit', + 'commentCursor', + 'runLimit', + 'runCursor', + 'reviewFileCursor', + ].some((key) => callArgs[key] !== undefined)) + ) { + return { + status: 'invalid_args', + message: + 'task_get occupancy accepts only taskId, view: "occupancy" and an optional non-empty requestedRunId (identifiers at most 200 UTF-16 code units); omit all paging arguments. requestedRunId requires occupancy view.', + }; + } + const readStartedAt = Date.now(); // A project-bound run may only read tasks on its own board — check // before the full context read leaks another project's discussion. const scoped = await loadTaskInScope( @@ -1044,6 +1127,63 @@ export async function runTaskTool( authority, ); if ('refusal' in scoped) return scoped.refusal; + if (occupancy) { + const raw: unknown = await ctx.runQuery( + internal.tasks.internal_queries.getTaskOccupancyForAgent, + { + organizationId, + projectId: String(scoped.task.projectId), + taskId, + ...(requestedRunId !== undefined ? { requestedRunId } : {}), + }, + ); + if (raw === null && requestedRunId !== undefined) { + return { + status: 'not_found', + message: + 'The requested run is unavailable on this task; occupancy is unknown.', + }; + } + const work = occupancySchema.safeParse(raw); + const task = occupancyTaskSchema.safeParse({ + taskId: scoped.task._id, + projectId: scoped.task.projectId, + status: scoped.task.status, + assigneeType: scoped.task.assigneeType, + assigneeId: scoped.task.assigneeId, + }); + if ( + !work.success || + !task.success || + task.data.taskId !== taskId || + work.data.requestedRun?.id !== requestedRunId + ) { + return { + status: 'error', + message: + 'The task occupancy could not be read; whether work is running is unknown. Do not treat it as idle.', + }; + } + return { + status: 'ok', + output: { + view: 'occupancy', + task: task.data, + observed: { + startedAt: modelTimestamp(readStartedAt), + completedAt: modelTimestamp(Date.now()), + }, + currentRun: + work.data.currentRun === null + ? null + : agentRunOccupancyView(work.data.currentRun), + ...(work.data.requestedRun !== undefined + ? { requestedRun: agentRunOccupancyView(work.data.requestedRun) } + : {}), + workflowRun: work.data.workflowRun, + }, + }; + } // Both continuations are bound to this task and judged before the // task is read: a cursor it did not answer is refused, never taken // for its newest page. diff --git a/services/platform/backend/core/node_only/sandbox/workspace_tools_bridge.task_reads.test.ts b/services/platform/backend/core/node_only/sandbox/workspace_tools_bridge.task_reads.test.ts index 8fa7ce7100..0c336e79d0 100644 --- a/services/platform/backend/core/node_only/sandbox/workspace_tools_bridge.task_reads.test.ts +++ b/services/platform/backend/core/node_only/sandbox/workspace_tools_bridge.task_reads.test.ts @@ -109,6 +109,7 @@ interface Harness { scope: Scope; context: (args: Record) => unknown; workState: (args: Record) => unknown; + occupancy: (args: Record) => unknown; } function createHarness(overrides: Partial = {}) { @@ -134,6 +135,7 @@ function createHarness(overrides: Partial = {}) { workflowRun: null, pendingReview: null, }), + occupancy: () => ({ currentRun: null, workflowRun: null }), ...overrides, }; const calls: { name: string; args: Record }[] = []; @@ -153,11 +155,16 @@ function createHarness(overrides: Partial = {}) { if (name === 'tasks/internal_queries:getTaskByIdInternal') { const id = String(args.taskId); if (id === 't-foreign') return { _id: id, projectId: 'p-other' }; - return id.startsWith('t-') ? { _id: id, projectId: 'p-1' } : null; + return id.startsWith('t-') + ? { _id: id, projectId: 'p-1', status: 'todo' } + : null; } if (name === 'tasks/internal_queries:getTaskContextForAgent') { return harness.context(args); } + if (name === 'tasks/internal_queries:getTaskOccupancyForAgent') { + return harness.occupancy(args); + } if (name === 'tasks/internal_queries:getTaskWorkStateForAgent') { return harness.workState(args); } @@ -945,3 +952,280 @@ describe('task_get reads what a manager decides with', () => { expect(called('getTaskWorkStateForAgent')).toHaveLength(0); }); }); + +describe('task_get compact occupancy', () => { + const run = (id: string, status: string) => ({ + id, + seq: 1, + agentId: 'worker-1', + status, + trigger: 'manual', + startedAt: 1790000000000, + launchedAt: null, + settledAt: status === 'settled' ? 1790000000100 : null, + waitingForCapacity: false, + failureCode: null, + retryPending: false, + feedback: 'Private full context', + feedbackTruncated: false, + }); + + it('binds an old requested run and a newer live occupant without full context', async () => { + const { call, called } = createHarness({ + occupancy: () => ({ + requestedRun: run('old-run', 'settled'), + currentRun: run('new-run', 'running'), + workflowRun: null, + }), + }); + const answer = await call('task_get', { + taskId: 't-0000', + view: 'occupancy', + requestedRunId: 'old-run', + }); + expect(answer.status).toBe('ok'); + expect(outputOf(answer)).toMatchObject({ + view: 'occupancy', + task: { taskId: 't-0000', projectId: 'p-1', status: 'todo' }, + requestedRun: { runId: 'old-run', live: false }, + currentRun: { runId: 'new-run', live: true }, + workflowRun: null, + }); + expect(called('getTaskOccupancyForAgent')).toEqual([ + { + name: 'tasks/internal_queries:getTaskOccupancyForAgent', + args: { + organizationId: 'org-1', + projectId: 'p-1', + taskId: 't-0000', + requestedRunId: 'old-run', + }, + }, + ]); + expect(called('getTaskContextForAgent')).toHaveLength(0); + expect(called('getTaskWorkStateForAgent')).toHaveLength(0); + expect(called('getTaskReviewFilesForAgent')).toHaveLength(0); + expect(JSON.stringify(answer)).not.toContain('Private full context'); + expect(outputOf(answer)).not.toHaveProperty('pendingReview'); + expect(outputOf(answer)).not.toHaveProperty('idle'); + expect(outputOf(answer)).not.toHaveProperty('canStart'); + }); + + it.each([ + { view: 'occupancy', taskId: 'x'.repeat(201) }, + { view: 'full' }, + { view: null }, + { requestedRunId: 'run' }, + ...[null, '', ' ', 1, {}, 'x'.repeat(201)].map((requestedRunId) => ({ + view: 'occupancy', + requestedRunId, + })), + ...[ + 'commentLimit', + 'commentCursor', + 'runLimit', + 'runCursor', + 'reviewFileCursor', + ].map((key) => ({ view: 'occupancy', [key]: null })), + ])( + 'refuses incompatible occupancy arguments before optional reads: %j', + async (args) => { + const { call, called } = createHarness(); + expect( + (await call('task_get', { taskId: 't-0000', ...args })).status, + ).toBe('invalid_args'); + expect(called('getTaskOccupancyForAgent')).toHaveLength(0); + expect(called('getTaskContextForAgent')).toHaveLength(0); + }, + ); + + it.each([ + undefined, + {}, + { currentRun: undefined, workflowRun: null }, + { + currentRun: { ...run('run', 'running'), retryPending: undefined }, + workflowRun: null, + }, + { currentRun: run('run', 'unknown'), workflowRun: null }, + { + currentRun: { ...run('run', 'running'), startedAt: 1e100 }, + workflowRun: null, + }, + { currentRun: null, workflowRun: {} }, + ])('answers malformed occupancy as unknown: %j', async (raw) => { + const { call } = createHarness({ occupancy: () => raw }); + const answer = await call('task_get', { + taskId: 't-0000', + view: 'occupancy', + }); + expect(answer.status).toBe('error'); + expect(answer).not.toHaveProperty('output'); + expect(answer.message).toContain('unknown'); + }); + + it('does not replace an unavailable requested run with an empty or different run', async () => { + for (const state of [ + null, + { currentRun: null, workflowRun: null }, + { + currentRun: null, + requestedRun: run('different', 'settled'), + workflowRun: null, + }, + ]) { + const { call } = createHarness({ occupancy: () => state }); + const answer = await call('task_get', { + taskId: 't-0000', + view: 'occupancy', + requestedRunId: 'requested', + }); + expect(answer.status).toBe(state === null ? 'not_found' : 'error'); + expect(answer).not.toHaveProperty('output'); + } + }); + + it('propagates unavailable reads and preserves a successfully empty observation', async () => { + const { call, harness } = createHarness(); + expect( + outputOf(await call('task_get', { taskId: 't-0000', view: 'occupancy' })), + ).toMatchObject({ currentRun: null, workflowRun: null }); + harness.occupancy = () => { + throw new Error('database unavailable'); + }; + const answer = await call('task_get', { + taskId: 't-0000', + view: 'occupancy', + }); + expect(answer.status).toBe('error'); + expect(answer).not.toHaveProperty('output'); + }); + + it.each([ + { kind: 'project', projectId: 'p-1' }, + { kind: 'org', allowedProjectIds: ['p-1'] }, + ] as const)( + 'preserves task scope before compact reads: %j', + async (scope) => { + const { call, called } = createHarness({ + scope: + scope.kind === 'project' + ? scope + : { ...scope, allowedProjectIds: [...scope.allowedProjectIds] }, + }); + const foreign = await call('task_get', { + taskId: 't-foreign', + view: 'occupancy', + requestedRunId: 'foreign-run', + }); + const missing = await call('task_get', { + taskId: 'missing', + view: 'occupancy', + requestedRunId: 'foreign-run', + }); + expect(foreign).toEqual(missing); + expect(foreign.status).toBe('not_found'); + expect(called('getTaskOccupancyForAgent')).toHaveLength(0); + }, + ); + + it('retains queued capacity waits, retry state and person-bound workflow occupancy', async () => { + const { call } = createHarness({ + occupancy: () => ({ + currentRun: { ...run('queued', 'queued'), waitingForCapacity: true }, + requestedRun: { + ...run('failed', 'failed'), + retryPending: false, + failureCode: 'harness_error', + }, + workflowRun: { + runId: 'workflow', + status: 'waiting', + live: true, + waitingFor: 'ask', + automation: 'private name', + ask: { question: 'private question' }, + }, + }), + }); + const answer = outputOf( + await call('task_get', { + taskId: 't-0000', + view: 'occupancy', + requestedRunId: 'failed', + }), + ); + expect(answer).toMatchObject({ + currentRun: { + runId: 'queued', + live: true, + waitingForCapacity: true, + retryPending: false, + }, + requestedRun: { + runId: 'failed', + live: false, + retryPending: false, + failureCode: 'harness_error', + }, + }); + expect(answer.workflowRun).toEqual({ + runId: 'workflow', + status: 'waiting', + live: true, + waitingFor: 'ask', + }); + expect(answer.observed).toEqual({ + startedAt: expect.any(String), + completedAt: expect.any(String), + }); + expect(JSON.stringify(answer)).not.toContain('private'); + }); + + it('measures a smaller response while leaving the full default context intact', async () => { + const description = 'Synthetic task context. '.repeat(800); + const { call, called } = createHarness({ + context: () => ({ + task: { + _id: 't-0000', + title: 'Fixture', + status: 'todo', + projectId: 'p-1', + description, + }, + project: { instructions: 'Synthetic policy. '.repeat(800) }, + subtasks: [], + blockedBy: [], + comments: [], + commentsHasMore: false, + }), + occupancy: () => ({ + currentRun: run('current', 'running'), + requestedRun: run('requested', 'settled'), + workflowRun: null, + }), + }); + const full = await call('task_get', { taskId: 't-0000' }); + const compact = await call('task_get', { + taskId: 't-0000', + view: 'occupancy', + requestedRunId: 'requested', + }); + expect((outputOf(full).task as Record).description).toBe( + description, + ); + expect(outputOf(full)).not.toHaveProperty('view'); + const fullBytes = Buffer.byteLength(JSON.stringify(full)); + const compactBytes = Buffer.byteLength(JSON.stringify(compact)); + expect(compactBytes).toBeLessThan(fullBytes / 4); + expect(compactBytes).toBeLessThan(4096); + expect(called('getTaskContextForAgent')).toHaveLength(1); + expect(called('getTaskWorkStateForAgent')).toHaveLength(1); + expect(called('getTaskOccupancyForAgent')).toHaveLength(1); + console.info('Synthetic task_get bytes', { + fullBytes, + compactBytes, + reduction: 1 - compactBytes / fullBytes, + }); + }); +}); diff --git a/services/platform/backend/core/node_only/sandbox/workspace_tools_bridge.ts b/services/platform/backend/core/node_only/sandbox/workspace_tools_bridge.ts index c2153cd00e..c015619f04 100644 --- a/services/platform/backend/core/node_only/sandbox/workspace_tools_bridge.ts +++ b/services/platform/backend/core/node_only/sandbox/workspace_tools_bridge.ts @@ -86,9 +86,9 @@ const WRITE_TOOL_SET: ReadonlySet = new Set(WRITE_EFFECT_TOOLS); /** * The role-matrix table each tool reads, for the per-dispatch access check. - * Knowledge surfaces (RAG passages, hub listings, entries) all map to - * `documents`: passages ARE document content and entries are document-backed, - * so one subject governs the whole knowledge read path. + * Scoped document passages and listings share `documents`. Knowledge entries + * are organization-wide, so their own subject must reach the user fallback + * gate instead of inheriting a project API key's document access. */ const TOOL_READ_SUBJECT: Record = { rag_search: 'documents', @@ -96,7 +96,7 @@ const TOOL_READ_SUBJECT: Record = { // subject to 'websites' per call — this entry is the file-id default. rag_fetch: 'documents', document_find: 'documents', - knowledge_entry_find: 'documents', + knowledge_entry_find: 'knowledge_entries', contact_find: 'contacts', product_find: 'products', website_find: 'websites', @@ -191,7 +191,18 @@ const TOOL_DESCRIPTIONS: Record = { 'automation run and a pending review. Args: {taskId: string, ' + 'commentLimit?: number (≤ 50, default 20), commentCursor?: string, ' + 'runLimit?: number (≤ 20, default 5), runCursor?: string, ' + - 'reviewFileCursor?: string}. comments are ' + + 'reviewFileCursor?: string}. For a compact run observation use only ' + + '{taskId, view: "occupancy", requestedRunId?: string}: no paging arguments. ' + + 'Require output.view "occupancy" to confirm support; an older full reply ' + + 'does not bind the requested run. It returns currentRun (newest) and, ' + + 'when requested, that exact requestedRun, plus workflowRun and the server ' + + 'observed read interval. A historical terminal run never replaces a newer ' + + 'occupant. Missing/inaccessible requested runs fail; failures are unknown. ' + + 'This omits instructions, comments, feedback, blockers and reviews. The ' + + 'read is not atomic, does not reserve capacity and never authorizes a ' + + 'start or review; read full current context and use guarded mutations. ' + + 'A quarantined workflow remains held even though it is not live. ' + + 'In the default full view, comments are ' + 'the newest page, oldest first, each with its commentId (the messageId ' + 'task_comment answered); while commentsPage.isDone is false, pass ' + 'commentsPage.continueCursor as commentCursor for older ones. agentRuns ' + diff --git a/services/platform/backend/core/sandbox/workspace_access.ts b/services/platform/backend/core/sandbox/workspace_access.ts index b2ead98abe..b588d00549 100644 --- a/services/platform/backend/core/sandbox/workspace_access.ts +++ b/services/platform/backend/core/sandbox/workspace_access.ts @@ -15,15 +15,19 @@ * ONE list every read leg types its subject against, so a table added to * the matrix cannot go missing in a caller's private copy. * - * `allowed: true` means only that the caller's ROLE may read the table. Some - * subjects need a second, narrower gate this vocabulary does not own: + * `allowed: true` means only that the caller's role and API-key owner may + * read the table. Some subjects need a second, narrower gate this vocabulary + * does not own: * `documents` and `tasks` narrow to the caller's team/project visibility, * and `conversations` narrows further still to its assignment scope (a * conversation assigned to nobody is admin triage only). Treating `allowed: - * true` as "read the whole org" is a leak for those three. + * true` as "read the whole org" is a leak for those three. Organization-wide + * `knowledge_entries` are a separate subject: unlike scoped documents, they + * are never readable by a project's own API key. */ export type AgentReadSubject = | 'documents' + | 'knowledge_entries' | 'contacts' | 'products' | 'websites' @@ -44,6 +48,7 @@ export type AgentReadSubject = export const SESSION_ACTION_SUBJECTS = [ 'tasks', 'documents', + 'knowledge_entries', 'contacts', 'products', 'websites', diff --git a/services/platform/backend/db/migrations/0164_immutable_budget_reservations.sql b/services/platform/backend/db/migrations/0164_immutable_budget_reservations.sql new file mode 100644 index 0000000000..8e63da9a5d --- /dev/null +++ b/services/platform/backend/db/migrations/0164_immutable_budget_reservations.sql @@ -0,0 +1,31 @@ +-- Keep admitted projects and voice cost holds stable until settlement +-- +-- A chat moved to another project used to move its live hold while its bill +-- still named the original project. Voice chunks checked booked usage only, +-- so distinct requests racing a cap could all pass. New writers stamp the +-- exact admitted projects ([] means deliberately none), and pending voice +-- attempts carry their estimated cost until ready/failed settlement. +-- +-- NULL preserves compatibility with previous writers and identifies legacy +-- unstamped rows; it must not be confused with an authoritative empty array. +-- No historical projects or provider outcomes can be inferred by a backfill. +-- Strict reservation guarantees begin with new admissions after old writers +-- have retired; nullable additive columns alone do not fence old processes. + +ALTER TABLE app.generations + ADD COLUMN IF NOT EXISTS project_ids text[]; + +ALTER TABLE app.tts_audio_chunks + ADD COLUMN IF NOT EXISTS project_ids text[], + ADD COLUMN IF NOT EXISTS reserved_cost_cents double precision; + +-- Read only pending attempts, not all retained audio, at every admission. +CREATE INDEX IF NOT EXISTS tts_audio_chunks_pending_budget + ON app.tts_audio_chunks (org_id) WHERE status = 'pending'; + +-- Direct automation model calls use the existing op reservation/settlement +-- ledger. Their settled transport rows use the same bounded age sweep as +-- model-api rows, with a separate literal-kind index for its ordered batch. +CREATE INDEX IF NOT EXISTS sandbox_session_ops_automation_llm_started + ON app.sandbox_session_ops (started_at_ms) + WHERE kind = 'automation-llm'; diff --git a/services/platform/backend/domains/api_keys/spec.md b/services/platform/backend/domains/api_keys/spec.md index 6164674d22..c6004cb2c8 100644 --- a/services/platform/backend/domains/api_keys/spec.md +++ b/services/platform/backend/domains/api_keys/spec.md @@ -75,8 +75,10 @@ the key acts with, and names whose key it is. A team's key sees the team's projects, documents and inbox. A project's key reaches its project, the project list (which shows that project only), `GET /me` and the model endpoints; any other route is refused (`API_KEY_SCOPE_FORBIDDEN`). Through the chat assistant it reads its project's -files and tasks, and none of the organization's contacts, products, websites, inbox or hub -documents. The organization's key sees what its role sees across the organization. +files and tasks, and none of the organization's contacts, products, websites, inbox, knowledge +entries or hub documents. Organization-wide knowledge entries stay out of both search and +listing, including the user-keyed sandbox entry finder. The organization's key sees what its role +sees across the organization. - **Example**: The Launch project's key calls `GET /contacts` → 403 `API_KEY_SCOPE_FORBIDDEN`. diff --git a/services/platform/backend/domains/automations/legacy-protocol.integration.ts b/services/platform/backend/domains/automations/legacy-protocol.integration.ts index 1436d18482..fc236bf23c 100644 --- a/services/platform/backend/domains/automations/legacy-protocol.integration.ts +++ b/services/platform/backend/domains/automations/legacy-protocol.integration.ts @@ -19,6 +19,11 @@ import { runBootMigrations, } from '../../db/migrate.ts'; import { resolvePostgresConnection } from '../../db/ssl.ts'; +import { eraseSubjectAutomationRuns } from '../erasure/service.ts'; +import { + assertNoLegacyAutomationHolds, + OrganizationError, +} from '../organizations/service.ts'; import { TaskError } from '../tasks/errors.ts'; import { findLatestAutomationRunForTask, @@ -747,6 +752,81 @@ export async function checkLegacyAutomationProtocol( afterStopDelete === 'P7502', 'one operator decision; original asks preserved; task start and purge still refused', ); + + // Exercise the real erasure primitive against an actual 0163 cutover, + // including a stopped hold. Ordinary subject rows must still be erased. + await fixture.begin(async (tx) => { + await markAutomationWriterInTx(tx); + await tx` + INSERT INTO app.automation_runs + (id, org_id, name, version, status, mode, started_by, started_at_ms, finished_at_ms) + VALUES ('erasure-unheld', 'fixture', 'example', 1, 'success', 'live', 'user:fixture', 1, 2), + ('erasure-other-subject', 'fixture', 'example', 1, 'success', 'live', 'user:other', 1, 2), + ('erasure-other-org', 'other', 'example', 1, 'success', 'live', 'user:fixture', 1, 2) + `; + }); + const heldSnapshot = () => fixture<{ rows: unknown }[]>` + SELECT jsonb_agg(to_jsonb(r) ORDER BY id) AS rows + FROM app.automation_runs r WHERE legacy_quarantine IS NOT NULL + `; + // The earlier writer-admission probes also left two unheld subject runs. + // Assert that complete starting set so the deletion count cannot ignore it. + const unheldSubjectRuns = () => fixture<{ id: string }[]>` + SELECT id FROM app.automation_runs + WHERE org_id = 'fixture' AND started_by = 'user:fixture' + AND legacy_quarantine IS NULL + ORDER BY id + `; + const beforeUnheldErasure = await unheldSubjectRuns(); + const beforeErasure = await heldSnapshot(); + const erased = await eraseSubjectAutomationRuns( + fixture, + 'fixture', + 'fixture', + ); + const afterErasure = await heldSnapshot(); + const afterUnheldErasure = await unheldSubjectRuns(); + const kept = await fixture<{ id: string }[]>` + SELECT id FROM app.automation_runs WHERE id LIKE 'erasure-%' ORDER BY id + `; + const [ask] = await fixture<{ question: string }[]>` + SELECT question FROM app.automation_human_asks WHERE id = 'held-ask' + `; + const repeatErasure = await eraseSubjectAutomationRuns( + fixture, + 'fixture', + 'fixture', + ); + record( + 'subject erasure deletes unheld runs and preserves exact held evidence across retries [ERASE-R9]', + beforeUnheldErasure.map((row) => row.id).join(',') === + 'erasure-unheld,fresh,future-floor' && + erased.deleted === 3 && + erased.held === 3 && + afterUnheldErasure.length === 0 && + repeatErasure.deleted === 0 && + repeatErasure.held === 3 && + JSON.stringify(beforeErasure) === JSON.stringify(afterErasure) && + kept.map((row) => row.id).join(',') === + 'erasure-other-org,erasure-other-subject' && + ask?.question === 'original question', + 'same subject in another tenant and another subject in this tenant survive; stop never grants deletion authority', + ); + let orgConflict: string | undefined; + try { + await fixture.begin((tx) => assertNoLegacyAutomationHolds(tx, 'fixture')); + } catch (error) { + if (!(error instanceof OrganizationError) || error.status !== 409) + throw error; + orgConflict = error.code; + } + await fixture.begin((tx) => assertNoLegacyAutomationHolds(tx, 'other')); + record( + 'organization legacy-hold preflight returns a tenant-scoped conflict [ORG-R12]', + orgConflict === 'ORG_LEGACY_AUTOMATION_HELD' && + JSON.stringify(afterErasure) === JSON.stringify(await heldSnapshot()), + 'held organization is refused; another tenant is admitted; hold facts remain unchanged', + ); } finally { await releaseLedger?.(); await lateWrite; diff --git a/services/platform/backend/domains/automations/llm-metering.test.ts b/services/platform/backend/domains/automations/llm-metering.test.ts index d235ae54ad..092bf69317 100644 --- a/services/platform/backend/domains/automations/llm-metering.test.ts +++ b/services/platform/backend/domains/automations/llm-metering.test.ts @@ -1,200 +1,190 @@ -/** - * An automation's `llm` step is measured and booked as its run's spend: the - * run's own subject (`resolveAutomationRunAttribution`, proven in its suite) - * is measured against every cap that binds it, counting the work in flight, - * and each call's tokens are booked under it. The gate, the holds and the - * ledger writer are stand-ins; the refusal's wording is the real one. - */ - import type { Sql } from 'postgres'; import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { AUTOMATION_SUBJECT_ID } from '../../../lib/shared/constants/usage.ts'; - const mocks = vi.hoisted(() => ({ resolveAutomationRunAttribution: vi.fn(), - budgetPolicyActive: vi.fn(), - findBudgetViolation: vi.fn(), - loadBudgetSubject: vi.fn(), - readInFlightReservations: vi.fn(), - record: vi.fn(async () => undefined), + reserveTurnBudget: vi.fn(), + reconcileSessionOpKey: vi.fn(), })); - vi.mock('../sandbox/op-attribution.ts', () => ({ resolveAutomationRunAttribution: mocks.resolveAutomationRunAttribution, })); -vi.mock('../governance/budget-gate.ts', () => ({ - budgetPolicyActive: mocks.budgetPolicyActive, - findBudgetViolation: mocks.findBudgetViolation, - loadBudgetSubject: mocks.loadBudgetSubject, +vi.mock('../sandbox/turn-budget.ts', () => ({ + reserveTurnBudget: mocks.reserveTurnBudget, })); -vi.mock('../governance/budget-reservations.ts', () => ({ - readInFlightReservations: mocks.readInFlightReservations, +vi.mock('../sandbox/spend-settlement.ts', () => ({ + reconcileSessionOpKey: mocks.reconcileSessionOpKey, })); -vi.mock('../chat/store.ts', () => ({ - createPgUsageLedger: () => ({ record: mocks.record }), -})); - -const { checkLlmStepBudget, recordLlmStepUsage } = +const { llmStepOp, reserveLlmStepBudget, recordLlmStepUsage } = await import('./llm-metering.ts'); -const SQL = {} as Sql; -const RUN = { organizationId: 'org-1', runId: 'run-1' }; -const HOLDS = { org: { costCents: 40, tokens: 0, requests: 1 } }; - -beforeEach(() => { - vi.clearAllMocks(); - mocks.budgetPolicyActive.mockResolvedValue(true); - mocks.findBudgetViolation.mockResolvedValue(null); - mocks.readInFlightReservations.mockResolvedValue(HOLDS); - mocks.loadBudgetSubject.mockImplementation( - async (_sql: unknown, args: object) => ({ ...args, userTeamIds: [] }), +const attempt = { + nodeId: 'loop[2:3]/model', + itemIndex: 2, + pass: 3, + attempt: 1, +}; +const request = { + organizationId: 'org', + runId: 'run', + attempt, + provider: 'provider', + model: 'vendor/model', + reserveCents: 2.5, + reserveTokens: 8040, +}; +const subject = { + userId: 'user', + agentSlug: 'automation', + projectIds: ['a', 'b'], +}; +function fakeSql(live = true, duplicate = false) { + const statements: Array<{ text: string; values: unknown[] }> = []; + const query = vi.fn( + async (strings: TemplateStringsArray, ...values: unknown[]) => { + const text = strings.join('?').replace(/\s+/g, ' '); + statements.push({ text, values }); + if (text.includes('FROM app.automation_node_attempts')) + return live ? [{ id: 'attempt' }] : []; + if (text.includes('SELECT id FROM app.sandbox_session_ops')) + return duplicate ? [{ id: 'old' }] : []; + return []; + }, ); + return { sql: query as unknown as Sql, query, statements }; +} +beforeEach(() => { + vi.resetAllMocks(); + mocks.resolveAutomationRunAttribution.mockResolvedValue(subject); + mocks.reserveTurnBudget.mockImplementation(async (sql, args) => { + await args.prepareSubject(sql); + return { allowed: true, budgetCents: 3 }; + }); }); -describe('checkLlmStepBudget', () => { - it('admits every call while no budget policy binds, reading nothing else', async () => { - mocks.budgetPolicyActive.mockResolvedValue(false); - await expect(checkLlmStepBudget(SQL, RUN)).resolves.toEqual({ - allowed: true, - }); - expect(mocks.resolveAutomationRunAttribution).not.toHaveBeenCalled(); - expect(mocks.findBudgetViolation).not.toHaveBeenCalled(); +describe('direct LLM attempt reservation', () => { + it('separates organization, run, nested node, item, pass and retry identities', () => { + const base = llmStepOp(request); + const variants = [ + { ...request, organizationId: 'other' }, + { ...request, runId: 'other' }, + ...(['nodeId', 'itemIndex', 'pass', 'attempt'] as const).map((field) => + Object.assign({}, request, { + attempt: Object.assign({}, attempt, { + [field]: field === 'nodeId' ? 'other' : 9, + }), + }), + ), + ]; + expect( + new Set([ + base.execId, + ...variants.map((value) => llmStepOp(value).execId), + ]).size, + ).toBe(7); + expect(llmStepOp({ ...request })).toEqual(base); }); - - it('measures the run’s person, key and projects, counting the work in flight [GOV-R14]', async () => { - mocks.resolveAutomationRunAttribution.mockResolvedValue({ - userId: 'user-2', - agentSlug: 'invoices/monthly', - apiKeyId: 'key-1', - projectIds: ['project-1', 'project-2'], - }); - - await expect(checkLlmStepBudget(SQL, RUN)).resolves.toEqual({ + it('holds the full request through the canonical admission and derives its subject under the lock [GOV-R14]', async () => { + const { sql, statements } = fakeSql(); + await expect(reserveLlmStepBudget(sql, request)).resolves.toMatchObject({ allowed: true, + ...llmStepOp(request), }); - - expect(mocks.resolveAutomationRunAttribution).toHaveBeenCalledWith( - SQL, - RUN, + expect(mocks.reserveTurnBudget).toHaveBeenCalledWith( + sql, + expect.objectContaining({ + kind: 'automation-llm', + defaultBudgetCents: 3, + whole: { prospectiveTokens: 8040 }, + modelRef: 'provider/provider/vendor/model', + prepareSubject: expect.any(Function), + }), ); - const subject = { - organizationId: 'org-1', - userId: 'user-2', - apiKeyId: 'key-1', - projectIds: ['project-1', 'project-2'], - }; - expect(mocks.loadBudgetSubject).toHaveBeenCalledWith(SQL, subject); - expect(mocks.findBudgetViolation).toHaveBeenCalledWith( - SQL, - expect.objectContaining(subject), - { reservations: HOLDS }, + expect(statements[0]?.text).toContain('a.claim_epoch = r.claim_epoch'); + expect(statements[0]?.text).toContain('r.lease_expires_at_ms >'); + expect(mocks.resolveAutomationRunAttribution).toHaveBeenCalledWith( + sql, + request, ); }); - - it('measures a run a trigger started as nobody: the organization’s caps, and its projects’', async () => { - mocks.resolveAutomationRunAttribution.mockResolvedValue({ - userId: AUTOMATION_SUBJECT_ID, - agentSlug: 'invoices/monthly', - projectIds: ['project-1'], - }); - - await checkLlmStepBudget(SQL, RUN); - - expect(mocks.loadBudgetSubject).not.toHaveBeenCalled(); - expect(mocks.findBudgetViolation).toHaveBeenCalledWith( - SQL, - { - organizationId: 'org-1', - userId: AUTOMATION_SUBJECT_ID, - userTeamIds: [], - impersonal: true, - projectIds: ['project-1'], - }, - { reservations: HOLDS }, + it.each([ + [false, false, 'no longer current'], + [true, true, 'already admitted'], + ] as const)( + 'refuses stale=%s duplicate=%s before acquiring a hold', + async (live, duplicate, reason) => { + const { sql } = fakeSql(live, duplicate); + await expect(reserveLlmStepBudget(sql, request)).rejects.toThrow(reason); + expect(mocks.resolveAutomationRunAttribution).not.toHaveBeenCalled(); + }, + ); + it('refuses an unattributable run instead of creating unowned spend', async () => { + mocks.resolveAutomationRunAttribution.mockResolvedValue(null); + await expect(reserveLlmStepBudget(fakeSql().sql, request)).rejects.toThrow( + 'no billing subject', ); }); - - it('refuses once a cap is reached, naming it in the gate’s own sentence [GOV-R4]', async () => { - mocks.resolveAutomationRunAttribution.mockResolvedValue({ - userId: AUTOMATION_SUBJECT_ID, - projectIds: ['project-1'], - }); - mocks.findBudgetViolation.mockResolvedValue({ - scope: 'project', - projectId: 'project-1', - code: 'COST_LIMIT', - period: 'monthly', - used: 100, - limit: 100, - reason: 'Cost limit reached', - resetsAt: Date.UTC(2026, 10, 1), - }); - - await expect(checkLlmStepBudget(SQL, RUN)).resolves.toEqual({ - allowed: false, - reason: - "Usage limit reached. This project's monthly cost limit is used up until 2026-11-01T00:00:00.000Z.", - }); + it('returns a canonical cap refusal unchanged [GOV-R4]', async () => { + const refusal = { allowed: false, reason: 'project cap' }; + mocks.reserveTurnBudget.mockResolvedValue(refusal); + await expect(reserveLlmStepBudget(fakeSql().sql, request)).resolves.toEqual( + refusal, + ); }); + it.each([NaN, -1, Infinity])( + 'rejects invalid reservation cost %s', + async (reserveCents) => { + await expect( + reserveLlmStepBudget(fakeSql().sql, { ...request, reserveCents }), + ).rejects.toThrow('Invalid'); + expect(mocks.reserveTurnBudget).not.toHaveBeenCalled(); + }, + ); }); -describe('recordLlmStepUsage', () => { - const USAGE = { - ...RUN, - provider: 'openrouter', - model: 'anthropic/claude-haiku-4.5', - inputTokens: 120, - outputTokens: 30, - }; - - it('books the call under the run’s subject, in each of its projects [GOV-R14]', async () => { - mocks.resolveAutomationRunAttribution.mockResolvedValue({ - userId: 'user-3', - agentSlug: 'invoices/monthly', - apiKeyId: 'key-1', - projectIds: ['project-1', 'project-2'], - }); - - await recordLlmStepUsage(SQL, USAGE); - - expect(mocks.record).toHaveBeenCalledWith({ - organizationId: 'org-1', - userId: 'user-3', - apiKeyId: 'key-1', - agentSlug: 'invoices/monthly', - model: 'anthropic/claude-haiku-4.5', - provider: 'openrouter', - inputTokens: 120, - outputTokens: 30, - totalTokens: 150, - projectIds: ['project-1', 'project-2'], +describe('durable direct LLM terminal facts', () => { + const op = { organizationId: 'org', ...llmStepOp(request) }; + it('persists reported facts before settlement and keeps the exact op identity', async () => { + const { sql, statements } = fakeSql(); + await recordLlmStepUsage(sql, { + ...op, + usage: { inputTokens: 40, outputTokens: 10, cents: 0.5 }, }); - }); - - it('books a run outside every project to the ledger alone', async () => { - mocks.resolveAutomationRunAttribution.mockResolvedValue({ - userId: AUTOMATION_SUBJECT_ID, - agentSlug: 'invoices/monthly', - }); - - await recordLlmStepUsage(SQL, USAGE); - - expect(mocks.record).toHaveBeenCalledWith( - expect.not.objectContaining({ projectIds: expect.anything() }), + expect(statements[0]?.values).toContain(0.5); + expect(statements[0]?.text).toContain( + 'AND finalized_at_ms IS NULL AND spend_settled_at_ms IS NULL', + ); + expect(mocks.reconcileSessionOpKey).toHaveBeenCalledWith( + sql, + expect.objectContaining(op), ); }); - - it('books nothing, and says so, for a run that names no one', async () => { - const error = vi.spyOn(console, 'error').mockImplementation(() => {}); - mocks.resolveAutomationRunAttribution.mockResolvedValue(null); - - await recordLlmStepUsage(SQL, USAGE); - - expect(mocks.record).not.toHaveBeenCalled(); - expect(error).toHaveBeenCalledWith( - expect.stringContaining('run run-1 names no one to book its llm step to'), + it('persists unknown as NULL and holds it until the original request deadline', async () => { + const { sql, statements } = fakeSql(); + await recordLlmStepUsage(sql, { ...op, usage: null }); + expect(statements[0]?.text).toContain('THEN started_at_ms +'); + expect(statements[0]?.values).toContain(null); + expect(statements[0]?.values).toContain(180000); + }); + it('does not settle when saving the only terminal facts fails', async () => { + const { sql, query } = fakeSql(); + query.mockRejectedValueOnce(new Error('offline')); + await expect( + recordLlmStepUsage(sql, { ...op, usage: null }), + ).rejects.toThrow('offline'); + expect(mocks.reconcileSessionOpKey).not.toHaveBeenCalled(); + }); + it('retains persisted facts when the ledger attempt fails', async () => { + const { sql, statements } = fakeSql(); + mocks.reconcileSessionOpKey.mockRejectedValueOnce( + new Error('ledger offline'), ); - error.mockRestore(); + await expect( + recordLlmStepUsage(sql, { + ...op, + usage: { inputTokens: 1, outputTokens: 2, cents: 0.3 }, + }), + ).rejects.toThrow('ledger offline'); + expect(statements).toHaveLength(1); }); }); diff --git a/services/platform/backend/domains/automations/llm-metering.ts b/services/platform/backend/domains/automations/llm-metering.ts index ec58b1223f..6eeb98ee84 100644 --- a/services/platform/backend/domains/automations/llm-metering.ts +++ b/services/platform/backend/domains/automations/llm-metering.ts @@ -1,94 +1,146 @@ +import { createHash } from 'node:crypto'; + import type { Sql } from 'postgres'; -import { createPgUsageLedger } from '../chat/store.ts'; -import { loadAttributedBudgetSubject } from '../governance/attributed-subject.ts'; import { - budgetPolicyActive, - findBudgetViolation, -} from '../governance/budget-gate.ts'; -import { budgetRefusalMessage } from '../governance/budget-refusal.ts'; -import { readInFlightReservations } from '../governance/budget-reservations.ts'; + AUTOMATION_LLM_LIFETIME_MS, + AUTOMATION_LLM_OP_KIND, + type LlmAttemptAddress, +} from '../../core/automations/llm_budget.ts'; import { resolveAutomationRunAttribution } from '../sandbox/op-attribution.ts'; +import { reconcileSessionOpKey } from '../sandbox/spend-settlement.ts'; +import { reserveTurnBudget } from '../sandbox/turn-budget.ts'; -/** - * An automation's `llm` step is a direct model call the organization pays - * for, made outside any sandbox session — so its run is its billing subject - * (`resolveAutomationRunAttribution`): the person who started the run, or - * `__automation__` for a run a trigger started, under the automation's - * name, with the key a keyed door used and the projects the run is in — - * what the run's agent steps book under too. - * - * Before each call the step is measured against every cap that binds that - * subject, counting what the work in flight holds, and refused once one is - * reached; after it, the tokens the provider reported are priced from the - * catalog and booked. The call holds nothing while it runs — one short - * request, like a chat title — so steps of runs at the same moment can - * pass a nearly reached cap together; their spend counts once booked. - */ +/** Every paid effect attempt owns one op; a resumed retry owns another. */ +export function llmStepOp(args: { + organizationId: string; + runId: string; + attempt: LlmAttemptAddress; +}): { sessionId: string; execId: string } { + const hash = (parts: unknown[]): string => + createHash('sha256').update(JSON.stringify(parts)).digest('hex'); + return { + sessionId: `automation-llm:${hash([args.organizationId, args.runId])}`, + execId: hash([ + args.organizationId, + args.runId, + args.attempt.nodeId, + args.attempt.itemIndex, + args.attempt.pass, + args.attempt.attempt, + ]), + }; +} -export type LlmStepAdmission = - | { allowed: true } - | { allowed: false; reason: string }; +export interface LlmStepReservation { + organizationId: string; + runId: string; + attempt: LlmAttemptAddress; + provider: string; + model: string; + reserveCents: number; + reserveTokens: number; +} -export async function checkLlmStepBudget( - sql: Sql, - args: { organizationId: string; runId: string }, -): Promise { - if (!(await budgetPolicyActive(sql, args.organizationId))) { - return { allowed: true }; +/** The same whole-request hold used by model API calls, with the subject + * and current durable effect attempt checked under the shared admission lock. */ +export async function reserveLlmStepBudget(sql: Sql, args: LlmStepReservation) { + if ( + !Number.isSafeInteger(args.reserveTokens) || + args.reserveTokens < 1 || + !Number.isFinite(args.reserveCents) || + args.reserveCents < 0 || + !Number.isSafeInteger(args.attempt.attempt) || + args.attempt.attempt < 1 || + !Number.isSafeInteger(args.attempt.itemIndex) || + !Number.isSafeInteger(args.attempt.pass) || + args.attempt.nodeId.length === 0 || + args.provider.length === 0 || + args.model.length === 0 + ) { + throw new Error('Invalid direct LLM reservation'); } - const subject = await loadAttributedBudgetSubject( - sql, - args.organizationId, - await resolveAutomationRunAttribution(sql, args), - ); - const violation = await findBudgetViolation(sql, subject, { - reservations: await readInFlightReservations(sql, subject), + const op = llmStepOp(args); + const allowance = await reserveTurnBudget(sql, { + organizationId: args.organizationId, + ...op, + kind: AUTOMATION_LLM_OP_KIND, + // The model-ref format has a connector and a gateway-provider prefix. + // Direct calls reuse that representation without creating a gateway. + modelRef: `${args.provider}/${args.provider}/${args.model}`, + defaultBudgetCents: Math.max(1, Math.ceil(args.reserveCents)), + whole: { prospectiveTokens: args.reserveTokens }, + prepareSubject: async (tx) => { + const live = await tx<{ id: string }[]>` + SELECT a.id FROM app.automation_node_attempts a + JOIN app.automation_runs r ON r.id = a.run_id AND r.org_id = a.org_id + WHERE a.org_id = ${args.organizationId} AND a.run_id = ${args.runId} + AND a.node_id = ${args.attempt.nodeId} + AND a.item_index = ${args.attempt.itemIndex} AND a.pass = ${args.attempt.pass} + AND a.attempt = ${args.attempt.attempt} AND a.kind = 'llm' + AND a.status = 'started' AND r.status = 'running' + AND a.claim_epoch = r.claim_epoch AND r.lease_epoch = r.claim_epoch + AND r.lease_expires_at_ms > ${Date.now()} + FOR SHARE OF a, r + `; + if (!live[0]) + throw new Error('The LLM effect attempt is no longer current'); + const prior = await tx<{ id: string }[]>` + SELECT id FROM app.sandbox_session_ops + WHERE session_id = ${op.sessionId} AND exec_id = ${op.execId} + `; + if (prior[0]) + throw new Error('The LLM effect attempt was already admitted'); + const subject = await resolveAutomationRunAttribution(tx, args); + if (subject === null) + throw new Error('The LLM run has no billing subject'); + return subject; + }, }); - return violation === null - ? { allowed: true } - : { allowed: false, reason: budgetRefusalMessage(violation) }; + return allowance.allowed ? { allowed: true as const, ...op } : allowance; } -/** One call's spend, as the provider reported it. */ export interface LlmStepUsage { organizationId: string; - runId: string; - /** The serving connector's slug and the catalog id it was called with — - * the pair the catalog prices. */ - provider: string; - model: string; - inputTokens: number; - outputTokens: number; + sessionId: string; + execId: string; + /** Null means the provider outcome is unknown, never a reported zero. */ + usage: { inputTokens: number; outputTokens: number; cents: number } | null; } +/** Persist terminal facts before attempting the idempotent shared settlement. + * On a DB failure the existing hold survives and the watchdog recovers it. */ export async function recordLlmStepUsage( sql: Sql, - usage: LlmStepUsage, + args: LlmStepUsage, ): Promise { - const attribution = await resolveAutomationRunAttribution(sql, usage); - if (attribution === null) { - console.error( - `[automations] run ${usage.runId} names no one to book its llm step to — ${usage.inputTokens} input and ${usage.outputTokens} output tokens of ${usage.provider}/${usage.model} are not booked`, - ); - return; + const usage = args.usage; + if ( + usage !== null && + (!Number.isSafeInteger(usage.inputTokens) || + usage.inputTokens < 0 || + !Number.isSafeInteger(usage.outputTokens) || + usage.outputTokens < 0 || + !Number.isFinite(usage.cents) || + usage.cents < 0) + ) { + throw new Error('Invalid direct LLM usage'); } - await createPgUsageLedger(sql).record({ - organizationId: usage.organizationId, - userId: attribution.userId, - ...(attribution.apiKeyId !== undefined - ? { apiKeyId: attribution.apiKeyId } - : {}), - ...(attribution.agentSlug !== undefined - ? { agentSlug: attribution.agentSlug } - : {}), - model: usage.model, - provider: usage.provider, - inputTokens: usage.inputTokens, - outputTokens: usage.outputTokens, - totalTokens: usage.inputTokens + usage.outputTokens, - ...(attribution.projectIds !== undefined - ? { projectIds: attribution.projectIds } - : {}), - }); + const now = Date.now(); + await sql` + UPDATE app.sandbox_session_ops SET + status = ${usage === null ? 'failed' : 'completed'}, + finalized_at_ms = ${now}, finished_at_ms = ${now}, + expected_cents = ${usage?.cents ?? null}, + input_tokens = ${usage?.inputTokens ?? null}, + output_tokens = ${usage?.outputTokens ?? null}, + settle_after_ms = CASE WHEN ${usage === null} + THEN started_at_ms + ${AUTOMATION_LLM_LIFETIME_MS} ELSE ${now} END + WHERE org_id = ${args.organizationId} AND session_id = ${args.sessionId} + AND exec_id = ${args.execId} AND kind = ${AUTOMATION_LLM_OP_KIND} + AND finalized_at_ms IS NULL AND spend_settled_at_ms IS NULL + `; + // Failure here leaves the persisted facts and hold for the existing sweep. + const outcome = await reconcileSessionOpKey(sql, args); + if (outcome === null) throw new Error('The direct LLM operation is missing'); } diff --git a/services/platform/backend/domains/automations/shim.test.ts b/services/platform/backend/domains/automations/shim.test.ts index 0eba54f324..67dd6390c8 100644 --- a/services/platform/backend/domains/automations/shim.test.ts +++ b/services/platform/backend/domains/automations/shim.test.ts @@ -74,7 +74,7 @@ describe('automationShimHandlers', () => { 'automations/human_asks:getPendingAskForExec', 'sandbox/session_mutations:upsertSessionOp', // The llm door's budget check and booking. - 'automations/queries:checkLlmStepBudget', + 'automations/mutations:reserveLlmStepBudget', 'automations/mutations:recordLlmStepUsage', ]), ); diff --git a/services/platform/backend/domains/automations/shim.ts b/services/platform/backend/domains/automations/shim.ts index 256a6f1f9f..8d701410f6 100644 --- a/services/platform/backend/domains/automations/shim.ts +++ b/services/platform/backend/domains/automations/shim.ts @@ -25,7 +25,7 @@ import { agentTurnShimHandlers } from '../tasks/agent-turn-shim.ts'; import { retractAskOnTask } from './ask-retraction.ts'; import { automationAskShimHandlers } from './ask-shim.ts'; import { - checkLlmStepBudget, + reserveLlmStepBudget, type LlmStepUsage, recordLlmStepUsage, } from './llm-metering.ts'; @@ -232,10 +232,10 @@ export function automationShimHandlers(sql: Sql): ShimHandlers { // An `llm` step's model call is its run's spend: measured against the // caps that bind the run before the call, booked after it. - 'automations/queries:checkLlmStepBudget': async (raw) => { + 'automations/mutations:reserveLlmStepBudget': async (raw) => { // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- shim boundary: the llm door passes exactly this shape - const args = raw as { organizationId: string; runId: string }; - return checkLlmStepBudget(sql, args); + const args = raw as Parameters[1]; + return reserveLlmStepBudget(sql, args); }, 'automations/mutations:recordLlmStepUsage': async (raw) => { // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- shim boundary: the llm door passes exactly this shape diff --git a/services/platform/backend/domains/chat/budget-admission.test.ts b/services/platform/backend/domains/chat/budget-admission.test.ts index a0c155bf29..c1b68399c4 100644 --- a/services/platform/backend/domains/chat/budget-admission.test.ts +++ b/services/platform/backend/domains/chat/budget-admission.test.ts @@ -148,6 +148,23 @@ describe('assertChatTurnBudget', () => { expect(statements[0]?.values).toEqual(['thread_in_project', 'org_1']); }); + it.each([{ projectIds: ['original-project'] }, { projectIds: [] }])( + 'measures the captured projects without following a moved thread: $projectIds [GOV-R14]', + async ({ projectIds }) => { + const threadSql = vi + .fn() + .mockResolvedValue([{ projectId: 'moved-project' }]); + await assertChatTurnBudget(threadSql as never, { + organizationId: 'org_1', + userId: 'user_1', + threadId: 'moved-thread', + projectIds, + }); + expect(gate.subjects).toEqual([expect.objectContaining({ projectIds })]); + expect(threadSql).not.toHaveBeenCalled(); + }, + ); + it('refuses a reached cap with BUDGET_EXCEEDED, naming the cap and its reset [CHAT-R6]', async () => { gate.violation = { scope: 'team', diff --git a/services/platform/backend/domains/chat/budget-admission.ts b/services/platform/backend/domains/chat/budget-admission.ts index 35c64622bf..4c559de000 100644 --- a/services/platform/backend/domains/chat/budget-admission.ts +++ b/services/platform/backend/domains/chat/budget-admission.ts @@ -86,6 +86,9 @@ export interface ChatTurnSender { userId: string; apiKeyId?: string; threadId?: string; + /** Captured request projects; absent for an early door check that must + * still resolve the thread's current project. */ + projectIds?: readonly string[]; } /** @@ -115,14 +118,18 @@ export async function assertChatTurnBudget( }, ): Promise { const projectId = - args.threadId !== undefined + args.projectIds === undefined && args.threadId !== undefined ? await readThreadProjectId(sql, args.organizationId, args.threadId) : undefined; const subject = await loadBudgetSubject(sql, { organizationId: args.organizationId, userId: args.userId, ...(args.apiKeyId !== undefined ? { apiKeyId: args.apiKeyId } : {}), - ...(projectId !== undefined ? { projectIds: [projectId] } : {}), + ...(args.projectIds !== undefined + ? { projectIds: args.projectIds } + : projectId !== undefined + ? { projectIds: [projectId] } + : {}), }); const violation = await findBudgetViolation(sql, subject, { reservations: await readInFlightReservations( diff --git a/services/platform/backend/domains/chat/shim.knowledge-scope.test.ts b/services/platform/backend/domains/chat/shim.knowledge-scope.test.ts index b6216e16f8..d6c845a8b1 100644 --- a/services/platform/backend/domains/chat/shim.knowledge-scope.test.ts +++ b/services/platform/backend/domains/chat/shim.knowledge-scope.test.ts @@ -10,11 +10,40 @@ */ import type { Sql } from 'postgres'; -import { describe, expect, it, vi } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { createChatToolExecutor } from '../../core/chat/assistant_tools.ts'; +import { searchKnowledge } from '../../core/knowledge/search.ts'; +import type { ActionCtx } from '../../core/lib/ctx.ts'; +import { dispatchWorkspaceToolImpl } from '../../core/node_only/sandbox/workspace_tools_bridge.ts'; +import { createCtxShim } from '../../lib/ctx-shim.ts'; import { listDocumentsForAgent } from '../documents/agent-list.ts'; +import { listEntriesForAgent } from '../knowledge_entries/service.ts'; +import { sandboxToolShimHandlers } from '../sandbox/shim.ts'; import { chatShimHandlers } from './shim.ts'; +vi.mock('../../core/knowledge/search.ts', () => ({ + searchKnowledge: vi.fn(() => Promise.resolve({ hits: [], diagnostics: {} })), +})); +vi.mock('../../core/lib/helpers/org_slug.ts', () => ({ + orgSlugFromId: () => Promise.resolve('acme'), +})); +vi.mock('../knowledge_entries/service.ts', () => ({ + listEntriesForAgent: vi.fn(() => + Promise.resolve({ + page: [ + { + _id: 'entry-org', + topic: 'Organization knowledge', + content: 'Shared organization fact', + }, + ], + isDone: true, + continueCursor: '', + }), + ), +})); + vi.mock('../documents/agent-list.ts', () => ({ listDocumentsForAgent: vi.fn(() => Promise.resolve({ @@ -45,13 +74,18 @@ vi.mock('../../auth/membership.ts', () => { // a project's own API key acting as a developer. const findActingMember = vi.fn( (sql: unknown, organizationId: string, userId: string) => - userId === 'u-project-key' + ['u-project-key', 'u-team-key', 'u-org-key'].includes(userId) ? Promise.resolve({ id: 'api-key:key-1', organizationId, userId, role: 'developer', - apiKeyOwner: { kind: 'project', projectId: 'proj-1' }, + apiKeyOwner: + userId === 'u-project-key' + ? { kind: 'project', projectId: 'proj-1' } + : userId === 'u-team-key' + ? { kind: 'team', teamId: 'team-a', projectId: null } + : { kind: 'organization', projectId: null }, }) : findOrganizationMember(sql, organizationId, userId), ); @@ -167,6 +201,7 @@ describe('a project’s own API key in the chat tools [APIKEY-R6]', () => { expect(await allowed('u-project-key', subject)).toBe(true); } for (const subject of [ + 'knowledge_entries', 'contacts', 'products', 'websites', @@ -204,3 +239,137 @@ describe('the chat turn knowledge scope', () => { } }); }); + +/** The real executor/bridge dispatch through the real SQL shim gates. Only + * storage/search edges and observation writes are substitutes; a refused + * dispatch must never reach the organization-wide entry reader. */ +function composedTools(userId: string) { + const sqlQuery = vi.fn(() => Promise.resolve([])); + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the SQL readers used here only need an empty row set; membership/project resolution is mocked above + const sql = sqlQuery as unknown as Sql; + const handlers = sandboxToolShimHandlers(sql); + const ctx = createCtxShim({ + ...handlers, + 'audit_logs/internal_mutations:createAuditLog': async () => null, + 'governance/internal_mutations:recordConnectorUsage': async () => null, + 'sandbox/session_mutations:recordToolCall': async () => null, + }); + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- production uses this same shim for the ActionCtx query/mutation/action surface + const actionCtx = ctx as unknown as ActionCtx; + return { + chat: createChatToolExecutor(actionCtx, { + organizationId: 'org-1', + userId, + projectId: 'proj-1', + }), + find: (tool: string) => + dispatchWorkspaceToolImpl(actionCtx, { + organizationId: 'org-1', + sessionId: 'user-session', + userId, + tool, + callArgs: {}, + }), + }; +} + +describe('composed project-key knowledge tools [APIKEY-R6]', () => { + beforeEach(() => vi.clearAllMocks()); + + it.each([ + { query: 'Organization knowledge' }, + { query: 'Organization knowledge', kind: 'knowledge-entry' }, + ])( + 'refuses organization entries in search %j before their reader', + async (input) => { + const result = await composedTools('u-project-key').chat.execute({ + id: 'search', + name: 'rag_search', + input, + }); + expect(result).toMatchObject({ + status: 'ok', + results: [], + sources: { knowledgeEntries: 'access denied for your role' }, + }); + expect(listEntriesForAgent).not.toHaveBeenCalled(); + }, + ); + + it('refuses organization-entry listing before its reader', async () => { + const result = await composedTools('u-project-key').chat.execute({ + id: 'list', + name: 'rag_search', + input: { action: 'list', kind: 'knowledge-entry' }, + }); + expect(result).toMatchObject({ status: 'unavailable' }); + expect(listEntriesForAgent).not.toHaveBeenCalled(); + }); + + it('refuses the sandbox entry finder through the real session fallback', async () => { + expect( + await composedTools('u-project-key').find('knowledge_entry_find'), + ).toMatchObject({ status: 'unavailable' }); + expect(listEntriesForAgent).not.toHaveBeenCalled(); + }); + + it('keeps project document search and listing scoped and available', async () => { + const tools = composedTools('u-project-key'); + expect( + await tools.chat.execute({ + id: 'documents', + name: 'rag_search', + input: { query: 'launch budget', kind: 'document' }, + }), + ).toMatchObject({ status: 'ok' }); + expect(searchKnowledge).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + access: expect.objectContaining({ + projectIds: ['proj-1'], + includeHub: false, + }), + }), + ); + expect( + await tools.chat.execute({ + id: 'document-list', + name: 'rag_search', + input: { action: 'list', kind: 'document' }, + }), + ).toMatchObject({ status: 'ok' }); + expect(await tools.find('document_find')).toMatchObject({ status: 'ok' }); + expect(listDocumentsForAgent).toHaveBeenCalledTimes(2); + for (const [, args] of vi.mocked(listDocumentsForAgent).mock.calls) { + expect(args).toMatchObject({ projectIds: ['proj-1'] }); + expect(args).not.toHaveProperty('includeHub'); + } + expect(listEntriesForAgent).not.toHaveBeenCalled(); + }); + + it.each(['u-1', 'u-team-key', 'u-org-key'])( + 'preserves authorized search, listing and sandbox entry reads for %s', + async (userId) => { + const tools = composedTools(userId); + for (const input of [ + { query: 'Organization knowledge', kind: 'knowledge-entry' }, + { action: 'list', kind: 'knowledge-entry' }, + ]) { + expect( + await tools.chat.execute({ + id: 'allowed', + name: 'rag_search', + input, + }), + ).toMatchObject({ + status: 'ok', + results: [expect.objectContaining({ kind: 'knowledge-entry' })], + }); + } + expect(await tools.find('knowledge_entry_find')).toMatchObject({ + status: 'ok', + }); + expect(listEntriesForAgent).toHaveBeenCalledTimes(3); + }, + ); +}); diff --git a/services/platform/backend/domains/chat/shim.ts b/services/platform/backend/domains/chat/shim.ts index 91057b63fa..87cff1a449 100644 --- a/services/platform/backend/domains/chat/shim.ts +++ b/services/platform/backend/domains/chat/shim.ts @@ -192,7 +192,8 @@ const WEBSITE_SUMMARY_CAP = 200; /** What a project's own API key may read through the chat tools: the * subjects its access scope narrows to its project. Contacts, products, - * websites and the inbox are the organization's, never one project's. */ + * websites, knowledge entries and the inbox are the organization's, never + * one project's. */ const PROJECT_KEY_READ_SUBJECTS: ReadonlySet = new Set([ 'documents', 'tasks', diff --git a/services/platform/backend/domains/chat/store.test.ts b/services/platform/backend/domains/chat/store.test.ts index 339e317312..397daa7f22 100644 --- a/services/platform/backend/domains/chat/store.test.ts +++ b/services/platform/backend/domains/chat/store.test.ts @@ -312,7 +312,12 @@ describe('createPgTurnStore.beginTurn admission exclusion', () => { }); expect(budget.admitChatTurnSpend).toHaveBeenCalledWith( expect.anything(), - { organizationId: 'org_1', userId: 'user_1', threadId: 'thread_1' }, + { + organizationId: 'org_1', + userId: 'user_1', + threadId: 'thread_1', + projectIds: [], + }, { threadId: 'thread_b' }, ); expect(f.transactions).toEqual(['commit']); @@ -327,7 +332,12 @@ describe('createPgTurnStore.beginTurn admission exclusion', () => { }); expect(budget.admitChatTurnSpend).toHaveBeenCalledWith( expect.anything(), - { organizationId: 'org_1', userId: 'user_1', threadId: 'thread_1' }, + { + organizationId: 'org_1', + userId: 'user_1', + threadId: 'thread_1', + projectIds: [], + }, undefined, ); }); @@ -445,6 +455,7 @@ describe('createPgTurnStore.beginTurn', () => { const SPEND = { userId: 'user_1', + projectIds: ['original-project'], apiKeyId: 'key_1', tokens: 4_096.4, costCents: 12.5, @@ -459,7 +470,13 @@ describe('createPgTurnStore.beginTurn', () => { ); expect(claim?.text).toContain('user_id, api_key_id, reserved_cost_cents,'); expect(claim?.values).toEqual( - expect.arrayContaining(['user_1', 'key_1', 12.5, 4_097]), + expect.arrayContaining([ + 'user_1', + 'key_1', + 12.5, + 4_097, + ['original-project'], + ]), ); // No budget policy is on: nothing to serialize, no admission. expect(budget.budgetPolicyActive).toHaveBeenCalledWith(f.sql, 'org_1'); @@ -483,6 +500,7 @@ describe('createPgTurnStore.beginTurn', () => { userId: 'user_1', apiKeyId: 'key_1', threadId: 'thread_1', + projectIds: ['original-project'], }, // No partner column to leave out of the measure on an ordinary open. undefined, @@ -517,7 +535,7 @@ describe('createPgTurnStore.beginTurn', () => { const claim = f.tx.find((statement) => statement.text.includes('INSERT INTO app.generations'), ); - expect(claim?.values.slice(-4)).toEqual([null, null, 0, 0]); + expect(claim?.values.slice(-5)).toEqual([null, null, 0, 0, []]); }); }); diff --git a/services/platform/backend/domains/chat/store.ts b/services/platform/backend/domains/chat/store.ts index 0b67b8f490..c1c18c8b09 100644 --- a/services/platform/backend/domains/chat/store.ts +++ b/services/platform/backend/domains/chat/store.ts @@ -445,6 +445,7 @@ function pgTurnStore( ? { apiKeyId: admission.apiKeyId } : {}), threadId: setup.threadId, + projectIds: admission.projectIds ?? [], }, admissionExclude, ); @@ -492,12 +493,13 @@ function pgTurnStore( INSERT INTO app.generations ( thread_id, org_id, message_id, started_at_ms, heartbeat_at_ms, updated_at_ms, user_id, api_key_id, reserved_cost_cents, - reserved_tokens + reserved_tokens, project_ids ) VALUES ( ${setup.threadId}, ${setup.organizationId}, ${assistantMessage.id}, ${now}, ${now}, ${now}, ${setup.spend?.userId ?? null}, ${setup.spend?.apiKeyId ?? null}, ${setup.spend?.costCents ?? 0}, - ${Math.ceil(setup.spend?.tokens ?? 0)} + ${Math.ceil(setup.spend?.tokens ?? 0)}, + ${[...(setup.spend?.projectIds ?? [])]} ) ON CONFLICT (thread_id) DO NOTHING RETURNING thread_id AS "threadId" diff --git a/services/platform/backend/domains/chat/threads.test.ts b/services/platform/backend/domains/chat/threads.test.ts index 5b2d9d6779..202bd5334e 100644 --- a/services/platform/backend/domains/chat/threads.test.ts +++ b/services/platform/backend/domains/chat/threads.test.ts @@ -48,6 +48,7 @@ import { projectSharedViewLeaf, searchChats, setThreadArchived, + setThreadSharedWithProject, shareThread, unshareThread, trashThread, @@ -692,7 +693,20 @@ describe('moveThreadToProject [CHAT-R3]', () => { }, ) => (statement: Statement): unknown[] | undefined => { - if (statement.text.includes('FROM app.threads t')) return [row]; + if (statement.text.includes('FROM app.threads t')) { + // The branch and its canonical root are separate owned rows. + return [ + row.branchRootId !== null && + statement.values.includes(row.branchRootId) + ? { + ...row, + id: row.branchRootId, + branchRootId: null, + hidden: false, + } + : row, + ]; + } if (statement.text.includes('FROM app.projects WHERE id')) { // The access read selects the audience (`PROJECT_TEAM_IDS_SQL`, // bound as a value by the stand-in's `unsafe`); the other read is @@ -801,13 +815,120 @@ describe('moveThreadToProject [CHAT-R3]', () => { const lineage = statements.find((s) => s.text.includes('OR branch_root_id = ?'), ); + expect(lineage?.text).toContain('project_id = ?'); + expect(lineage?.text).toContain( + 'shared_with_project = CASE WHEN project_id IS DISTINCT FROM ?', + ); expect(lineage?.text).toContain( - 'UPDATE app.thread_metadata SET project_id = ?', + 'THEN false ELSE shared_with_project END', ); - expect(lineage?.values).toEqual(['project_b', 'org_1', rootId, rootId]); + expect(lineage?.values).toEqual([ + 'project_b', + 'project_b', + 'org_1', + 'user_1', + rootId, + rootId, + ]); } }); + it('a hidden sibling refile clears the root audience and audits the root, not the private sibling [CHAT-R3] [GOV-R14]', async () => { + const branch = { + ...OWNED_ROW, + id: 'branch_2', + branchRootId: 'thread_1', + hidden: true, + sharedWithProject: false, + }; + const { sql, statements } = fakeSql((statement) => { + if (statement.text.includes('FROM app.threads t')) { + return statement.values.includes(branch.id) ? [branch] : [OWNED_ROW]; + } + return answering(OWNED_ROW)(statement); + }); + await expect( + moveThreadToProject(sql, auth, branch.id, 'project_b'), + ).resolves.toBe(true); + const ownedReads = statements.filter((statement) => + statement.text.includes('FROM app.threads t'), + ); + expect(ownedReads).toHaveLength(2); + expect(JSON.stringify(ownedReads[1])).toContain('FOR UPDATE'); + expect(ownedReads[1]?.values).toEqual( + expect.arrayContaining(['thread_1', 'org_1', 'user_1']), + ); + const rootUpdate = statements.find((statement) => + statement.text.includes('UPDATE app.thread_metadata'), + ); + expect(rootUpdate?.values).toEqual(['project_b', false, 'thread_1']); + const lineage = statements.find((statement) => + statement.text.includes('OR branch_root_id = ?'), + ); + expect(lineage?.text).toContain('shared_with_project'); + expect(createAuditLog).toHaveBeenCalledTimes(2); + expect(createAuditLog.mock.calls[0]?.[1]).toMatchObject({ + action: 'project.thread.unshared', + resourceId: 'project_a', + previousState: { threadId: 'thread_1', shared: true }, + newState: { + threadId: 'thread_1', + shared: false, + movedToProjectId: 'project_b', + }, + }); + expect(createAuditLog.mock.calls[1]?.[1]).toMatchObject({ + action: 'project.thread.moved', + resourceId: 'project_b', + previousState: { threadId: 'thread_1', projectId: 'project_a' }, + newState: { threadId: 'thread_1', projectId: 'project_b' }, + }); + }); + + it('a sibling cannot refile a root absent from the same owner and organization [CHAT-R1] [CHAT-R3]', async () => { + const branch = { + ...OWNED_ROW, + id: 'branch_2', + branchRootId: 'thread_1', + hidden: true, + }; + const { sql, statements } = fakeSql((statement) => { + if (statement.text.includes('FROM app.threads t')) + return statement.values.includes(branch.id) ? [branch] : []; + return answering(OWNED_ROW)(statement); + }); + await expect( + moveThreadToProject(sql, auth, branch.id, 'project_b'), + ).resolves.toBe(false); + expect( + statements.some((statement) => statement.text.includes('UPDATE')), + ).toBe(false); + expect(createAuditLog).not.toHaveBeenCalled(); + }); + + it('a sibling refile to the same root project preserves its existing share and emits no move audit [CHAT-R3]', async () => { + const branch = { + ...OWNED_ROW, + id: 'branch_2', + branchRootId: 'thread_1', + hidden: true, + sharedWithProject: false, + }; + const { sql, statements } = fakeSql((statement) => { + if (statement.text.includes('FROM app.threads t')) + return statement.values.includes(branch.id) ? [branch] : [OWNED_ROW]; + return answering(OWNED_ROW)(statement); + }); + await expect( + moveThreadToProject(sql, auth, branch.id, 'project_a'), + ).resolves.toBe(true); + const update = statements.find((statement) => + statement.text.includes('UPDATE app.thread_metadata'), + ); + expect(update?.values).toEqual(['project_a', true, 'thread_1']); + expect(createAuditLog).not.toHaveBeenCalled(); + }); + it('audits filing an unfiled thread into a project, on that project', async () => { const { sql } = fakeSql( answering({ ...OWNED_ROW, projectId: null, sharedWithProject: false }), @@ -823,6 +944,74 @@ describe('moveThreadToProject [CHAT-R3]', () => { }); }); +describe('setThreadSharedWithProject locked audience [CHAT-R2] [CHAT-R3]', () => { + const auth = { organizationId: 'org_1', userId: 'user_1' }; + + it.each([true, false])( + 'locks and reads the current project before setting shared=%s and auditing', + async (shared) => { + const { sql, statements } = fakeSql((statement) => { + if (statement.text.includes('FROM app.threads t')) { + // A stale unlocked read would still see A. A refile already committed + // before this metadata lock, so the protected read must see B. + return [ + { + ...OWNED_ROW, + projectId: JSON.stringify(statement).includes('FOR UPDATE') + ? 'project_b' + : 'project_a', + }, + ]; + } + if (statement.text.includes('FROM app.projects WHERE id')) + return [{ name: 'Project B' }]; + return []; + }); + await expect( + setThreadSharedWithProject(sql, auth, 'thread_1', shared), + ).resolves.toBe(true); + const owned = statements.find((statement) => + statement.text.includes('FROM app.threads t'), + ); + expect(JSON.stringify(owned)).toContain('FOR UPDATE'); + const update = statements.find((statement) => + statement.text.includes('UPDATE app.thread_metadata'), + ); + expect(update?.values).toEqual([shared, 'thread_1']); + expect(createAuditLog).toHaveBeenCalledOnce(); + expect(createAuditLog.mock.calls[0]?.[1]).toMatchObject({ + action: shared ? 'project.thread.shared' : 'project.thread.unshared', + resourceId: 'project_b', + newState: { threadId: 'thread_1', shared }, + }); + }, + ); + + it('refuses a missing owned thread without a sharing write or audit', async () => { + const { sql, statements } = fakeSql(() => []); + await expect( + setThreadSharedWithProject(sql, auth, 'thread_1', true), + ).resolves.toBe(false); + expect( + statements.some((statement) => statement.text.includes('UPDATE')), + ).toBe(false); + expect(createAuditLog).not.toHaveBeenCalled(); + }); + + it('refuses a currently unfiled thread after acquiring its metadata lock', async () => { + const { sql, statements } = fakeSql(() => [ + { ...OWNED_ROW, projectId: null }, + ]); + await expect( + setThreadSharedWithProject(sql, auth, 'thread_1', true), + ).rejects.toThrow('File the conversation in a project first'); + expect( + statements.some((statement) => statement.text.includes('UPDATE')), + ).toBe(false); + expect(createAuditLog).not.toHaveBeenCalled(); + }); +}); + /** * The palette search reads the transcript the user reads: an edit or * regenerate lands on a HIDDEN sibling that never graduates, so the message @@ -982,9 +1171,12 @@ describe('the project share read grant [CHAT-R2]', () => { userId: 'user_1', }), ).resolves.toBe('thread_sibling'); - // The lineage is read as the OWNER — the reader never holds it. + // The lineage is read as the OWNER — the reader never holds it. The + // fake tag retains the static unsafe lock suffix as one extra value; + // this read deliberately has no metadata lock. const owned = statements.find(({ text }) => isOwnedRead(text)); - expect(owned?.values.slice(1)).toEqual(['thread_1', 'org_1', 'user_1']); + expect(owned?.values.slice(1, 4)).toEqual(['thread_1', 'org_1', 'user_1']); + expect(owned?.values.slice(4)).toEqual(['']); }); it('serves the root itself while nothing is selected away from it', async () => { diff --git a/services/platform/backend/domains/chat/threads.ts b/services/platform/backend/domains/chat/threads.ts index 5621d059ec..369d9c6acf 100644 --- a/services/platform/backend/domains/chat/threads.ts +++ b/services/platform/backend/domains/chat/threads.ts @@ -222,6 +222,8 @@ export async function loadOwnedThread( organizationId: string, userId: string, threadId: string, + /** Only inside a caller-owned transaction when changing project sharing. */ + lockMetadata = false, ): Promise { const rows = await sql` SELECT ${sql.unsafe(THREAD_COLUMNS)} @@ -229,7 +231,7 @@ export async function loadOwnedThread( JOIN app.thread_metadata tm ON tm.thread_id = t.id WHERE t.id = ${threadId} AND t.org_id = ${organizationId} AND t.user_id = ${userId} AND tm.status = 'active' - LIMIT 1 + LIMIT 1 ${sql.unsafe(lockMetadata ? 'FOR UPDATE OF tm' : '')} `; return rows[0] ?? null; } @@ -506,13 +508,13 @@ export async function moveThreadToProject( threadId: string, projectId: string | null, ): Promise { - const thread = await loadOwnedThread( + const selected = await loadOwnedThread( sql, auth.organizationId, auth.userId, threadId, ); - if (!thread) return false; + if (!selected) return false; if (projectId !== null) { const access = await projectChatAccess(sql, { projectId, @@ -527,11 +529,22 @@ export async function moveThreadToProject( ); } } - const previousProjectId = thread.projectId; - const moved = projectId !== previousProjectId; - const endsShare = - moved && thread.sharedWithProject === true && previousProjectId !== null; - await sql.begin(async (tx) => { + return sql.begin(async (tx) => { + // The opt-in and audit belong to the canonical root, even when an API + // caller names its hidden sibling. Re-read after locking so another + // move cannot leave us interpreting an old audience or share flag. + const thread = await loadOwnedThread( + tx, + auth.organizationId, + auth.userId, + selected.branchRootId ?? selected.id, + true, + ); + if (!thread || thread.branchRootId !== null) return false; + const previousProjectId = thread.projectId; + const moved = projectId !== previousProjectId; + const endsShare = + moved && thread.sharedWithProject === true && previousProjectId !== null; await tx` UPDATE app.thread_metadata SET project_id = ${projectId}, @@ -542,13 +555,15 @@ export async function moveThreadToProject( // an arena column — carry its later turns: they move with it, or a turn // on one would keep spending in, and being capped by, the project the // conversation left. - const rootId = thread.branchRootId ?? thread.id; await tx` - UPDATE app.thread_metadata SET project_id = ${projectId} - WHERE org_id = ${auth.organizationId} - AND (thread_id = ${rootId} OR branch_root_id = ${rootId}) + UPDATE app.thread_metadata SET + shared_with_project = CASE WHEN project_id IS DISTINCT FROM ${projectId} + THEN false ELSE shared_with_project END, + project_id = ${projectId} + WHERE org_id = ${auth.organizationId} AND user_id = ${auth.userId} + AND (thread_id = ${thread.id} OR branch_root_id = ${thread.id}) `; - if (!moved) return; + if (!moved) return true; const projectName = async (id: string): Promise => { const rows = await tx<{ name: string }[]>` SELECT name FROM app.projects WHERE id = ${id} LIMIT 1 @@ -583,7 +598,7 @@ export async function moveThreadToProject( // off the project the chat lands in (or the one it leaves, when it is // taken out of projects altogether). const anchorProjectId = projectId ?? previousProjectId; - if (anchorProjectId === null) return; + if (anchorProjectId === null) return true; const anchorName = await projectName(anchorProjectId); await createAuditLog(tx, { ...actor, @@ -593,8 +608,8 @@ export async function moveThreadToProject( previousState: { threadId: thread.id, projectId: previousProjectId }, newState: { threadId: thread.id, projectId }, }); + return true; }); - return true; } /** The header cap on a chat name — mirrors the AI title generator's own. */ @@ -865,20 +880,21 @@ export async function setThreadSharedWithProject( threadId: string, shared: boolean, ): Promise { - const thread = await loadOwnedThread( - sql, - auth.organizationId, - auth.userId, - threadId, - ); - if (!thread) return false; - if (thread.projectId === null) { - throw new ChatThreadError( - 'THREAD_NOT_IN_PROJECT', - 'File the conversation in a project first', + return sql.begin(async (tx) => { + const thread = await loadOwnedThread( + tx, + auth.organizationId, + auth.userId, + threadId, + true, ); - } - await sql.begin(async (tx) => { + if (!thread) return false; + if (thread.projectId === null) { + throw new ChatThreadError( + 'THREAD_NOT_IN_PROJECT', + 'File the conversation in a project first', + ); + } await tx` UPDATE app.thread_metadata SET shared_with_project = ${shared} WHERE thread_id = ${thread.id} @@ -903,8 +919,8 @@ export async function setThreadSharedWithProject( newState: { threadId: thread.id, shared }, }); } + return true; }); - return true; } /** diff --git a/services/platform/backend/domains/erasure/receipt-status.test.ts b/services/platform/backend/domains/erasure/receipt-status.test.ts index b17c95f9c8..f0497d4e8a 100644 --- a/services/platform/backend/domains/erasure/receipt-status.test.ts +++ b/services/platform/backend/domains/erasure/receipt-status.test.ts @@ -21,6 +21,14 @@ describe('erasureReceiptStatus', () => { // stopped halfway, which is the Art 19 confirmation the subject reads. expect(erasureReceiptStatus([], ['documents'])).toBe('partial'); }); + + test('preserved legacy automation runs keep an otherwise clean receipt partial [ERASE-R9]', () => { + expect(erasureReceiptStatus([], [], 1)).toBe('partial'); + expect(erasureReceiptError([], [], 1)).toBe('legacy_automation_hold'); + expect(erasureReceiptError(['uploads'], ['documents'], 2)).toBe( + 'failed passes: uploads; held off by a legal hold: documents; legacy_automation_hold', + ); + }); }); describe('erasureReceiptError', () => { diff --git a/services/platform/backend/domains/erasure/service.lifecycle.test.ts b/services/platform/backend/domains/erasure/service.lifecycle.test.ts index 32bd45530e..f955cfbaf7 100644 --- a/services/platform/backend/domains/erasure/service.lifecycle.test.ts +++ b/services/platform/backend/domains/erasure/service.lifecycle.test.ts @@ -442,7 +442,7 @@ describe('processErasure', () => { s.text.startsWith('DELETE FROM app.automation_runs'), ); expect(runs?.text).toBe( - 'DELETE FROM app.automation_runs WHERE org_id = ? AND started_by = ANY(?) RETURNING id', + 'DELETE FROM app.automation_runs WHERE org_id = ? AND started_by = ANY(?) AND legacy_quarantine IS NULL RETURNING id', ); expect(runs?.values).toEqual([ 'org_1', @@ -456,6 +456,69 @@ describe('processErasure', () => { expect(settle?.values[2]).toMatchObject({ automationRuns: 3 }); }); + it('deletes unheld runs while preserving and reporting legacy-held subject runs [ERASE-R9]', async () => { + vi.mocked(loadActiveHolds).mockResolvedValue(noHolds); + const fake = fakeSql((text, values) => { + if ( + text.startsWith( + "UPDATE app.gdpr_erasure_requests SET status = 'running'", + ) + ) + return [ + { + organizationId: 'org_1', + targetUserId: 'subject', + status: 'running', + }, + ]; + if ( + text.includes('FROM app.automation_runs') && + text.startsWith('SELECT') + ) { + expect(text).toContain('legacy_quarantine IS NOT NULL'); + expect(values).toEqual([ + 'org_1', + ['user:subject', 'api-key:subject', 'subject'], + ]); + return [{ count: 1 }]; + } + if (text.startsWith('DELETE FROM app.automation_runs')) { + if (!text.includes('legacy_quarantine IS NULL')) + throw Object.assign(new Error('held run cannot be deleted'), { + code: 'P7502', + }); + expect(values).toEqual([ + 'org_1', + ['user:subject', 'api-key:subject', 'subject'], + ]); + return [{ id: 'unheld-run' }]; + } + if (text.startsWith('SELECT EXISTS')) return [{ elsewhere: false }]; + return undefined; + }); + await processErasure(fake.sql, 'req-1'); + const settle = fake.statements.find( + (s) => + s.text.startsWith('UPDATE app.gdpr_erasure_requests SET status = ?') && + s.text.includes('counts = ?'), + ); + expect(settle?.values[0]).toBe('partial'); + expect(settle?.values[2]).toMatchObject({ + automationRuns: { rows: 1, skippedByHold: 1 }, + }); + expect(settle?.values[3]).toBe('legacy_automation_hold'); + expect( + fake.statements.some((s) => + s.text.startsWith('UPDATE app.project_agent_runs'), + ), + ).toBe(true); + expect( + fake.statements.some((s) => + s.text.includes('automation_legacy_stop_run'), + ), + ).toBe(false); + }); + /** * A request through the model endpoints for API keys is an op row stamped * with the key holder. One whose spend is booked and whose key is deleted @@ -463,7 +526,7 @@ describe('processErasure', () => { * for the settlement — deleting it would orphan the key and drop the spend * from the organization's usage — and loses the identity instead. */ - it('deletes the settled model-endpoint request rows of the subject and pseudonymises the ones in flight [ERASE-R5]', async () => { + it('deletes settled model API and direct automation requests and pseudonymises the ones in flight [ERASE-R5]', async () => { vi.mocked(loadActiveHolds).mockResolvedValue(noHolds); const fake = fakeSql((text) => { if ( @@ -493,22 +556,29 @@ describe('processErasure', () => { const removed = fake.statements[indexOf('DELETE FROM app.sandbox_session_ops')]; expect(removed?.text).toBe( - 'DELETE FROM app.sandbox_session_ops WHERE org_id = ? AND kind = ? AND user_id = ? AND spend_settled_at_ms IS NOT NULL AND (key_revoked_at_ms IS NOT NULL OR minted_key_id IS NULL) RETURNING id', + 'DELETE FROM app.sandbox_session_ops WHERE org_id = ? AND kind = ANY(?) AND user_id = ? AND spend_settled_at_ms IS NOT NULL AND (key_revoked_at_ms IS NOT NULL OR minted_key_id IS NULL) RETURNING id', ); - expect(removed?.values).toEqual(['org_1', 'model-api', 'subject']); + expect(removed?.values).toEqual([ + 'org_1', + ['model-api', 'automation-llm'], + 'subject', + ]); const pseudonymised = fake.statements[indexOf('UPDATE app.sandbox_session_ops')]; // Every row of the subject the delete left — no settlement predicate, so // a row that settled in between cannot keep the subject's id. expect(pseudonymised?.text).toBe( - 'UPDATE app.sandbox_session_ops SET user_id = ? WHERE org_id = ? AND kind = ? AND user_id = ? RETURNING id', + 'UPDATE app.sandbox_session_ops SET user_id = ? WHERE org_id = ? AND kind = ANY(?) AND user_id = ? RETURNING id', ); expect(pseudonymised?.values).toEqual([ 'erased-user', 'org_1', - 'model-api', + ['model-api', 'automation-llm'], 'subject', ]); + expect(indexOf('DELETE FROM app.sandbox_session_ops')).toBeGreaterThan( + indexOf('DELETE FROM app.automation_runs'), + ); // The delete first, then the pseudonym — both before the ledger pass, // so a request settling mid-cascade books either before the ledger is // cleared or under the pseudonym, never under the subject afterwards. @@ -527,6 +597,110 @@ describe('processErasure', () => { expect(settle?.values[2]).toMatchObject({ modelApiRequests: 3 }); }); + it.each(['automationRuns', 'modelApiRequests'] as const)( + 'keeps dependent identity and ledger passes retryable after %s fails [ERASE-R5]', + async (failedPass) => { + vi.mocked(loadActiveHolds).mockResolvedValue(noHolds); + const failedPrefix = + failedPass === 'automationRuns' + ? 'DELETE FROM app.automation_runs' + : 'UPDATE app.sandbox_session_ops'; + const fake = fakeSql((text) => { + if ( + text.startsWith( + "UPDATE app.gdpr_erasure_requests SET status = 'running'", + ) + ) + return [ + { + organizationId: 'org_1', + targetUserId: 'subject', + status: 'running', + }, + ]; + if (text.startsWith(failedPrefix)) + throw new Error('fixture pass failed'); + if (text.startsWith('SELECT EXISTS')) return [{ elsewhere: false }]; + return undefined; + }); + await processErasure(fake.sql, 'req-1'); + expect( + fake.statements.some((statement) => + statement.text.startsWith('DELETE FROM app.usage_ledger'), + ), + ).toBe(false); + if (failedPass === 'automationRuns') + expect( + fake.statements.some((statement) => + statement.text.includes('app.sandbox_session_ops'), + ), + ).toBe(false); + const receipt = fake.statements.find( + (statement) => + statement.text.startsWith( + 'UPDATE app.gdpr_erasure_requests SET status = ?', + ) && statement.text.includes('counts = ?'), + ); + expect(receipt?.values[0]).toBe('partial'); + expect(receipt?.values[3]).toContain(failedPass); + expect(receipt?.values[3]).toContain('usageLedger'); + }, + ); + + it.each(['automationRuns', 'modelApiRequests'] as const)( + 'keeps the personal ledger when a hold skips prerequisite %s [ERASE-R1]', + async (heldPass) => { + let holdNext = false; + vi.mocked(loadActiveHolds).mockImplementation(async () => { + if (!holdNext) return noHolds; + holdNext = false; + return { orgHeld: false, userMembershipIds: new Set(['subject']) }; + }); + const precedingPrefix = + heldPass === 'automationRuns' + ? 'DELETE FROM app.memories' + : 'DELETE FROM app.automation_runs'; + const fake = fakeSql((text) => { + if ( + text.startsWith( + "UPDATE app.gdpr_erasure_requests SET status = 'running'", + ) + ) + return [ + { + organizationId: 'org_1', + targetUserId: 'subject', + status: 'running', + }, + ]; + if (text.startsWith(precedingPrefix)) holdNext = true; + if (text.startsWith('SELECT EXISTS')) return [{ elsewhere: false }]; + return undefined; + }); + await processErasure(fake.sql, 'req-1'); + expect( + fake.statements.some((statement) => + statement.text.includes('app.sandbox_session_ops'), + ), + ).toBe(false); + expect( + fake.statements.some((statement) => + statement.text.startsWith('DELETE FROM app.usage_ledger'), + ), + ).toBe(false); + const receipt = fake.statements.find( + (statement) => + statement.text.startsWith( + 'UPDATE app.gdpr_erasure_requests SET status = ?', + ) && statement.text.includes('counts = ?'), + ); + expect(receipt?.values[0]).toBe('partial'); + expect(receipt?.values[3]).toContain( + `held off by a legal hold: ${heldPass}`, + ); + }, + ); + it('holds the model-endpoint requests pass off like any other while a hold binds the subject [ERASE-R1]', async () => { // The first hold read (the cascade's gate) passes; every per-pass // re-read finds the subject held, so no pass touches a row. @@ -954,6 +1128,45 @@ describe('getErasureRequest — the blocked receipt re-checks the hold [ERASE-R2 }); }); + it.each([ + { + threads: 2, + documents: 3, + automationRuns: 1, + }, + { + threads: { rows: 2, skippedByHold: 4 }, + documents: { rows: 3, skippedByHold: 5 }, + automationRuns: { rows: 1, skippedByHold: 6 }, + }, + ])( + 'keeps summary erased counts consistent with the breakdown [ERASE-R9]', + async (counts) => { + const fake = fakeSql((text) => + text.startsWith('SELECT id, target_user_id') + ? [ + { + ...blockedRow('legacy_automation_hold'), + status: 'partial', + counts, + }, + ] + : [], + ); + + const detail = await getErasureRequest(fake.sql, 'org_1', 'req-1'); + + expect(detail?.request).toMatchObject({ + threadsErased: 2, + documentsErased: 3, + wfExecutionsErased: 1, + threadsSkippedByHold: typeof counts.threads === 'number' ? 0 : 4, + documentsSkippedByHold: typeof counts.documents === 'number' ? 0 : 5, + perCategorySnapshot: counts, + }); + }, + ); + it('does not check holds for a receipt that is not blocked', async () => { const fake = fakeSql((text) => text.startsWith('SELECT id, target_user_id') diff --git a/services/platform/backend/domains/erasure/service.ts b/services/platform/backend/domains/erasure/service.ts index 62feb7668a..24c601f43a 100644 --- a/services/platform/backend/domains/erasure/service.ts +++ b/services/platform/backend/domains/erasure/service.ts @@ -3,10 +3,13 @@ import type { Sql, TransactionSql } from 'postgres'; import { isRecord } from '../../../lib/utils/type-utils.ts'; import { isAdminRole } from '../../auth/membership.ts'; +import { AUTOMATION_LLM_OP_KIND } from '../../core/automations/llm_budget.ts'; import { + ERASURE_LEGACY_AUTOMATION_HOLD, ERASURE_REASON_CODES, ERASURE_WATCHDOG_TIMEOUT_MESSAGE, } from '../../core/governance/erasure_constants.ts'; +import { foldBreakdownEntries } from '../../core/governance/erasure_counts.ts'; import { normalizeAuthEmail } from '../../core/lib/auth/normalize_auth_email.ts'; import { parseBlobRef } from '../../core/lib/storage/blob_ref.ts'; import { MODEL_API_OP_KIND } from '../../core/sandbox/session_constants.ts'; @@ -703,8 +706,11 @@ async function scrubSubjectAuditLogs( export function erasureReceiptStatus( failedPasses: readonly string[], heldOffPasses: readonly string[], + legacyHeldAutomationRuns = 0, ): 'done' | 'partial' { - return failedPasses.length === 0 && heldOffPasses.length === 0 + return failedPasses.length === 0 && + heldOffPasses.length === 0 && + legacyHeldAutomationRuns === 0 ? 'done' : 'partial'; } @@ -739,6 +745,7 @@ export function erasureHoldBlock( export function erasureReceiptError( failedPasses: readonly string[], heldOffPasses: readonly string[], + legacyHeldAutomationRuns = 0, ): string | null { const parts: string[] = []; if (failedPasses.length > 0) { @@ -747,6 +754,7 @@ export function erasureReceiptError( if (heldOffPasses.length > 0) { parts.push(`held off by a legal hold: ${heldOffPasses.join(', ')}`); } + if (legacyHeldAutomationRuns > 0) parts.push(ERASURE_LEGACY_AUTOMATION_HOLD); return parts.length > 0 ? parts.join('; ') : null; } @@ -781,6 +789,36 @@ async function subjectBelongsToOtherActiveOrg( return rows[0]?.elsewhere ?? false; } +/** Erase only unheld subject runs. The immutable hold and its protected + * children stay intact; its presence cannot roll back unrelated deletions. + * Both queries share one transaction and the same tenant/starter scope. */ +export async function eraseSubjectAutomationRuns( + sql: Sql, + organizationId: string, + targetUserId: string, +): Promise<{ deleted: number; held: number }> { + const starters = [ + `user:${targetUserId}`, + `api-key:${targetUserId}`, + targetUserId, + ]; + return sql.begin(async (tx) => { + await markAutomationWriterInTx(tx); + const [held] = await tx<{ count: number }[]>` + SELECT count(*)::int AS count FROM app.automation_runs + WHERE org_id = ${organizationId} AND started_by = ANY(${starters}) + AND legacy_quarantine IS NOT NULL + `; + const removed = await tx<{ id: string }[]>` + DELETE FROM app.automation_runs + WHERE org_id = ${organizationId} AND started_by = ANY(${starters}) + AND legacy_quarantine IS NULL + RETURNING id + `; + return { deleted: removed.length, held: held?.count ?? 0 }; + }); +} + /** The cascade — each pass bounded and idempotent; per-pass counts land on * the receipt. Reuses the retention purge primitives for threads and the * document trash for owned documents. */ @@ -843,9 +881,15 @@ export async function processErasure( return; } - const counts: Record = {}; + const counts: Record< + string, + number | { rows: number; skippedByHold: number } + > = {}; const failures: string[] = []; const heldOff: string[] = []; + let legacyHeldAutomationRuns = 0; + let automationRunsRetired = false; + let modelRequestsDeidentified = false; const pass = async ( name: string, run: () => Promise, @@ -1003,10 +1047,43 @@ export async function processErasure( return removed.length; }); - // Requests through the model endpoints for API keys: one op row per - // request (`app.sandbox_session_ops`, kind `model-api`), stamped with the - // key holder. A row whose spend is booked and whose key is deleted (or was - // never minted) has done its work — its spend went to the ledger, whose + // Automation runs the subject started. `input`, `output`, `trace` and + // `effects` hold every node's resolved values, so the run is subject data + // even though the row is org-owned. Three markers: `user:` from the + // app door (and, since the engine store prefixes its starter, from the + // builder session and the chat capability), `api-key:` from REST and + // MCP — and the BARE id those two engine lanes recorded before they did, + // which this pass used to leave behind: a retention defect, since a run + // started from the builder carried the subject's data as much as any. + await pass('automationRuns', async () => { + const result = await eraseSubjectAutomationRuns( + sql, + organizationId, + targetUserId, + ); + legacyHeldAutomationRuns = result.held; + automationRunsRetired = true; + return result.deleted; + }); + if ( + legacyHeldAutomationRuns > 0 && + typeof counts.automationRuns === 'number' + ) { + // This per-category shape is already understood by historical receipt + // readers. Held rows must never be presented as erased rows. + counts.automationRuns = { + rows: counts.automationRuns, + skippedByHold: legacyHeldAutomationRuns, + }; + } + + // Retirement waits for admissions holding the run's FOR SHARE lock. + // Their committed ops are therefore visible to the identity pass below; + // later admission cannot find the deleted run. Preserved legacy runs are + // quarantined and cannot satisfy the running/live-lease admission gate. + // Model API requests and direct automation LLM calls each own an op row + // stamped with the person who started them. A row whose spend is booked + // and whose key is deleted (or was never minted) has done its work — its spend went to the ledger, whose // rows of the subject the pass below erases — so it is deleted. A row // still in flight is not: it carries the request's budget hold, or names a // live gateway key whose spend the settlement has yet to read and book, so @@ -1019,9 +1096,12 @@ export async function processErasure( // books either before that pass (and is erased by it) or under the // pseudonym — never under the subject after the ledger was cleared. await pass('modelApiRequests', async () => { + if (!automationRunsRetired) + throw new Error('Automation run retirement did not complete'); + const kinds = [MODEL_API_OP_KIND, AUTOMATION_LLM_OP_KIND]; const removed = await sql<{ id: string }[]>` DELETE FROM app.sandbox_session_ops - WHERE org_id = ${organizationId} AND kind = ${MODEL_API_OP_KIND} + WHERE org_id = ${organizationId} AND kind = ANY(${kinds}) AND user_id = ${targetUserId} AND spend_settled_at_ms IS NOT NULL AND (key_revoked_at_ms IS NOT NULL OR minted_key_id IS NULL) @@ -1029,10 +1109,11 @@ export async function processErasure( `; const pseudonymised = await sql<{ id: string }[]>` UPDATE app.sandbox_session_ops SET user_id = ${ERASED_SUBJECT} - WHERE org_id = ${organizationId} AND kind = ${MODEL_API_OP_KIND} + WHERE org_id = ${organizationId} AND kind = ANY(${kinds}) AND user_id = ${targetUserId} RETURNING id `; + modelRequestsDeidentified = true; return removed.length + pseudonymised.length; }); @@ -1041,6 +1122,8 @@ export async function processErasure( // run's starter carry the door forms (`user:`, `api-key:`) and are // the subject's spend all the same. await pass('usageLedger', async () => { + if (!modelRequestsDeidentified) + throw new Error('Model request de-identification did not complete'); const removed = await sql<{ orgId: string }[]>` DELETE FROM app.usage_ledger WHERE org_id = ${organizationId} @@ -1162,27 +1245,6 @@ export async function processErasure( return removed.length; }); - // Automation runs the subject started. `input`, `output`, `trace` and - // `effects` hold every node's resolved values, so the run is subject data - // even though the row is org-owned. Three markers: `user:` from the - // app door (and, since the engine store prefixes its starter, from the - // builder session and the chat capability), `api-key:` from REST and - // MCP — and the BARE id those two engine lanes recorded before they did, - // which this pass used to leave behind: a retention defect, since a run - // started from the builder carried the subject's data as much as any. - await pass('automationRuns', async () => { - return sql.begin(async (tx) => { - await markAutomationWriterInTx(tx); - const removed = await tx<{ id: string }[]>` - DELETE FROM app.automation_runs - WHERE org_id = ${organizationId} - AND started_by = ANY(${[`user:${targetUserId}`, `api-key:${targetUserId}`, targetUserId]}) - RETURNING id - `; - return removed.length; - }); - }); - // The sandbox workspaces the subject's runs with the organization's agents // worked in. A run a member starts works in a workspace of its own with // that agent, so what those runs left there is the subject's alone: it @@ -1412,13 +1474,17 @@ export async function processErasure( scrubSubjectAuditLogs(sql, organizationId, targetUserId), ); - const status = erasureReceiptStatus(failures, heldOff); + const status = erasureReceiptStatus( + failures, + heldOff, + legacyHeldAutomationRuns, + ); await sql.begin(async (tx) => { await tx` UPDATE app.gdpr_erasure_requests SET status = ${status}, finished_at_ms = ${Date.now()}, counts = ${tx.json(toJson(counts))}, - error = ${erasureReceiptError(failures, heldOff)} + error = ${erasureReceiptError(failures, heldOff, legacyHeldAutomationRuns)} WHERE id = ${requestId} `; await createAuditLog(tx, { @@ -1679,7 +1745,7 @@ export async function getErasureRequest( cancelledBy: string | null; cancellationReason: string | null; threadsTargeted: string[] | null; - counts: Record | null; + counts: Record | null; error: string | null; }[] >` @@ -1723,6 +1789,12 @@ export async function getErasureRequest( ]; const nameOf = await userNames(sql, userIds); const counts = row.counts; + const categories = Object.fromEntries( + foldBreakdownEntries(counts ?? {}).visible.map((entry) => [ + entry.key, + entry, + ]), + ); const terminalAt = row.finishedAt; const request: Record = { _id: row.id, @@ -1739,11 +1811,16 @@ export async function getErasureRequest( ...(row.threadsTargeted !== null ? { threadsTargeted: row.threadsTargeted } : {}), - ...(counts?.threads !== undefined ? { threadsErased: counts.threads } : {}), - ...(counts?.documents !== undefined - ? { documentsErased: counts.documents } + ...(counts !== null + ? { + threadsErased: categories.threads?.rows ?? 0, + threadsSkippedByHold: categories.threads?.skippedByHold ?? 0, + documentsErased: categories.documents?.rows ?? 0, + documentsSkippedByHold: categories.documents?.skippedByHold ?? 0, + wfExecutionsErased: categories.automationRuns?.rows ?? 0, + perCategorySnapshot: counts, + } : {}), - ...(counts !== null ? { perCategorySnapshot: counts } : {}), ...(row.error !== null ? { errorMessage: row.error } : {}), ...(row.startedAt !== null ? { startedAt: row.startedAt } : {}), ...(row.status === 'cancelled' diff --git a/services/platform/backend/domains/erasure/spec.md b/services/platform/backend/domains/erasure/spec.md index abaf645157..2634e42bde 100644 --- a/services/platform/backend/domains/erasure/spec.md +++ b/services/platform/backend/domains/erasure/spec.md @@ -53,12 +53,14 @@ without a new approval. A request that has finished in the meantime is not run a | What the person started | What happens to it | | --- | --- | -| automation runs | deleted | +| automation runs | deleted unless preserved by an unresolved legacy execution hold (`ERASE-R9`) | | runs of a project agent | kept, with the person's identity replaced by a pseudonym | -| finished requests to the model API | deleted | -| requests to the model API still in progress | kept, with the person's identity replaced by a pseudonym | +| finished model API and direct automation model requests | deleted | +| model API and direct automation model requests still in progress | kept, with the person's identity replaced by a pseudonym | -The receipt counts each of these steps. +The receipt counts each of these steps. Automation runs are retired before their model +requests lose the identity, so an admitted call that finishes later books only under the +pseudonym. A failed prerequisite keeps the affected cleanup partial and retryable. - **Example**: Noah started twelve automation runs. Ada's erasure of Noah completes → the twelve runs are gone, and the receipt counts them. @@ -89,6 +91,19 @@ be checked, the request fails with an error; it is not recorded as a denial. - **Example**: A script files erasure requests in a loop → after the limit they are refused, and each refusal is in the audit log. +## Preserved automation runs + +### ERASE-R9 · An erasure preserves held runs and deletes other eligible runs + +The erasure removes the person's unheld automation runs in this organization and counts +deleted and preserved runs separately. Any preserved legacy run keeps the receipt partial +with an execution-hold reason. A stop request or a retry does not release that hold, erase +its evidence or allow its task to restart. This is separate from a legal hold. Summary counters +and the category breakdown read both historical count shapes and agree on erased rows. + +- **Example**: Noah started two runs and one is held after an upgrade. Ada's erasure removes + the unheld run → the receipt shows one erased, one preserved and a partial result. + ## Not yet - **Who can file, approve and retry a request**, and the second admin's approval itself: see diff --git a/services/platform/backend/domains/governance/README.md b/services/platform/backend/domains/governance/README.md index 7092b77cbc..845bf795c0 100644 --- a/services/platform/backend/domains/governance/README.md +++ b/services/platform/backend/domains/governance/README.md @@ -52,7 +52,7 @@ page, the budget gate, erasure and retention are its readers. Beside it, `app.pr subautomation's included, which runs as one step of its parent's run — spends outside any session: its run is its subject, through `resolveAutomationRunAttribution` — the mapping the run's agent turns resolve through too — and `domains/automations/llm-metering.ts` measures that - subject before each call and books the call after it. Every lane that measures a run's subject + subject under the shared admission lock and reserves the full priced prompt/output estimate on an `automation-llm` op before each call. The durable effect attempt identifies the op. Reported usage is persisted before idempotent settlement; an unknown outcome keeps its hold until the bounded request lifetime, then books the reserved estimate. Its `expected_cents` remains NULL and `floor_cents` records that estimate, so it is distinguishable from reported usage. A model without catalog pricing is refused before dispatch. Every lane that measures a run's subject builds it with `loadAttributedBudgetSubject` (`attributed-subject.ts`). A run's `started_by` is parsed only by `parseRunStarter` (`lib/shared/run-starter.ts`); a `split(':')` on a starter anywhere else is a defect. @@ -87,6 +87,21 @@ page, the budget gate, erasure and retention are its readers. Beside it, `app.pr its project whatever it calls (`loadBudgetSubject`). Transcription and video ingestion name no project. + Voice output reserves its estimated cost and one request under the projects captured at + admission (`tts_audio_chunks.project_ids`); `[]` means deliberately no project. A successful + request records its resolved model rate. Any already-reserved failure, watchdog expiry or + stale replacement records the saved estimate and one request once before releasing its hold, + including a failure before the provider POST: no durable dispatch distinction is available. + This is conservative estimated usage, not confirmation of a provider charge. A successful + provider response followed by a body/storage failure retains the resolved rate. A retry must + fit the remaining budget after the predecessor estimate; late results cannot charge that + predecessor again or release the successor's hold. Legacy `NULL` project stamps retain the + current-thread fallback, and a `NULL` saved price is never reconstructed. Ordinary age cleanup + defers pending attempts to their existing watchdog. Authorized history purge and erasure keep + their existing deletion behavior; the budget rule does not restore erased attribution or + promise a strict cap across that privacy boundary. Old admission writers must retire before + every new request receives these reservation guarantees. + ## Lanes (the write side) | Lane | Resolver | `user_id` | `agent_slug` | `api_key_id` | project | @@ -95,9 +110,9 @@ page, the budget gate, erasure and retention are its readers. Beside it, `app.pr | Chat title | `core/chat/generate_title.ts` → same ledger | the thread's member | `thread-title` | — | the thread's (`chat.generate_title` job) | | Project agent turn (`task-agent` op) | `resolveSessionOpAttribution` | `project_agent_runs.started_by` (bare); `__automation__` for `trigger:` | `project_agents.id` | — | `project_agent_runs.project_id` | | Automation agent turn (`workflow-agent` op) | `resolveSessionOpAttribution` | the person `started_by` names; `__automation__` for `trigger:` | automation name | `automation_runs.api_key_id` | `automation_runs.project_id`, else every project the automation is bound to | -| Automation `llm` step | `resolveAutomationRunAttribution` (`domains/automations/llm-metering.ts`) → `createPgUsageLedger` | the person `started_by` names; `__automation__` for `trigger:` | automation name | `automation_runs.api_key_id` | `automation_runs.project_id`, else every project the automation is bound to | +| Automation `llm` step | `resolveAutomationRunAttribution` → immutable `automation-llm` op → `settleSessionOpSpend` | the person `started_by` names; `__automation__` for `trigger:` | automation name | `automation_runs.api_key_id` | `automation_runs.project_id`, else every project the automation is bound to | | Agent image generation (`generate_image`, one row per billed request, no tokens) | `resolveSessionOpAttribution` on the op the turn's token names (`domains/sandbox/image-generation.ts`) | the turn's person, as above; `__automation__` for `trigger:` | the turn's agent id or automation name | the run's key, as above | the run's, as above | -| Voice output | `domains/tts` | the requester | `__tts__` | — | the thread's | +| Voice output | `domains/tts` | the requester | `__tts__` | — | captured at admission; legacy `NULL` uses the current thread | | Transcription | `domains/files/transcription.ts` | the requester | `__transcription__` | — | — | | Model endpoint request (`model-api` op) | `domains/model_api/metering.ts` stamps the op; settlement reads the stamp | the key holder | `__direct_api__` | the API key | a project's key's project | | Connector call | `recordConnectorUsage` | the caller | optional | — | the chat's, for the assistant's tools | @@ -120,7 +135,7 @@ page, the budget gate, erasure and retention are its readers. Beside it, `app.pr - `domains/sandbox/turn-budget.test.ts`, `spend-settlement.test.ts` — reservation and settlement book the same subject and the key; a trigger run is impersonal. - `core/automations/llm_call.test.ts`, `domains/automations/llm-metering.test.ts` — an - automation's `llm` step is measured before each call, refused with `budget_exceeded` at a + automation's `llm` step reserves before each call, refused with `budget_exceeded` at a reached cap, and booked under its run's subject after it, an empty reply included. - `domains/model_api/metering.test.ts` — a model-endpoint request reserves under the key holder with the key and books the gateway's figure under the person, `__direct_api__` and the key. diff --git a/services/platform/backend/domains/governance/budget-reservations.test.ts b/services/platform/backend/domains/governance/budget-reservations.test.ts index d0b76875d3..f785b240a2 100644 --- a/services/platform/backend/domains/governance/budget-reservations.test.ts +++ b/services/platform/backend/domains/governance/budget-reservations.test.ts @@ -148,8 +148,9 @@ describe('readInFlightReservations', () => { 'project-2': { costCents: 40, tokens: 0, requests: 1 }, }); const read = statements[0]?.text ?? ''; - // A chat turn is in its thread's project; an op in every project its - // reservation stamped, each counting it once. + // A new chat hold follows its immutable stamp. Legacy NULL still has + // the previous thread lookup; an empty stamp never falls back. + expect(read).toContain('coalesce(g.project_ids,'); expect(read).toContain( 'LEFT JOIN app.thread_metadata tm ON tm.thread_id = g.thread_id', ); @@ -220,6 +221,7 @@ describe('readInFlightReservations', () => { { threadId: 'thread-1', op: { sessionId: 'session-1', execId: 'exec-1' }, + tts: { chunkId: 'chunk-1', attemptCreatedAt: 123 }, }, ); expect(statements[0]?.text).toContain('thread_id <> ?'); @@ -227,7 +229,13 @@ describe('readInFlightReservations', () => { 'AND NOT (session_id = ? AND exec_id = ?)', ); expect(statements[0]?.values).toEqual( - expect.arrayContaining(['thread-1', 'session-1', 'exec-1']), + expect.arrayContaining([ + 'thread-1', + 'session-1', + 'exec-1', + 'chunk-1', + 123, + ]), ); }); }); diff --git a/services/platform/backend/domains/governance/budget-reservations.ts b/services/platform/backend/domains/governance/budget-reservations.ts index e22599eaac..20493efc0f 100644 --- a/services/platform/backend/domains/governance/budget-reservations.ts +++ b/services/platform/backend/domains/governance/budget-reservations.ts @@ -115,6 +115,7 @@ export async function readInFlightReservations( exclude: { threadId?: string; op?: { sessionId: string; execId: string }; + tts?: { chunkId: string; attemptCreatedAt: number }; } = {}, ): Promise { const org = subject.organizationId; @@ -124,15 +125,18 @@ export async function readInFlightReservations( const projectIds = [...(subject.projectIds ?? [])]; const rows = await sql` WITH holds AS ( - -- A chat turn belongs to its thread's project. + -- New turns keep the projects captured with the request. Only legacy + -- unstamped rows follow the thread's current project. SELECT g.user_id, g.api_key_id, - CASE WHEN tm.project_id IS NULL THEN '{}'::text[] - ELSE ARRAY[tm.project_id] END AS project_ids, + coalesce(g.project_ids, + CASE WHEN tm.project_id IS NULL THEN '{}'::text[] + ELSE ARRAY[tm.project_id] END) AS project_ids, g.reserved_cost_cents::float8 AS cost_cents, g.reserved_tokens::float8 AS tokens, 1::float8 AS requests FROM app.generations g - LEFT JOIN app.thread_metadata tm ON tm.thread_id = g.thread_id + LEFT JOIN app.thread_metadata tm + ON tm.thread_id = g.thread_id AND tm.org_id = g.org_id WHERE g.org_id = ${org} AND g.user_id IS NOT NULL AND g.thread_id <> ${exclude.threadId ?? ''} UNION ALL @@ -151,6 +155,21 @@ export async function readInFlightReservations( AND spend_settled_at_ms IS NULL AND NOT (session_id = ${exclude.op?.sessionId ?? ''} AND exec_id = ${exclude.op?.execId ?? ''}) + UNION ALL + -- Pending voice attempts hold one request and their admitted cost. + -- Legacy rows have no known cost; keep their request visible anyway. + SELECT c.user_id, NULL::text, + coalesce(c.project_ids, + CASE WHEN tm.project_id IS NULL THEN '{}'::text[] + ELSE ARRAY[tm.project_id] END), + coalesce(c.reserved_cost_cents, 0)::float8, + 0::float8, 1::float8 + FROM app.tts_audio_chunks c + LEFT JOIN app.thread_metadata tm + ON tm.thread_id = c.thread_id AND tm.org_id = c.org_id + WHERE c.org_id = ${org} AND c.status = 'pending' + AND NOT (c.id = ${exclude.tts?.chunkId ?? ''} + AND c.attempt_created_at_ms = ${exclude.tts?.attemptCreatedAt ?? -1}) ), -- Who spends for a team: its current members, and the keys it owns. team_spenders AS ( diff --git a/services/platform/backend/domains/governance/immutable-projects.integration.ts b/services/platform/backend/domains/governance/immutable-projects.integration.ts new file mode 100644 index 0000000000..105c309576 --- /dev/null +++ b/services/platform/backend/domains/governance/immutable-projects.integration.ts @@ -0,0 +1,343 @@ +/** Real PostgreSQL and app-door proof that admission, holds and billing use + * the same project set even when a conversation or automation is refiled. */ +import { randomUUID } from 'node:crypto'; +import { mkdir, readFile, unlink, writeFile } from 'node:fs/promises'; +import path from 'node:path'; + +import type { Sql } from 'postgres'; +import { z } from 'zod'; + +import type { RecordCheck } from '../../integration-lane-helpers.ts'; +import { clearOrgConfigCaches } from '../../lib/org-config.ts'; +import { markAutomationWriterInTx } from '../automations/writer-protocol.ts'; +import { ChatBudgetExceededError } from '../chat/budget-admission.ts'; +import { createPgTurnStore } from '../chat/store.ts'; +import { + admitImageGeneration, + resolveImageTurnContext, + settleImageGeneration, +} from '../sandbox/image-generation.ts'; +import { settleSessionOpSpend } from '../sandbox/spend-settlement.ts'; +import { reserveTurnBudget } from '../sandbox/turn-budget.ts'; +import { readInFlightReservations } from './budget-reservations.ts'; + +const threadSchema = z.object({ id: z.string() }); + +export async function checkImmutableBudgetProjects( + sql: Sql, + base: string, + ctx: { cookie: string; orgId: string; userId: string }, + record: RecordCheck, +): Promise { + const { orgId, userId } = ctx; + const suffix = randomUUID(); + const now = Date.now(); + const automation = `itest/immutable-budget-${suffix}`; + const sessionId = `wf-immutable-budget-${suffix}`; + const emptySession = `model-api:immutable-budget-${suffix}`; + const projects: string[] = []; + const threads: string[] = []; + let runId = ''; + const [org] = await sql< + { slug: string }[] + >`SELECT slug FROM "organization" WHERE id = ${orgId}`; + if (org === undefined) + throw new Error('Budget fixture organization is missing'); + const directory = path.join( + process.env.TALE_CONFIG_DIR ?? '', + org.slug, + 'governance', + ); + const policy = path.join(directory, 'budgets.yml'); + let previous: string | undefined; + try { + previous = await readFile(policy, 'utf8'); + } catch (error) { + if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT')) + throw error; + } + const report = (name: string, ok: boolean, detail: unknown) => + record(`immutable budget projects: ${name}`, ok, JSON.stringify(detail)); + const project = async () => { + const [row] = await sql<{ id: string }[]>` + INSERT INTO app.projects (org_id, name, team_ids, team_id, shared_with_team_ids, created_by, created_at_ms, updated_at_ms) + VALUES (${orgId}, ${`Immutable budget ${suffix}`}, ${[]}, NULL, ${[]}, ${userId}, ${now}, ${now}) RETURNING id`; + if (row === undefined) throw new Error('Budget fixture project missing'); + projects.push(row.id); + return row.id; + }; + const thread = async (projectId?: string) => { + const response = await fetch( + `${base}/api/app/chat/threads?orgId=${orgId}`, + { + method: 'POST', + headers: { + cookie: ctx.cookie, + origin: base, + 'content-type': 'application/json', + }, + body: JSON.stringify({ + ...(projectId !== undefined ? { projectId } : {}), + title: `Budget ${suffix}`, + }), + }, + ); + const parsed = threadSchema.safeParse(await response.json()); + if (!response.ok || !parsed.success) + throw new Error('Budget fixture thread refused'); + threads.push(parsed.data.id); + return parsed.data.id; + }; + const refile = async (threadId: string, projectId: string) => { + const response = await fetch( + `${base}/api/app/chat/threads/${threadId}/project?orgId=${orgId}`, + { + method: 'POST', + headers: { + cookie: ctx.cookie, + origin: base, + 'content-type': 'application/json', + }, + body: JSON.stringify({ projectId }), + }, + ); + if (!response.ok) + throw new Error(`Budget fixture refile refused: ${response.status}`); + }; + const budget = async (projectId: string, maxCostCents: number) => { + await mkdir(directory, { recursive: true }); + await writeFile( + policy, + [ + 'enabled: true', + 'rules: []', + 'projectRules:', + ' - scope: project', + ` scopeId: ${projectId}`, + ' period: monthly', + ` maxCostCents: ${maxCostCents}`, + ].join('\n'), + ); + clearOrgConfigCaches(); + }; + const holds = () => + readInFlightReservations(sql, { + organizationId: orgId, + userId, + userTeamIds: [], + projectIds: projects, + }); + const store = createPgTurnStore(sql); + const open = (threadId: string, projectIds: string[], costCents: number) => + store.beginTurn({ + organizationId: orgId, + threadId, + userParts: [{ type: 'text', text: 'bounded budget fixture' }], + spend: { userId, projectIds, tokens: 1, costCents }, + }); + try { + const a = await project(); + const b = await project(); + const c = await project(); + const active = await thread(a); + const next = await thread(b); + const outside = await thread(); + await budget(a, 10); + await open(active, [a], 10); + await refile(active, b); + const afterMove = await holds(); + let refused = false; + try { + await open(next, [a], 1); + } catch (error) { + if ( + error instanceof ChatBudgetExceededError && + error.data.projectId === a + ) + refused = true; + else throw error; + } + report( + 'refiling a live chat retains its original hold and refuses another captured-project admission', + afterMove.projects?.[a]?.costCents === 10 && + afterMove.projects?.[b] === undefined && + refused, + { afterMove, refused }, + ); + await store.endGeneration({ organizationId: orgId, threadId: active }); + await store.endGeneration({ organizationId: orgId, threadId: next }); + + await open(outside, [], 2); + await refile(outside, b); + const empty = await holds(); + report( + 'a no-project chat keeps an authoritative empty stamp after refiling', + projects.every((id) => empty.projects?.[id] === undefined), + empty, + ); + await store.endGeneration({ organizationId: orgId, threadId: outside }); + + // A pre-upgrade writer can still insert its old column set. This proves + // schema/read compatibility, not a historical binary or old-cost recall. + await sql`INSERT INTO app.generations (thread_id, org_id, user_id, reserved_cost_cents, reserved_tokens, started_at_ms, heartbeat_at_ms, updated_at_ms) + VALUES (${active}, ${orgId}, ${userId}, 3, 1, ${now}, ${now}, ${now})`; + const legacy = await holds(); + report( + 'legacy unstamped generation rows retain current-thread fallback', + legacy.projects?.[b]?.costCents === 3, + legacy, + ); + await store.endGeneration({ organizationId: orgId, threadId: active }); + + await budget(a, 100); + for (const id of [a, b]) + await sql` + INSERT INTO app.automation_project_bindings (org_id, automation_name, project_id, bound_at_ms, bound_by) + VALUES (${orgId}, ${automation}, ${id}, ${now}, ${userId})`; + const [run] = await sql.begin(async (tx) => { + await markAutomationWriterInTx(tx); + return tx< + { id: string }[] + >`INSERT INTO app.automation_runs (org_id, name, version, status, mode, started_by, input, checkpoints, wake_at_ms, claim_epoch, started_at_ms) + VALUES (${orgId}, ${automation}, 1, 'running', 'live', 'trigger:itest', ${sql.json({})}, ${sql.json({ nodes: {}, executions: 0 })}, NULL, 1, ${now}) RETURNING id`; + }); + if (run === undefined) throw new Error('Budget fixture run missing'); + runId = run.id; + await sql`INSERT INTO app.sandbox_sessions (org_id, session_id, status, owner_type, owner_id, created_by, pinned, created_at_ms, expires_at_ms) + VALUES (${orgId}, ${sessionId}, 'active', 'workflow_run', ${runId}, 'itest', false, ${now}, ${now + 3600000})`; + const reservationArgs = { + organizationId: orgId, + sessionId, + execId: 'step', + kind: 'workflow-agent' as const, + defaultBudgetCents: 50, + modelRef: `itest/${automation}`, + }; + const first = await reserveTurnBudget(sql, reservationArgs); + await sql`DELETE FROM app.automation_project_bindings WHERE org_id = ${orgId} AND automation_name = ${automation}`; + await sql`INSERT INTO app.automation_project_bindings (org_id, automation_name, project_id, bound_at_ms, bound_by) + VALUES (${orgId}, ${automation}, ${c}, ${now}, ${userId})`; + const repeated = await reserveTurnBudget(sql, reservationArgs); + const context = await resolveImageTurnContext(sql, reservationArgs); + const rebound = await holds(); + report( + 'managed retries and live image context retain the admitted automation projects after rebinding', + first.allowed && + repeated.allowed && + context.status === 'live' && + JSON.stringify(context.subject.projectIds?.toSorted()) === + JSON.stringify([a, b].toSorted()) && + rebound.projects?.[a]?.costCents === 50 && + rebound.projects?.[b]?.costCents === 50 && + rebound.projects?.[c] === undefined, + { first, repeated, context, rebound }, + ); + if (context.status !== 'live') + throw new Error('Budget fixture image context ended'); + // Simulate context captured after a rebind: admission must refresh the + // op's billing stamp under its lock, not trust that stale project list. + const staleSubject = { ...context.subject, projectIds: [c] }; + const image = await admitImageGeneration(sql, { + organizationId: orgId, + sessionId, + execId: 'step', + subject: staleSubject, + images: 1, + }); + const duringImage = await holds(); + report( + 'image admission adds its hold to the same admitted projects', + image.admitted && + duringImage.projects?.[a]?.costCents === 75 && + duringImage.projects?.[b]?.costCents === 75 && + duringImage.projects?.[c] === undefined, + { image, duringImage }, + ); + if (!image.admitted) throw new Error('Budget fixture image refused'); + await settleImageGeneration(sql, { + organizationId: orgId, + sessionId, + execId: 'step', + callStartedAt: image.callStartedAt, + subject: staleSubject, + provider: 'itest', + model: automation, + charges: [7], + timestamp: now, + }); + await settleSessionOpSpend(sql, { + sessionId, + execId: 'step', + spentCents: 3, + usage: { inputTokens: 1, outputTokens: 1 }, + }); + const booked = await sql< + { projectId: string; cost: number }[] + >`SELECT project_id AS "projectId", cost_estimate_cents::float8 AS cost FROM app.project_usage + WHERE org_id = ${orgId} AND project_id = ANY(${projects}) AND granularity = 'monthly'`; + const after = await holds(); + report( + 'image and managed settlement replace the admitted holds with bills in exactly those projects', + booked.length === 2 && + booked.every( + (row) => [a, b].includes(row.projectId) && row.cost === 10, + ) && + projects.every((id) => after.projects?.[id] === undefined), + { booked, after }, + ); + + const outsideArgs = { + organizationId: orgId, + sessionId: emptySession, + execId: 'empty', + kind: 'model-api' as const, + defaultBudgetCents: 1, + subject: { userId, agentSlug: automation, projectIds: [] as string[] }, + whole: { prospectiveTokens: 1 }, + }; + const emptyFirst = await reserveTurnBudget(sql, outsideArgs); + const emptyRetry = await reserveTurnBudget(sql, { + ...outsideArgs, + subject: { ...outsideArgs.subject, projectIds: [c] }, + }); + await settleSessionOpSpend(sql, { + sessionId: emptySession, + execId: 'empty', + spentCents: 1, + }); + const noNewProject = await sql< + { count: number }[] + >`SELECT count(*)::int AS count FROM app.project_usage WHERE org_id = ${orgId} AND project_id = ${c}`; + report( + 'an explicit empty op stamp stays empty during retry and settlement', + emptyFirst.allowed && emptyRetry.allowed && noNewProject[0]?.count === 0, + { emptyFirst, emptyRetry, noNewProject }, + ); + } finally { + if (previous === undefined) + await unlink(policy).catch((error: unknown) => { + if ( + !( + error instanceof Error && + 'code' in error && + error.code === 'ENOENT' + ) + ) + throw error; + }); + else await writeFile(policy, previous); + clearOrgConfigCaches(); + await sql`DELETE FROM app.sandbox_session_ops WHERE org_id = ${orgId} AND session_id = ANY(${[sessionId, emptySession]})`; + await sql`DELETE FROM app.sandbox_sessions WHERE org_id = ${orgId} AND session_id = ${sessionId}`; + if (runId !== '') + await sql.begin(async (tx) => { + await markAutomationWriterInTx(tx); + await tx`DELETE FROM app.automation_runs WHERE org_id = ${orgId} AND id = ${runId}`; + }); + await sql`DELETE FROM app.automation_project_bindings WHERE org_id = ${orgId} AND automation_name = ${automation}`; + await sql`DELETE FROM app.threads WHERE org_id = ${orgId} AND id = ANY(${threads})`; + await sql`DELETE FROM app.usage_ledger WHERE org_id = ${orgId} AND agent_slug = ${automation}`; + await sql`DELETE FROM app.project_usage WHERE org_id = ${orgId} AND project_id = ANY(${projects})`; + await sql`DELETE FROM app.projects WHERE org_id = ${orgId} AND id = ANY(${projects})`; + } +} diff --git a/services/platform/backend/domains/governance/project-budget.integration.ts b/services/platform/backend/domains/governance/project-budget.integration.ts index 817066b579..c475a0e091 100644 --- a/services/platform/backend/domains/governance/project-budget.integration.ts +++ b/services/platform/backend/domains/governance/project-budget.integration.ts @@ -10,7 +10,8 @@ import { buildPeriodKeyFromTimestamp } from '../../core/governance/helpers.ts'; import type { RecordCheck } from '../../integration-lane-helpers.ts'; import { clearOrgConfigCaches } from '../../lib/org-config.ts'; import { - checkLlmStepBudget, + reserveLlmStepBudget, + llmStepOp, recordLlmStepUsage, } from '../automations/llm-metering.ts'; import { markAutomationWriterInTx } from '../automations/writer-protocol.ts'; @@ -18,7 +19,16 @@ import { assertChatTurnBudget, ChatBudgetExceededError, } from '../chat/budget-admission.ts'; -import { settleSessionOpSpend } from '../sandbox/spend-settlement.ts'; +import { + loadProjectSharedThread, + projectChatAccess, + setThreadSharedWithProject, +} from '../chat/threads.ts'; +import { processErasure } from '../erasure/service.ts'; +import { + reconcilePendingSessionOpKeys, + settleSessionOpSpend, +} from '../sandbox/spend-settlement.ts'; import { reserveTurnBudget } from '../sandbox/turn-budget.ts'; import { readInFlightReservations } from './budget-reservations.ts'; import { incrementUsageLedger } from './service.ts'; @@ -92,7 +102,13 @@ export async function checkProjectBudgets( const automationName = `itest/project-budget-${suffix}`; const runSession = `wf-itest-project-${suffix}`; let secondProjectId = ''; + let llmSession = ''; let runId = ''; + const projectReaderId = randomUUID(); + const erasureRequestId = randomUUID(); + let erasureRunId = ''; + let erasureSession = ''; + const erasureAutomation = `itest/project-erasure-${suffix}`; // A hidden branch of the project's conversation, as an edit or a // regenerate leaves one: later turns run on it. const [branch] = await sql<{ id: string }[]>` @@ -309,11 +325,11 @@ export async function checkProjectBudgets( return fixtureTx<{ id: string }[]>` INSERT INTO app.automation_runs ( org_id, name, version, status, mode, started_by, input, checkpoints, - wake_at_ms, claim_epoch, started_at_ms + wake_at_ms, claim_epoch, lease_epoch, lease_expires_at_ms, started_at_ms ) VALUES ( ${orgId}, ${automationName}, 1, 'running', 'live', 'trigger:itest', ${sql.json({})}, ${sql.json({ nodes: {}, executions: 0 })}, - ${null}, 1, ${now} + ${null}, 1, 1, ${now + 3_600_000}, ${now} ) RETURNING id `; }); @@ -373,18 +389,78 @@ export async function checkProjectBudgets( // both projects' caps, and booked to both beside the ledger, under the // automation subject and the automation's name. const stepModel = `itest-model-${suffix}`; - const beforeCap = await checkLlmStepBudget(sql, { - organizationId: orgId, - runId, + const attemptFor = (nodeId: string) => ({ + nodeId, + itemIndex: 0, + pass: 0, + attempt: 1, }); - await recordLlmStepUsage(sql, { + for (const node of [ + 'llm-one', + 'llm-two', + 'llm-capped', + 'llm-unknown', + 'llm-crashed', + ]) { + await sql` + INSERT INTO app.automation_node_attempts + (org_id, run_id, node_id, kind, node_type, status, claim_epoch, started_at_ms) + VALUES (${orgId}, ${runId}, ${node}, 'llm', 'llm', 'started', 1, ${now}) + `; + } + const reservation = (nodeId: string) => ({ organizationId: orgId, runId, + attempt: attemptFor(nodeId), provider: 'itest', model: stepModel, - inputTokens: 40, - outputTokens: 10, + reserveCents: 20, + reserveTokens: 50, }); + llmSession = llmStepOp(reservation('llm-one')).sessionId; + // Both calls would fit settled usage alone; only one fits the actual + // headroom once both the earlier model hold and the first LLM hold count. + const competing = await Promise.all([ + reserveLlmStepBudget(sql, reservation('llm-one')), + reserveLlmStepBudget(sql, reservation('llm-two')), + ]); + const beforeCap = competing.find((result) => result.allowed); + record( + 'project budgets: distinct direct LLM attempts serialize whole holds before a provider call', + competing.filter((result) => result.allowed).length === 1, + JSON.stringify(competing), + ); + if (beforeCap === undefined || !beforeCap.allowed) + throw new Error('No direct LLM fixture admitted'); + await sql`DELETE FROM app.automation_project_bindings + WHERE org_id = ${orgId} AND automation_name = ${automationName} AND project_id = ${secondProjectId}`; + const heldAfterUnbind = await readInFlightReservations(sql, { + organizationId: orgId, + userId: '__automation__', + userTeamIds: [], + projectIds: [secondProjectId], + }); + record( + 'project budgets: a direct LLM hold retains the project unbound during the call', + heldAfterUnbind.projects?.[secondProjectId]?.costCents === 20, + JSON.stringify(heldAfterUnbind.projects), + ); + await recordLlmStepUsage(sql, { + organizationId: orgId, + sessionId: beforeCap.sessionId, + execId: beforeCap.execId, + usage: { inputTokens: 40, outputTokens: 10, cents: 0 }, + }); + // Repeated delivery is idempotent; live bindings do not redirect spend. + await recordLlmStepUsage(sql, { + organizationId: orgId, + sessionId: beforeCap.sessionId, + execId: beforeCap.execId, + usage: { inputTokens: 40, outputTokens: 10, cents: 0 }, + }); + await sql`INSERT INTO app.automation_project_bindings + (org_id, automation_name, project_id, bound_at_ms, bound_by) + VALUES (${orgId}, ${automationName}, ${secondProjectId}, ${now}, ${userId})`; const stepBuckets = await sql< { projectId: string; tokens: number; requests: number }[] >` @@ -418,10 +494,7 @@ export async function checkProjectBudgets( ].join('\n'), ); clearOrgConfigCaches(); - const atCap = await checkLlmStepBudget(sql, { - organizationId: orgId, - runId, - }); + const atCap = await reserveLlmStepBudget(sql, reservation('llm-capped')); record( 'project budgets: an automation’s llm step is measured against, and booked to, every project its run is in', beforeCap.allowed && @@ -433,9 +506,356 @@ export async function checkProjectBudgets( stepLedger[0]?.userId === '__automation__' && stepLedger[0].tokens === 50 && !atCap.allowed && - atCap.reason.includes("This project's monthly request limit"), + atCap.violation?.scope === 'project' && + atCap.violation.projectId === secondProjectId && + atCap.violation.code === 'REQUEST_LIMIT' && + atCap.violation.period === 'monthly' && + atCap.violation.used === 2 && + atCap.violation.limit === 2, `before the cap=${JSON.stringify(beforeCap)} (want allowed), buckets=${JSON.stringify(stepBuckets)} (want 15+7+50 and 7+50 tokens, the second at 2 requests), ledger=${JSON.stringify(stepLedger)} (want 50 tokens under __automation__), at the cap=${JSON.stringify(atCap)} (want refused for the project's request limit)`, ); + await writeFile( + budgetsFile, + 'enabled: true\nrules: []\nprojectRules: []\n', + ); + clearOrgConfigCaches(); + const unknown = await reserveLlmStepBudget(sql, { + ...reservation('llm-unknown'), + reserveCents: 2, + reserveTokens: 123, + }); + if (!unknown.allowed) + throw new Error('Unknown-outcome fixture was refused'); + await sql`UPDATE app.sandbox_session_ops SET started_at_ms = ${Date.now() - 180_001} + WHERE org_id = ${orgId} AND session_id = ${unknown.sessionId} AND exec_id = ${unknown.execId}`; + await recordLlmStepUsage(sql, { + organizationId: orgId, + sessionId: unknown.sessionId, + execId: unknown.execId, + usage: null, + }); + const unknownFacts = await sql< + { + expected: number | null; + floor: number; + spent: number; + settled: boolean; + }[] + >` + SELECT expected_cents AS expected, floor_cents AS floor, spent_cents AS spent, + spend_settled_at_ms IS NOT NULL AS settled FROM app.sandbox_session_ops + WHERE org_id = ${orgId} AND session_id = ${unknown.sessionId} AND exec_id = ${unknown.execId}`; + record( + 'project budgets: unknown direct LLM outcome settles its durable reserved estimate, never no-key zero', + unknownFacts[0]?.expected === null && + unknownFacts[0]?.floor === 2 && + unknownFacts[0]?.spent === 2 && + unknownFacts[0] !== undefined && + unknownFacts[0].settled, + JSON.stringify(unknownFacts), + ); + + // A process can disappear after dispatch without saving terminal facts. + // The ordinary watchdog must find that running op and settle it once. + const crashedModel = `${stepModel}-crashed`; + const crashed = await reserveLlmStepBudget(sql, { + ...reservation('llm-crashed'), + model: crashedModel, + reserveCents: 3, + reserveTokens: 29, + }); + if (!crashed.allowed) throw new Error('Crash fixture was refused'); + const beforeCrash = await sql<{ running: boolean }[]>` + SELECT status = 'running' AND finalized_at_ms IS NULL + AND spend_settled_at_ms IS NULL AS running + FROM app.sandbox_session_ops + WHERE org_id = ${orgId} AND session_id = ${crashed.sessionId} AND exec_id = ${crashed.execId}`; + const readCrashProjects = () => sql<{ projectId: string; cost: number }[]>` + SELECT project_id AS "projectId", cost_estimate_cents::float8 AS cost + FROM app.project_usage WHERE org_id = ${orgId} AND granularity = 'monthly' + AND project_id = ANY(${[projectId, secondProjectId]}) ORDER BY project_id`; + const beforeCrashProjects = await readCrashProjects(); + await sql`DELETE FROM app.automation_project_bindings + WHERE org_id = ${orgId} AND automation_name = ${automationName} AND project_id = ${secondProjectId}`; + await sql`UPDATE app.sandbox_session_ops SET started_at_ms = ${Date.now() - 180_001} + WHERE org_id = ${orgId} AND session_id = ${crashed.sessionId} AND exec_id = ${crashed.execId}`; + await reconcilePendingSessionOpKeys(sql, { batch: 100, now: Date.now() }); + const crashFacts = await sql< + { + projectIds: string[] | null; + failed: boolean; + finalized: boolean; + expected: number | null; + floor: number; + spent: number; + settled: boolean; + }[] + >` + SELECT project_ids AS "projectIds", status = 'failed' AS failed, + finalized_at_ms IS NOT NULL AS finalized, expected_cents AS expected, + floor_cents AS floor, spent_cents AS spent, + spend_settled_at_ms IS NOT NULL AS settled FROM app.sandbox_session_ops + WHERE org_id = ${orgId} AND session_id = ${crashed.sessionId} AND exec_id = ${crashed.execId}`; + const afterCrashProjects = await readCrashProjects(); + await reconcilePendingSessionOpKeys(sql, { batch: 100, now: Date.now() }); + const afterRepeatedSweep = await readCrashProjects(); + const crashLedger = await sql< + { cost: number; tokens: number; requests: number }[] + >` + SELECT cost_estimate_cents::float8 AS cost, total_tokens::float8 AS tokens, + request_count::float8 AS requests FROM app.usage_ledger + WHERE org_id = ${orgId} AND agent_slug = ${automationName} + AND model = ${crashedModel} AND granularity = 'monthly'`; + record( + 'project budgets: the ordinary sweep recovers a never-finalized direct LLM op once in its original projects', + beforeCrash[0] !== undefined && + beforeCrash[0].running && + crashFacts[0] !== undefined && + JSON.stringify(crashFacts[0]?.projectIds) === + JSON.stringify([projectId, secondProjectId].toSorted()) && + crashFacts[0].failed && + crashFacts[0].finalized && + crashFacts[0]?.expected === null && + crashFacts[0]?.floor === 3 && + crashFacts[0]?.spent === 3 && + crashFacts[0].settled && + beforeCrashProjects.length === 2 && + afterCrashProjects.length === 2 && + afterCrashProjects.every( + (row) => + row.cost === + (beforeCrashProjects.find( + (prior) => prior.projectId === row.projectId, + )?.cost ?? -1) + + 3, + ) && + JSON.stringify(afterCrashProjects) === + JSON.stringify(afterRepeatedSweep) && + crashLedger.length === 1 && + crashLedger[0]?.cost === 3 && + crashLedger[0]?.tokens === 29 && + crashLedger[0]?.requests === 1, + JSON.stringify({ + beforeCrash, + crashFacts, + beforeCrashProjects, + afterCrashProjects, + afterRepeatedSweep, + crashLedger, + }), + ); + + // Refiling through a hidden sibling must end the root's old audience. + // The second member can access B, but not this conversation until the + // owner explicitly shares the canonical root again after the move. + await sql`INSERT INTO "user" ("id", "email", "name", "emailVerified", "createdAt", "updatedAt") + VALUES (${projectReaderId}, ${`itest-budget-reader-${suffix}@example.test`}, 'Budget project reader', true, now(), now())`; + await sql`INSERT INTO "member" ("id", "organizationId", "userId", "role", "createdAt") + VALUES (${randomUUID()}, ${orgId}, ${projectReaderId}, 'member', now())`; + await setThreadSharedWithProject( + sql, + { organizationId: orgId, userId }, + projectThread, + true, + ); + const beforeRefile = await loadProjectSharedThread( + sql, + orgId, + projectReaderId, + projectThread, + ); + const targetAccess = await projectChatAccess(sql, { + organizationId: orgId, + userId: projectReaderId, + projectId: secondProjectId, + }); + const refileBranch = await fetch( + `${base}/api/app/chat/threads/${branchThread}/project?orgId=${orgId}`, + { + method: 'POST', + headers: { + 'content-type': 'application/json', + cookie: ctx.cookie, + origin: base, + }, + body: JSON.stringify({ projectId: secondProjectId }), + }, + ); + const movedLineage = await sql< + { threadId: string; projectId: string; shared: boolean | null }[] + >` + SELECT thread_id AS "threadId", project_id AS "projectId", shared_with_project AS shared + FROM app.thread_metadata WHERE org_id = ${orgId} + AND thread_id = ANY(${[projectThread, branchThread]})`; + const beforeReshare = await loadProjectSharedThread( + sql, + orgId, + projectReaderId, + projectThread, + ); + await setThreadSharedWithProject( + sql, + { organizationId: orgId, userId }, + projectThread, + true, + ); + const afterReshare = await loadProjectSharedThread( + sql, + orgId, + projectReaderId, + projectThread, + ); + record( + 'project budgets: refiling through a hidden branch ends the original project share until the root is explicitly shared again', + beforeRefile?.id === projectThread && + targetAccess === 'ok' && + refileBranch.ok && + movedLineage.length === 2 && + movedLineage.every( + (row) => + row.projectId === secondProjectId && + row.shared !== null && + !row.shared, + ) && + beforeReshare === null && + afterReshare?.id === projectThread && + afterReshare.projectId === secondProjectId, + JSON.stringify({ + beforeRefile: beforeRefile?.id, + targetAccess, + status: refileBranch.status, + movedLineage, + beforeReshare: beforeReshare?.id, + afterReshare: afterReshare?.id, + }), + ); + + // A producer is retired before its ops lose identity. A provider result + // arriving after erasure must use the preserved op's pseudonym, not + // recreate personal usage. Use the isolated reader created above. + const [erasureRun] = await sql.begin(async (fixtureTx) => { + await markAutomationWriterInTx(fixtureTx); + return fixtureTx<{ id: string }[]>` + INSERT INTO app.automation_runs ( + org_id, name, version, status, mode, started_by, input, checkpoints, + wake_at_ms, claim_epoch, lease_epoch, lease_expires_at_ms, started_at_ms + ) VALUES ( + ${orgId}, ${erasureAutomation}, 1, 'running', 'live', ${`user:${projectReaderId}`}, + ${sql.json({})}, ${sql.json({ nodes: {}, executions: 0 })}, + ${null}, 1, 1, ${Date.now() + 3_600_000}, ${Date.now()} + ) RETURNING id + `; + }); + erasureRunId = erasureRun?.id ?? ''; + for (const node of [ + 'erasure-settled', + 'erasure-pending', + 'erasure-too-late', + ]) { + await sql` + INSERT INTO app.automation_node_attempts + (org_id, run_id, node_id, kind, node_type, status, claim_epoch, started_at_ms) + VALUES (${orgId}, ${erasureRunId}, ${node}, 'llm', 'llm', 'started', 1, ${Date.now()}) + `; + } + const erasureReservation = (nodeId: string) => ({ + organizationId: orgId, + runId: erasureRunId, + attempt: attemptFor(nodeId), + provider: 'itest', + model: `erasure-${suffix}`, + reserveCents: 2, + reserveTokens: 20, + }); + const settledRequest = await reserveLlmStepBudget( + sql, + erasureReservation('erasure-settled'), + ); + const pendingRequest = await reserveLlmStepBudget( + sql, + erasureReservation('erasure-pending'), + ); + if (!settledRequest.allowed || !pendingRequest.allowed) + throw new Error('Erasure direct LLM fixture was not admitted'); + erasureSession = pendingRequest.sessionId; + await recordLlmStepUsage(sql, { + organizationId: orgId, + sessionId: settledRequest.sessionId, + execId: settledRequest.execId, + usage: { inputTokens: 8, outputTokens: 2, cents: 1 }, + }); + await sql` + INSERT INTO app.gdpr_erasure_requests (id, org_id, target_user_id, reason, + reason_code, requested_by, requested_at_ms, sla_deadline_at_ms, status) + VALUES (${erasureRequestId}, ${orgId}, ${projectReaderId}, 'Direct model settlement regression', + 'consent_withdrawn', ${userId}, ${Date.now()}, ${Date.now() + 86_400_000}, 'pending') + `; + await processErasure(sql, erasureRequestId); + const afterErasure = await sql< + { execId: string; userId: string; settled: boolean }[] + >` + SELECT exec_id AS "execId", user_id AS "userId", spend_settled_at_ms IS NOT NULL AS settled + FROM app.sandbox_session_ops WHERE org_id = ${orgId} AND session_id = ${erasureSession} + `; + const [erasureReceipt] = await sql< + { + status: string; + counts: { modelApiRequests?: number; automationRuns?: number }; + }[] + >` + SELECT status, counts FROM app.gdpr_erasure_requests WHERE id = ${erasureRequestId} + `; + let retiredAdmissionRefused = false; + try { + await reserveLlmStepBudget(sql, erasureReservation('erasure-too-late')); + } catch (error) { + retiredAdmissionRefused = + error instanceof Error && + error.message === 'The LLM effect attempt is no longer current'; + } + const lateUsage = { + organizationId: orgId, + sessionId: pendingRequest.sessionId, + execId: pendingRequest.execId, + usage: { inputTokens: 12, outputTokens: 3, cents: 2 }, + }; + await recordLlmStepUsage(sql, lateUsage); + await recordLlmStepUsage(sql, lateUsage); + const afterLateSettlement = await sql< + { userId: string; cost: number; requests: number }[] + >` + SELECT user_id AS "userId", cost_estimate_cents::float8 AS cost, request_count::int AS requests + FROM app.usage_ledger WHERE org_id = ${orgId} AND granularity = 'monthly' + AND agent_slug = ${erasureAutomation} + `; + const [personalUsage] = await sql<{ count: number }[]>` + SELECT count(*)::int AS count FROM app.usage_ledger + WHERE org_id = ${orgId} AND user_id = ANY(${[projectReaderId, `user:${projectReaderId}`, `api-key:${projectReaderId}`]}) + `; + record( + 'project budgets: erasure retires direct LLM producers and late settlement books once only under the erased-user pseudonym', + erasureReceipt?.status === 'done' && + erasureReceipt.counts.modelApiRequests === 2 && + erasureReceipt.counts.automationRuns === 1 && + afterErasure.length === 1 && + afterErasure[0]?.execId === pendingRequest.execId && + afterErasure[0]?.userId === 'erased-user' && + afterErasure[0] !== undefined && + !afterErasure[0].settled && + retiredAdmissionRefused && + personalUsage?.count === 0 && + afterLateSettlement.length === 1 && + afterLateSettlement[0]?.userId === 'erased-user' && + afterLateSettlement[0]?.cost === 2 && + afterLateSettlement[0]?.requests === 1, + JSON.stringify({ + erasureReceipt, + afterErasure, + retiredAdmissionRefused, + personalUsage, + afterLateSettlement, + }), + ); } finally { await unlink(budgetsFile).catch((error: unknown) => { console.warn('[itest] project budgets: budgets file not removed', error); @@ -443,7 +863,7 @@ export async function checkProjectBudgets( clearOrgConfigCaches(); await sql` DELETE FROM app.sandbox_session_ops - WHERE org_id = ${orgId} AND session_id = ANY(${[opSession, runSession]}) + WHERE org_id = ${orgId} AND session_id = ANY(${[opSession, runSession, llmSession, erasureSession]}) `; await sql` DELETE FROM app.sandbox_sessions @@ -451,7 +871,7 @@ export async function checkProjectBudgets( `; await sql.begin(async (fixtureTx) => { await markAutomationWriterInTx(fixtureTx); - await fixtureTx`DELETE FROM app.automation_runs WHERE id = ${runId}`; + await fixtureTx`DELETE FROM app.automation_runs WHERE id = ANY(${[runId, erasureRunId]})`; }); await sql` DELETE FROM app.automation_project_bindings @@ -465,7 +885,7 @@ export async function checkProjectBudgets( `; await sql` DELETE FROM app.usage_ledger - WHERE org_id = ${orgId} AND agent_slug = ANY(${[agentSlug, automationName]}) + WHERE org_id = ${orgId} AND agent_slug = ANY(${[agentSlug, automationName, erasureAutomation]}) `; await sql` DELETE FROM app.project_usage @@ -475,5 +895,8 @@ export async function checkProjectBudgets( await sql` DELETE FROM app.projects WHERE id = ANY(${[projectId, secondProjectId]}) `; + await sql`DELETE FROM app.gdpr_erasure_requests WHERE id = ${erasureRequestId}`; + await sql`DELETE FROM "member" WHERE "organizationId" = ${orgId} AND "userId" = ${projectReaderId}`; + await sql`DELETE FROM "user" WHERE "id" = ${projectReaderId}`; } } diff --git a/services/platform/backend/domains/governance/spec.md b/services/platform/backend/domains/governance/spec.md index 06ed2dd558..73ddbb9522 100644 --- a/services/platform/backend/domains/governance/spec.md +++ b/services/platform/backend/domains/governance/spec.md @@ -52,6 +52,15 @@ schedule started included, and binds nothing done outside the project. A run tha project, of an automation installed in several projects, is each one's work: it counts toward, and must fit, every one of their limits, as a member's spend counts toward each of their teams. +Voice output keeps the projects it was admitted under even if the conversation moves; an empty +project list remains empty. It reserves an estimate and one request while pending. Success books +its resolved rate; an already-reserved failure or stale replacement conservatively books its +saved estimate once, even when failure precedes the provider call. That estimate does not assert +that the provider charged it. A retry includes the predecessor estimate when checking the limit, +and a late result cannot bill it again. Ordinary audio age cleanup leaves pending attempts to +their watchdog. Authorized history purge and erasure retain their existing deletion behavior; +no strict budget guarantee overrides that privacy boundary. + - **Example**: The Website project is capped at 100 a month and has spent 100. Mia, far from her own limit, writes in one of the project's chats → refused, naming the project's limit. She can still chat outside the project. @@ -159,11 +168,11 @@ It counts only in the organization it was granted in. - **The usage pages** and their figures (`usage-metrics.ts`). - **A project's limit and transcription**: an audio or video file transcribed for a project's chat is booked to the person who added it, not to the project, and a project's limit warns - no one before it is reached. Voice output in a project is checked against its limit but holds - nothing while it is made. -- **An automation's model steps hold nothing while they run**: an `llm` step is checked against - the limits before each call and counted after it, but sets nothing aside meanwhile, so steps of - runs at the same moment can pass a nearly reached limit together. + no one before it is reached. +- **Legacy voice reservations**: previous writers left no saved price or project stamp. `NULL` + projects retain the current-thread fallback, unlike an explicitly empty project list; an + unknown legacy price is not invented. Every new admission receives the reservation guarantee + only after old writers retire. - **Nothing in the database forbids a start marker in place of a person in the usage ledger**, and **the per-turn usage table is retired but not dropped**; the contract debt ledger in [`.agents/repo.md`](../../../../../.agents/repo.md) records both. diff --git a/services/platform/backend/domains/model_api/retention.test.ts b/services/platform/backend/domains/model_api/retention.test.ts index 3b46897b3e..90cd7a4d58 100644 --- a/services/platform/backend/domains/model_api/retention.test.ts +++ b/services/platform/backend/domains/model_api/retention.test.ts @@ -44,18 +44,28 @@ describe('sweepSettledModelApiOps', () => { expect(deleted).toBe(3); expect(statements).toHaveLength(1); const [statement] = statements; - expect(statement?.text).toBe( - 'DELETE FROM app.sandbox_session_ops WHERE id IN ( ' + - 'SELECT id FROM app.sandbox_session_ops ' + - "WHERE kind = 'model-api' " + - "AND status <> 'running' " + - 'AND spend_settled_at_ms IS NOT NULL ' + - 'AND (key_revoked_at_ms IS NOT NULL OR minted_key_id IS NULL) ' + - 'AND started_at_ms < ? ' + - 'ORDER BY started_at_ms LIMIT ? ) RETURNING id', - ); + for (const kind of ['model-api', 'automation-llm']) { + expect(statement?.text).toContain( + `WHERE kind = '${kind}' AND status <> 'running'`, + ); + } + expect( + statement?.text.match(/AND spend_settled_at_ms IS NOT NULL/g), + ).toHaveLength(2); + expect( + statement?.text.match( + /AND \(key_revoked_at_ms IS NOT NULL OR minted_key_id IS NULL\)/g, + ), + ).toHaveLength(2); + expect(statement?.text).toContain('UNION ALL'); // The cutoff is a week before the tick; the default batch is 1,000. - expect(statement?.values).toEqual([NOW - WEEK_MS, 1_000]); + expect(statement?.values).toEqual([ + NOW - WEEK_MS, + 1_000, + NOW - WEEK_MS, + 1_000, + 1_000, + ]); }); it('spells the kind as the literal the partial index is declared on, never a bound value', async () => { @@ -83,7 +93,7 @@ describe('sweepSettledModelApiOps', () => { expect(deleted).toBe(5); expect(statements).toHaveLength(3); for (const statement of statements) { - expect(statement.values).toEqual([NOW - WEEK_MS, 2]); + expect(statement.values).toEqual([NOW - WEEK_MS, 2, NOW - WEEK_MS, 2, 2]); } }); diff --git a/services/platform/backend/domains/model_api/retention.ts b/services/platform/backend/domains/model_api/retention.ts index e208085a74..25265a344f 100644 --- a/services/platform/backend/domains/model_api/retention.ts +++ b/services/platform/backend/domains/model_api/retention.ts @@ -1,10 +1,10 @@ import type { Sql } from 'postgres'; /** - * The sweep of settled model-endpoint requests. + * The sweep of settled model-endpoint and direct automation LLM requests. * * Every request through the model endpoints for API keys is one row in - * `app.sandbox_session_ops` (`kind = 'model-api'`, `metering.ts`), so the + * `app.sandbox_session_ops` (`kind = 'model-api'` or `automation-llm`), so the * table grows by a row per request. The usage ledger is the durable record * of a request's spend: the op row only carries the request's budget hold * and its virtual key to the settlement. Once both are done — the spend @@ -41,22 +41,28 @@ export async function sweepSettledModelApiOps( const cutoff = (options.now ?? Date.now()) - SETTLED_OP_RETENTION_MS; let deleted = 0; for (let round = 0; round < maxBatches; round += 1) { - // `kind = 'model-api'` (`MODEL_API_OP_KIND`) is written as a literal, - // never a bound parameter: the planner matches a partial index only - // against a predicate it can prove, and - // `sandbox_session_ops_model_api_started` holds exactly these rows in - // `started_at_ms` order. + // Literal predicates retain both kinds' partial started-at indexes. + // Each input and the combined result are bounded; the existing total + // statement/row budget remains shared by both direct-call lanes. const rows = await sql<{ id: string }[]>` DELETE FROM app.sandbox_session_ops WHERE id IN ( - SELECT id FROM app.sandbox_session_ops - WHERE kind = 'model-api' - AND status <> 'running' - AND spend_settled_at_ms IS NOT NULL - AND (key_revoked_at_ms IS NOT NULL OR minted_key_id IS NULL) - AND started_at_ms < ${cutoff} - ORDER BY started_at_ms - LIMIT ${batch} + SELECT id FROM ( + (SELECT id, started_at_ms FROM app.sandbox_session_ops + WHERE kind = 'model-api' AND status <> 'running' + AND spend_settled_at_ms IS NOT NULL + AND (key_revoked_at_ms IS NOT NULL OR minted_key_id IS NULL) + AND started_at_ms < ${cutoff} + ORDER BY started_at_ms LIMIT ${batch}) + UNION ALL + (SELECT id, started_at_ms FROM app.sandbox_session_ops + WHERE kind = 'automation-llm' AND status <> 'running' + AND spend_settled_at_ms IS NOT NULL + AND (key_revoked_at_ms IS NOT NULL OR minted_key_id IS NULL) + AND started_at_ms < ${cutoff} + ORDER BY started_at_ms LIMIT ${batch}) + ) AS settled_direct_ops + ORDER BY started_at_ms LIMIT ${batch} ) RETURNING id `; diff --git a/services/platform/backend/domains/organizations/routes.test.ts b/services/platform/backend/domains/organizations/routes.test.ts index 2e66a973ea..270f862098 100644 --- a/services/platform/backend/domains/organizations/routes.test.ts +++ b/services/platform/backend/domains/organizations/routes.test.ts @@ -228,6 +228,17 @@ describe('POST /:id/delete', () => { ); }); + it('maps the database legacy-hold race to a conflict without leaking SQL details [ORG-R12]', async () => { + deleteOrganization.mockRejectedValue( + Object.assign(new Error('private SQL detail'), { code: 'P7502' }), + ); + const response = await remove({ confirmName: 'Acme' }); + expect(response.status).toBe(409); + const body = await response.json(); + expect(body).toMatchObject({ error: 'ORG_LEGACY_AUTOMATION_HELD' }); + expect(JSON.stringify(body)).not.toContain('private SQL detail'); + }); + it('answers the mismatch code the service raises, and sends an absent name as empty [ORG-R5]', async () => { const { OrganizationError } = await import('./service.ts'); deleteOrganization.mockRejectedValue( diff --git a/services/platform/backend/domains/organizations/routes.ts b/services/platform/backend/domains/organizations/routes.ts index eda2410043..0cce068081 100644 --- a/services/platform/backend/domains/organizations/routes.ts +++ b/services/platform/backend/domains/organizations/routes.ts @@ -19,6 +19,7 @@ import { hasAnyOrganizations } from './has-any-organizations.ts'; import { deleteOrganization, getOrganization, + legacyAutomationHoldError, listUserOrganizations, OrganizationError, recordOrgSwitch, @@ -187,6 +188,15 @@ export function createOrganizationRoutes(deps: { ); return c.json(result); } catch (error) { + // A cutover can race the preflight. Its trigger rolls back the whole + // transaction; report the same conflict without exposing SQL details. + if (isRecord(error) && error.code === 'P7502') { + const blocked = legacyAutomationHoldError(); + return c.json( + { error: blocked.code, message: blocked.message }, + blocked.status, + ); + } if (error instanceof OrganizationError) { return c.json( { error: error.code, message: error.message }, diff --git a/services/platform/backend/domains/organizations/service.test.ts b/services/platform/backend/domains/organizations/service.test.ts index 6733810798..e0a7e48d4c 100644 --- a/services/platform/backend/domains/organizations/service.test.ts +++ b/services/platform/backend/domains/organizations/service.test.ts @@ -38,6 +38,7 @@ interface Scenario { memberRole: string | null; slug: string | null; holds: { targetType: string; targetId: string }[]; + legacyHeld?: boolean; /** Rows the final `DELETE FROM "organization" … RETURNING` answers. */ orgDeleteReturns?: { id: string }[]; /** What `information_schema.columns` lists as org_id-bearing app tables. */ @@ -107,6 +108,9 @@ function createRecordingTx(scenario: Scenario): { if (text.includes('FROM app.legal_holds')) { return scenario.holds; } + if (text.includes('FROM app.automation_runs')) { + return scenario.legacyHeld ? [{ id: 'held-run' }] : []; + } if ( text === "SELECT set_config('tale.automation_writer_protocol', $, true)" ) { @@ -366,6 +370,29 @@ describe('deleteOrganization', () => { expect(sends).toEqual([]); }); + it('refuses a legacy execution hold before audit, cancellation or deletion [ORG-R12]', async () => { + const sends = installFakeBoss(); + const { tx, statements } = createRecordingTx({ + memberRole: 'owner', + slug: 'acme', + holds: [], + legacyHeld: true, + }); + await expect( + deleteOrganization(tx, { userId: OWNER_ID }, ORG_ID, 'Acme'), + ).rejects.toMatchObject({ + code: 'ORG_LEGACY_AUTOMATION_HELD', + status: 409, + }); + expect(statements.filter(isWrite)).toEqual([]); + expect(sends).toEqual([]); + const probe = statements.find((s) => + s.text.includes('FROM app.automation_runs'), + ); + expect(probe?.text).toContain('legacy_quarantine IS NOT NULL'); + expect(probe?.values).toEqual([ORG_ID]); + }); + it('refuses non-owners and the default organization before any write [ORG-R4] [ORG-R6]', async () => { const sends = installFakeBoss(); const admin = createRecordingTx({ diff --git a/services/platform/backend/domains/organizations/service.ts b/services/platform/backend/domains/organizations/service.ts index cd3a8c59e1..842d16911a 100644 --- a/services/platform/backend/domains/organizations/service.ts +++ b/services/platform/backend/domains/organizations/service.ts @@ -31,7 +31,7 @@ import { scheduleOrganizationSandboxRetirement } from '../sandbox/retirement-sch export class OrganizationError extends Error { readonly code: string; - readonly status: 400 | 401 | 403 | 404; + readonly status: 400 | 401 | 403 | 404 | 409; /** Structured detail a door hands on under `data` — the organizations a * key holder may name, on every refusal of the one it named (or did not). */ readonly data?: Record; @@ -39,7 +39,7 @@ export class OrganizationError extends Error { constructor( code: string, message: string, - status: 400 | 401 | 403 | 404, + status: 400 | 401 | 403 | 404 | 409, data?: Record, ) { super(message); @@ -467,6 +467,28 @@ export function describeOrganizationHoldBlock( return null; } +export function legacyAutomationHoldError(): OrganizationError { + return new OrganizationError( + 'ORG_LEGACY_AUTOMATION_HELD', + 'This organization has automation runs on hold because their earlier external actions have not been verified. The organization was preserved. A stop request does not release these holds.', + 409, + ); +} + +/** This guard precedes every deletion write. The database guards remain the + * authority if the cutover lands after the caller's transaction snapshot. */ +export async function assertNoLegacyAutomationHolds( + tx: TransactionSql, + organizationId: string, +): Promise { + const held = await tx<{ id: string }[]>` + SELECT id FROM app.automation_runs + WHERE org_id = ${organizationId} AND legacy_quarantine IS NOT NULL + LIMIT 1 + `; + if (held.length > 0) throw legacyAutomationHoldError(); +} + /** * The ONE deletion door — owner-only, whole teardown in the caller's * transaction so it either fully commits or leaves nothing behind. Order: @@ -547,6 +569,7 @@ export async function deleteOrganization( if (holdBlock !== null) { throw holdBlock; } + await assertNoLegacyAutomationHolds(tx, organizationId); await logSuccess(tx, { auditCtx: { diff --git a/services/platform/backend/domains/organizations/spec.md b/services/platform/backend/domains/organizations/spec.md index 12ac982a6b..33416360be 100644 --- a/services/platform/backend/domains/organizations/spec.md +++ b/services/platform/backend/domains/organizations/spec.md @@ -106,6 +106,18 @@ Each organization is listed with the person's one role in it. - **Example**: Mia's membership in a second organization was disabled → her organization switcher lists the first one only. +## Preserved automation runs + +### ORG-R12 · An organization with unresolved legacy automation holds cannot be deleted + +The delete is refused (`ORG_LEGACY_AUTOMATION_HELD`, 409) before audit or cleanup work starts. +A hold detected by the database during deletion returns the same conflict and rolls back +the whole deletion. These execution holds are separate from legal holds. A stop request +does not release them. + +- **Example**: An earlier automation run has unknown external outcomes. Ada deletes its + organization → the organization is preserved, with an explanation of the execution hold. + ## Not yet - **Creating an organization**: the creation itself is refused for someone who is not offered diff --git a/services/platform/backend/domains/sandbox/image-generation.test.ts b/services/platform/backend/domains/sandbox/image-generation.test.ts index 00a10924ba..ee35013070 100644 --- a/services/platform/backend/domains/sandbox/image-generation.test.ts +++ b/services/platform/backend/domains/sandbox/image-generation.test.ts @@ -24,7 +24,8 @@ const mocks = vi.hoisted(() => ({ setVirtualKeyBudget: vi.fn(), })); -vi.mock('./op-attribution.ts', () => ({ +vi.mock('./op-attribution.ts', async (importOriginal) => ({ + ...(await importOriginal()), resolveSessionOpAttribution: mocks.attribution, })); vi.mock('../governance/budget-gate.ts', () => ({ @@ -134,6 +135,31 @@ beforeEach(() => { }); describe('resolveImageTurnContext', () => { + it('keeps admitted projects while retaining live-run authorization [GOV-R14]', async () => { + const { sql } = scriptedSql([ + { match: 'FROM app.project_agent_runs', rows: [{ taskId: 'task_1' }] }, + { + match: 'FROM app.sandbox_session_ops', + rows: [{ projectIds: ['original-project'] }], + }, + ]); + mocks.attribution.mockResolvedValue({ + userId: 'user_starter', + projectIds: ['new-project'], + }); + await expect( + resolveImageTurnContext(sql, { + organizationId: 'org_1', + sessionId: 'pa-alice', + kind: 'task-agent', + execId: 'exec_1', + }), + ).resolves.toMatchObject({ + status: 'live', + subject: { projectIds: ['original-project'] }, + }); + }); + it('delivers a live task run into its task’s own box, for its starter', async () => { const { sql, statements } = scriptedSql([ { match: 'FROM app.project_agent_runs', rows: [{ taskId: 'task_1' }] }, @@ -242,6 +268,29 @@ describe('resolveImageTurnContext', () => { }); describe('admitImageGeneration', () => { + it.each([{ projectIds: ['original-project'] }, { projectIds: [] }])( + 'checks the projects held by the op even with stale image context: $projectIds [GOV-R14]', + async ({ projectIds }) => { + const { sql, statements } = opSql({ projectIds }); + const result = await admitImageGeneration( + sql, + { + ...ADMIT, + subject: { ...ADMIT.subject, projectIds: ['new-project'] }, + }, + deps, + ); + expect(result.admitted).toBe(true); + expect(mocks.findBudgetViolation).toHaveBeenCalledWith( + sql, + expect.objectContaining({ projectIds }), + expect.anything(), + ); + expect(holdWrite(statements)?.values).toContainEqual(projectIds); + expect(holdWrite(statements)?.values).not.toContainEqual(['new-project']); + }, + ); + it('admits under every bound, holding the estimate on the op row', async () => { const { sql, statements } = opSql(); await expect(admitImageGeneration(sql, ADMIT, deps)).resolves.toEqual({ @@ -283,15 +332,7 @@ describe('admitImageGeneration', () => { expect(write?.text).toContain('images_admitted = images_admitted + ?'); expect(write?.text).toContain('user_id = coalesce(user_id, ?)'); // A turn outside any project holds its images in none. - expect(write?.values).toEqual([ - NOW, - 75, - 3, - 3, - 'user_starter', - null, - 'op_1', - ]); + expect(write?.values).toEqual([NOW, 75, 3, 3, 'user_starter', [], 'op_1']); }); it('measures the images against what the allowance has left after the model’s live spend', async () => { @@ -537,6 +578,28 @@ describe('admitImageGeneration', () => { }); describe('settleImageGeneration', () => { + it.each([{ projectIds: ['original-project'] }, { projectIds: [] }])( + 'books the admitted projects after bindings changed during provider work: $projectIds [GOV-R14]', + async ({ projectIds }) => { + const { sql } = opSql({ projectIds }); + await settleImageGeneration(sql, { + organizationId: 'org_1', + sessionId: 'pa-alice', + execId: 'exec_1', + callStartedAt: NOW, + subject: { ...ADMIT.subject, projectIds: ['new-project'] }, + provider: 'provider', + model: 'model', + charges: [5], + timestamp: NOW, + }); + expect(mocks.incrementUsageLedger).toHaveBeenCalledWith( + sql, + expect.objectContaining({ projectIds, costEstimateCents: 5 }), + ); + }, + ); + const SETTLE = { organizationId: 'org_1', sessionId: 'pa-alice', diff --git a/services/platform/backend/domains/sandbox/image-generation.ts b/services/platform/backend/domains/sandbox/image-generation.ts index b38d30b123..926c49fb4b 100644 --- a/services/platform/backend/domains/sandbox/image-generation.ts +++ b/services/platform/backend/domains/sandbox/image-generation.ts @@ -24,6 +24,7 @@ import { incrementUsageLedger } from '../governance/service.ts'; import { resolveSessionOpAttribution, type SessionOpAttribution, + withSessionOpBillingProjects, } from './op-attribution.ts'; /** @@ -132,7 +133,11 @@ export async function resolveImageTurnContext( if (ops.length === 0) return { status: 'ended' }; outputDir = '/agent/output'; } - const attribution = await resolveSessionOpAttribution(sql, args); + const attribution = await withSessionOpBillingProjects( + sql, + args, + await resolveSessionOpAttribution(sql, args), + ); return { status: 'live', outputDir, subject: subjectOf(attribution) }; } @@ -319,10 +324,13 @@ export async function admitImageGeneration( `This turn's spend allowance has ${cents(Math.max(0, room))} left, and ${args.images === 1 ? 'an image is' : `${args.images} images are`} held at ${cents(holdCents)} until ${args.images === 1 ? 'its' : 'their'} cost is known.`, ); } + const billingSubject = subjectOf( + await withSessionOpBillingProjects(tx, args, args.subject), + ); const subject = await loadAttributedBudgetSubject( tx, args.organizationId, - args.subject, + billingSubject, ); const violation = await findBudgetViolation(tx, subject, { // Every hold in flight — this turn's own allowance too: its model may @@ -347,7 +355,7 @@ export async function admitImageGeneration( -- turn's) holds these images in its projects all the same. project_ids = coalesce( project_ids, - ${subject.projectIds !== undefined ? [...subject.projectIds] : null} + ${[...(subject.projectIds ?? [])]} ) WHERE id = ${op.id} `; @@ -440,6 +448,12 @@ export async function settleImageGeneration( const setKeyBudget = deps.setKeyBudget ?? setVirtualKeyBudget; const spent = args.charges.reduce((sum, charge) => sum + charge, 0); const settled = await sql.begin(async (tx) => { + // Settle against the admitted stamp, including an explicitly empty + // project list, even if a caller captured its context before a rebind. + const billingSubject = + args.charges.length === 0 + ? args.subject + : subjectOf(await withSessionOpBillingProjects(tx, args, args.subject)); for (const costCents of args.charges) { await incrementUsageLedger(tx, { organizationId: args.organizationId, @@ -450,8 +464,8 @@ export async function settleImageGeneration( ...(args.subject.apiKeyId !== undefined ? { apiKeyId: args.subject.apiKeyId } : {}), - ...(args.subject.projectIds !== undefined - ? { projectIds: args.subject.projectIds } + ...(billingSubject.projectIds !== undefined + ? { projectIds: billingSubject.projectIds } : {}), provider: args.provider, model: args.model, diff --git a/services/platform/backend/domains/sandbox/op-attribution.test.ts b/services/platform/backend/domains/sandbox/op-attribution.test.ts index 10c8e6ec32..f240d365c9 100644 --- a/services/platform/backend/domains/sandbox/op-attribution.test.ts +++ b/services/platform/backend/domains/sandbox/op-attribution.test.ts @@ -14,6 +14,7 @@ import { resolveAutomationRunAttribution, resolveSessionOpAttribution, splitModelRef, + withSessionOpBillingProjects, } from './op-attribution.ts'; interface Statement { @@ -39,6 +40,52 @@ const TASK_OP = { kind: 'task-agent', }; const WORKFLOW_OP = { ...TASK_OP, sessionId: 'wf-1', kind: 'workflow-agent' }; + +describe('admitted billing projects [GOV-R14]', () => { + it.each([{ projectIds: ['project-a', 'project-b'] }, { projectIds: [] }])( + 'preserves a non-null stamp after live bindings change: $projectIds', + async ({ projectIds }) => { + const { sql, statements } = fakeSql([ + { match: 'FROM app.sandbox_session_ops', rows: [{ projectIds }] }, + ]); + const subject = { + userId: 'current-user', + apiKeyId: 'key-1', + agentSlug: 'automation', + projectIds: ['project-a', 'project-c'], + }; + await expect( + withSessionOpBillingProjects(sql, WORKFLOW_OP, subject), + ).resolves.toEqual({ ...subject, projectIds }); + expect(statements[0]?.values).toEqual(['org-1', 'wf-1', 'exec-1']); + expect(statements[0]?.text).toContain('WHERE org_id = ?'); + }, + ); + + it.each([null, undefined])( + 'keeps legacy fallback for %j', + async (projectIds) => { + const { sql } = fakeSql([ + { + match: 'FROM app.sandbox_session_ops', + rows: projectIds === undefined ? [] : [{ projectIds }], + }, + ]); + const subject = { userId: 'user-1', projectIds: ['project-current'] }; + await expect( + withSessionOpBillingProjects(sql, WORKFLOW_OP, subject), + ).resolves.toEqual(subject); + }, + ); + + it('cannot turn missing attribution into an authorized subject', async () => { + const { sql, statements } = fakeSql([]); + await expect( + withSessionOpBillingProjects(sql, WORKFLOW_OP, null), + ).resolves.toBeNull(); + expect(statements).toHaveLength(0); + }); +}); /** The workflow session's owner: the automation run it executes. */ const SESSION = { match: 'FROM app.sandbox_sessions s', diff --git a/services/platform/backend/domains/sandbox/op-attribution.ts b/services/platform/backend/domains/sandbox/op-attribution.ts index 5def334503..83623bd88d 100644 --- a/services/platform/backend/domains/sandbox/op-attribution.ts +++ b/services/platform/backend/domains/sandbox/op-attribution.ts @@ -119,7 +119,8 @@ export async function resolveSessionOpAttribution( SELECT user_id AS "userId", agent_slug AS "agentSlug", api_key_id AS "apiKeyId", project_ids AS "projectIds" FROM app.sandbox_session_ops - WHERE session_id = ${args.sessionId} AND exec_id = ${args.execId} + WHERE org_id = ${args.organizationId} + AND session_id = ${args.sessionId} AND exec_id = ${args.execId} LIMIT 1 `; const op = stamped[0]; @@ -132,6 +133,28 @@ export async function resolveSessionOpAttribution( }; } +/** Billing keeps the projects admitted on the op, even after bindings move. + * Only legacy NULL stamps fall back to current run projects; [] explicitly + * means no project. Live run/member authorization stays with the caller. + * Take the budget admission lock before reading/writing a first stamp. */ +export async function withSessionOpBillingProjects( + sql: Sql | TransactionSql, + args: { organizationId: string; sessionId: string; execId: string }, + attribution: SessionOpAttribution | null, +): Promise { + if (attribution === null) return null; + const [op] = await sql<{ projectIds: string[] | null }[]>` + SELECT project_ids AS "projectIds" + FROM app.sandbox_session_ops + WHERE org_id = ${args.organizationId} + AND session_id = ${args.sessionId} AND exec_id = ${args.execId} + LIMIT 1 + `; + return op?.projectIds != null + ? { ...attribution, projectIds: op.projectIds } + : attribution; +} + /** What an automation run's billing subject is read from. */ interface AutomationRunRow { startedBy: string; diff --git a/services/platform/backend/domains/sandbox/spend-settlement.test.ts b/services/platform/backend/domains/sandbox/spend-settlement.test.ts index f34b7baac6..41b2e8e363 100644 --- a/services/platform/backend/domains/sandbox/spend-settlement.test.ts +++ b/services/platform/backend/domains/sandbox/spend-settlement.test.ts @@ -411,7 +411,7 @@ describe('reconcilePendingSessionOpKeys', () => { gateway.readVirtualKeySpend.mockResolvedValue({ status: 'unavailable' }); const { sql, statements } = fakeSql([ { - match: 'WHERE finalized_at_ms IS NOT NULL AND finalized_at_ms <', + match: 'WHERE ((finalized_at_ms IS NOT NULL AND finalized_at_ms <', rows: [ { organizationId: 'org-1', sessionId: 'pa-alice', execId: 'exec-1' }, ], @@ -439,7 +439,7 @@ describe('reconcilePendingSessionOpKeys', () => { expect(result).toEqual({ scanned: 1, settled: 0, pending: 1 }); const select = statements.find((s) => s.text.includes( - 'WHERE finalized_at_ms IS NOT NULL AND finalized_at_ms <', + 'WHERE ((finalized_at_ms IS NOT NULL AND finalized_at_ms <', ), ); expect(select?.text).toContain( @@ -601,3 +601,164 @@ describe('reconcilePendingSessionOpKeys — deferred settlements', () => { expect(statements[0]?.values).toContain(5_000_000); }); }); + +describe('direct LLM reconciliation', () => { + function fixture(overrides: Record = {}) { + return fakeSql([ + { + match: 'SELECT org_id AS "organizationId", kind, minted_key_id', + rows: [ + { + organizationId: 'org-1', + kind: 'automation-llm', + mintedKeyId: null, + finalizedAt: null, + spendSettledAt: null, + keyRevokedAt: null, + startedAtMs: 1, + settleAfter: null, + expectedCents: null, + floorCents: null, + budgetCents: 8, + reservedTokens: 8000, + ...overrides, + }, + ], + }, + { match: "status = 'failed'", rows: [{ id: 'op' }] }, + { + match: 'UPDATE app.sandbox_session_ops SET spent_cents', + rows: [ + { + organizationId: 'org-1', + kind: 'automation-llm', + modelRef: 'first/first/vendor/model', + inputTokens: 20, + outputTokens: 4, + }, + ], + }, + { + match: 'SELECT user_id AS "userId"', + rows: [ + { + userId: 'user-1', + agentSlug: 'flow', + apiKeyId: null, + projectIds: ['a', 'b'], + }, + ], + }, + { + match: 'SELECT project_ids AS "projectIds"', + rows: [{ projectIds: ['a', 'b'] }], + }, + ]); + } + const key = { + organizationId: 'org-1', + sessionId: 'direct', + execId: 'attempt', + }; + it('books known direct spend without a virtual key under its immutable project stamp', async () => { + const { sql } = fixture({ expectedCents: 2, finalizedAt: 10 }); + await expect(reconcileSessionOpKey(sql, key)).resolves.toEqual({ + spendSettled: true, + keyRevoked: true, + }); + expect(ledger.incrementUsageLedger).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + costEstimateCents: 2, + inputTokens: 20, + outputTokens: 4, + projectIds: ['a', 'b'], + provider: 'first', + model: 'vendor/model', + }), + ); + expect(gateway.readVirtualKeySpend).not.toHaveBeenCalled(); + }); + it('keeps an unknown direct call held until its bounded deadline', async () => { + const { sql, statements } = fixture({ startedAtMs: Date.now() }); + await expect(reconcileSessionOpKey(sql, key)).resolves.toEqual({ + spendSettled: false, + keyRevoked: true, + }); + expect(statements).toHaveLength(1); + expect(ledger.incrementUsageLedger).not.toHaveBeenCalled(); + }); + it('recovers a lost direct call at its reserved estimate, never the generic no-key zero', async () => { + const { sql, statements } = fixture(); + await reconcileSessionOpKey(sql, key); + expect(ledger.incrementUsageLedger).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + costEstimateCents: 8, + inputTokens: 8000, + outputTokens: 0, + }), + ); + expect( + statements.some( + ({ text }) => + text.includes('floor_cents = budget_cents') && + text.includes('expected_cents IS NULL'), + ), + ).toBe(true); + expect(gateway.revokeVirtualKey).not.toHaveBeenCalled(); + }); + it('leaves an invalid estimate unsettled instead of freeing its hold', async () => { + await expect( + reconcileSessionOpKey(fixture({ budgetCents: null }).sql, key), + ).rejects.toThrow('no valid settlement estimate'); + expect(ledger.incrementUsageLedger).not.toHaveBeenCalled(); + }); + it('does not book an already settled attempt twice', async () => { + await reconcileSessionOpKey(fixture({ spendSettledAt: 10 }).sql, key); + expect(ledger.incrementUsageLedger).not.toHaveBeenCalled(); + }); +}); + +describe('managed op immutable billing projects', () => { + it.each([{ projectIds: ['a', 'b'] }, { projectIds: [] }])( + 'books admitted $projectIds after live bindings change to A/C [GOV-R14]', + async ({ projectIds }) => { + const { sql } = fakeSql([ + { + match: 'UPDATE app.sandbox_session_ops SET spent_cents', + rows: [ + { + organizationId: 'org-1', + kind: 'workflow-agent', + modelRef: 'p/p/m', + }, + ], + }, + WORKFLOW_SESSION, + { + match: 'FROM app.automation_runs ar', + rows: [ + { + startedBy: 'user:user-1', + name: 'flow', + apiKeyId: null, + projectId: null, + boundProjectIds: ['a', 'c'], + }, + ], + }, + { match: 'SELECT project_ids AS "projectIds"', rows: [{ projectIds }] }, + ]); + await settleSessionOpSpend(sql, { + sessionId: 'workflow', + execId: 'op', + spentCents: 3, + }); + expect(ledger.incrementUsageLedger).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ projectIds }), + ); + }, + ); +}); diff --git a/services/platform/backend/domains/sandbox/spend-settlement.ts b/services/platform/backend/domains/sandbox/spend-settlement.ts index 4c75b5433f..6f699a1b59 100644 --- a/services/platform/backend/domains/sandbox/spend-settlement.ts +++ b/services/platform/backend/domains/sandbox/spend-settlement.ts @@ -1,5 +1,9 @@ import type { Sql, TransactionSql } from 'postgres'; +import { + AUTOMATION_LLM_OP_KIND, + AUTOMATION_LLM_LIFETIME_MS, +} from '../../core/automations/llm_budget.ts'; import { type GatewayKeySettlementOutcome, type GatewayKeySettlementPort, @@ -15,6 +19,7 @@ import { addJobInTx } from '../../jobs/enqueue.ts'; import { incrementUsageLedger } from '../governance/service.ts'; import { resolveSessionOpAttribution, + withSessionOpBillingProjects, splitModelRef, } from './op-attribution.ts'; @@ -70,6 +75,9 @@ export interface SessionOpSettlementRow { spendSettled: boolean; keyRevoked: boolean; hints: SpendHints; + startedAtMs: number; + budgetCents: number | null; + reservedTokens: number | null; } /** @@ -118,6 +126,9 @@ async function readSessionOpSettlement( settleAfter: number | null; floorCents: number | null; expectedCents: number | null; + startedAtMs: number; + budgetCents: number | null; + reservedTokens: number | null; }[] >` SELECT org_id AS "organizationId", kind, @@ -127,7 +138,9 @@ async function readSessionOpSettlement( key_revoked_at_ms::float8 AS "keyRevokedAt", settle_after_ms::float8 AS "settleAfter", floor_cents::float8 AS "floorCents", - expected_cents::float8 AS "expectedCents" + expected_cents::float8 AS "expectedCents", + started_at_ms::float8 AS "startedAtMs", budget_cents::float8 AS "budgetCents", + reserved_tokens::float8 AS "reservedTokens" FROM app.sandbox_session_ops WHERE session_id = ${args.sessionId} AND exec_id = ${args.execId} LIMIT 1 @@ -137,6 +150,9 @@ async function readSessionOpSettlement( return { organizationId: row.organizationId, kind: row.kind, + startedAtMs: row.startedAtMs, + budgetCents: row.budgetCents, + reservedTokens: row.reservedTokens, mintedKeyId: row.mintedKeyId, finalized: row.finalizedAt !== null, spendSettled: row.spendSettledAt !== null, @@ -208,12 +224,17 @@ export async function settleSessionOpSpend( }; const counted = usage.inputTokens > 0 || usage.outputTokens > 0; if (args.spentCents === null && !counted) return 'settled'; - const attribution = await resolveSessionOpAttribution(tx, { + const attributionArgs = { organizationId: op.organizationId, sessionId: args.sessionId, execId: args.execId, kind: op.kind, - }); + }; + const attribution = await withSessionOpBillingProjects( + tx, + attributionArgs, + await resolveSessionOpAttribution(tx, attributionArgs), + ); if (attribution === null) { // The fact is closed either way (the figure is on the op row); what is // lost is the ledger attribution, which needs a run to charge. @@ -312,6 +333,53 @@ export async function reconcileSessionOpKey( ): Promise { const op = await readSessionOpSettlement(sql, args); if (op === null || op.organizationId !== args.organizationId) return null; + if (op.kind === AUTOMATION_LLM_OP_KIND) { + if (op.spendSettled) return { spendSettled: true, keyRevoked: true }; + const known = op.hints.expectedCents !== null; + const deadline = + op.hints.settleAfterMs ?? op.startedAtMs + AUTOMATION_LLM_LIFETIME_MS; + if (!known && Date.now() < deadline) + return { spendSettled: false, keyRevoked: true }; + const cents = known ? op.hints.expectedCents : op.budgetCents; + if ( + cents === null || + !Number.isFinite(cents) || + cents < 0 || + (!known && + (op.reservedTokens === null || + !Number.isSafeInteger(op.reservedTokens) || + op.reservedTokens < 0)) + ) { + throw new Error( + 'The direct LLM reservation has no valid settlement estimate', + ); + } + if (!known) { + // A timeout/crash never proves zero spend. floor_cents marks the + // reserved estimate; expected_cents remains NULL (not reported usage). + const estimated = await sql<{ id: string }[]>` + UPDATE app.sandbox_session_ops SET + status = 'failed', finalized_at_ms = coalesce(finalized_at_ms, ${Date.now()}), + finished_at_ms = coalesce(finished_at_ms, ${Date.now()}), floor_cents = budget_cents + WHERE org_id = ${args.organizationId} AND session_id = ${args.sessionId} + AND exec_id = ${args.execId} AND kind = ${AUTOMATION_LLM_OP_KIND} + AND expected_cents IS NULL AND spend_settled_at_ms IS NULL + RETURNING id + `; + // A reported completion or another settlement won the row lock. + // Re-read its durable fact instead of replacing it with this estimate. + if (!estimated[0]) return reconcileSessionOpKey(sql, args); + } + await settleSessionOpSpend(sql, { + sessionId: args.sessionId, + execId: args.execId, + spentCents: cents, + ...(!known + ? { usage: { inputTokens: op.reservedTokens ?? 0, outputTokens: 0 } } + : {}), + }); + return { spendSettled: true, keyRevoked: true }; + } if ( op.hints.settleAfterMs !== null && Date.now() < op.hints.settleAfterMs && @@ -371,7 +439,9 @@ export async function reconcilePendingSessionOpKeys( SELECT org_id AS "organizationId", session_id AS "sessionId", exec_id AS "execId" FROM app.sandbox_session_ops - WHERE finalized_at_ms IS NOT NULL AND finalized_at_ms < ${cutoff} + WHERE ((finalized_at_ms IS NOT NULL AND finalized_at_ms < ${cutoff}) + OR (kind = ${AUTOMATION_LLM_OP_KIND} AND finalized_at_ms IS NULL + AND started_at_ms <= ${options.now - AUTOMATION_LLM_LIFETIME_MS})) AND (spend_settled_at_ms IS NULL OR (minted_key_id IS NOT NULL AND key_revoked_at_ms IS NULL)) AND (settle_after_ms IS NULL OR settle_after_ms <= ${options.now}) diff --git a/services/platform/backend/domains/sandbox/turn-budget.test.ts b/services/platform/backend/domains/sandbox/turn-budget.test.ts index 9841f6b10e..2a0edb6864 100644 --- a/services/platform/backend/domains/sandbox/turn-budget.test.ts +++ b/services/platform/backend/domains/sandbox/turn-budget.test.ts @@ -75,6 +75,33 @@ beforeEach(() => { }); describe('reserveTurnBudget', () => { + it.each([{ projectIds: ['original-project'] }, { projectIds: [] }])( + 're-admits an existing op against its immutable projects: $projectIds [GOV-R14]', + async ({ projectIds }) => { + gate.resolveTurnAllowance.mockResolvedValue({ + allowed: true, + budgetCents: 10, + }); + const { sql, statements } = fakeSql([ + { match: 'SELECT project_ids AS', rows: [{ projectIds }] }, + ]); + await reserveTurnBudget(sql, { + ...ARGS, + kind: 'model-api', + subject: { userId: 'user-1', projectIds: ['new-project'] }, + }); + expect(gate.resolveTurnAllowance).toHaveBeenCalledWith( + sql, + expect.objectContaining({ projectIds }), + ); + const write = statements.find((s) => + s.text.includes('INSERT INTO app.sandbox_session_ops'), + ); + expect(write?.values).toContainEqual(projectIds); + expect(write?.values).not.toContainEqual(['new-project']); + }, + ); + it('evaluates the allowance for the starter with the in-flight reservations and records it [SBX-R16]', async () => { gate.resolveTurnAllowance.mockResolvedValue({ allowed: true, @@ -541,7 +568,7 @@ describe('reserveTurnBudget', () => { expect(projectStamp(statements)).toEqual(['project-1', 'project-2']); }); - it('stamps no project on work outside one', async () => { + it('stamps an authoritative empty project list on work outside one', async () => { gate.resolveTurnAllowance.mockResolvedValue({ allowed: true, budgetCents: 500, @@ -553,7 +580,7 @@ describe('reserveTurnBudget', () => { }, ]); await reserveTurnBudget(sql, ARGS); - expect(projectStamp(statements)).toBeNull(); + expect(projectStamp(statements)).toEqual([]); }); }); }); diff --git a/services/platform/backend/domains/sandbox/turn-budget.ts b/services/platform/backend/domains/sandbox/turn-budget.ts index 181e6bbb8b..bce5a9795a 100644 --- a/services/platform/backend/domains/sandbox/turn-budget.ts +++ b/services/platform/backend/domains/sandbox/turn-budget.ts @@ -13,6 +13,7 @@ import { lockOrgAdmission } from './admission-lock.ts'; import { resolveSessionOpAttribution, type SessionOpAttribution, + withSessionOpBillingProjects, } from './op-attribution.ts'; /** @@ -45,7 +46,7 @@ export async function reserveTurnBudget( /** `model-api`: one request through the model endpoints for API keys * (`domains/model_api`), which has no run behind it and names its * subject itself. */ - kind: 'task-agent' | 'workflow-agent' | 'model-api'; + kind: 'task-agent' | 'workflow-agent' | 'model-api' | 'automation-llm'; defaultBudgetCents: number; modelRef?: string; /** The harness this turn runs on — the op row's own record, which the @@ -56,6 +57,10 @@ export async function reserveTurnBudget( * `__direct_api__`, with the key. Stamped on the op row, where the * settlement's attribution finds it (`resolveSessionOpAttribution`). */ subject?: SessionOpAttribution; + /** Backend-only direct LLM admission: validate the live effect attempt + * and resolve its billing subject under the shared budget lock. Throw + * on a stale/replayed call to roll back the entire reservation. */ + prepareSubject?: (tx: TransactionSql) => Promise; /** Admit the default whole or not at all, with this many tokens: the * model endpoints' hold is the request's worst case, never a budget to * shrink to what remains (`resolveTurnAllowance`'s `whole`). The tokens @@ -68,13 +73,36 @@ export async function reserveTurnBudget( concurrencyLimit?: number; }, ): Promise { + if (args.kind === 'automation-llm') { + if ( + args.whole === undefined || + args.prepareSubject === undefined || + args.subject !== undefined + ) { + throw new Error( + 'A direct automation LLM reservation needs its complete estimate and live attempt subject', + ); + } + } else if (args.prepareSubject !== undefined) { + throw new Error( + 'Only a direct automation LLM reservation can prepare an effect subject', + ); + } const defaultCents = Math.max(1, Math.floor(args.defaultBudgetCents)); return sql.begin(async (tx) => { - if (args.kind !== 'model-api') { + if (args.kind !== 'model-api' && args.kind !== 'automation-llm') { await lockOrgAdmission(tx, args.organizationId); } - const attribution = - args.subject ?? (await resolveSessionOpAttribution(tx, args)); + // Read after the shared lock: a prior admission of this op may have + // committed its projects while this transaction waited. + await lockBudgetAdmission(tx, args.organizationId); + const attribution = await withSessionOpBillingProjects( + tx, + args, + args.prepareSubject !== undefined + ? await args.prepareSubject(tx) + : (args.subject ?? (await resolveSessionOpAttribution(tx, args))), + ); const userId = attribution?.userId ?? ''; // Nobody to measure — an op without a run to attribute, or a run a // trigger started — is evaluated against the organization's caps (and @@ -89,7 +117,6 @@ export async function reserveTurnBudget( // The chat lane's opens take the same budget-admission lock and hold on // their generation rows: the allowance counts live chat turns as well // as the unsettled ops, and they count it. - await lockBudgetAdmission(tx, args.organizationId); if (args.concurrencyLimit !== undefined && userId !== '') { const busy = await runningRequestsOf(tx, { organizationId: args.organizationId, @@ -135,7 +162,7 @@ export async function reserveTurnBudget( ${args.kind}, 'running', ${userId === '' ? null : userId}, ${attribution?.agentSlug ?? null}, ${attribution?.apiKeyId ?? null}, - ${subject.projectIds !== undefined ? [...subject.projectIds] : null}, + ${[...(subject.projectIds ?? [])]}, ${args.modelRef ?? null}, ${args.harness ?? null}, ${allowance.budgetCents}, ${args.whole?.prospectiveTokens ?? null}, ${now}, ${now} diff --git a/services/platform/backend/domains/sandbox/watchdogs.test.ts b/services/platform/backend/domains/sandbox/watchdogs.test.ts index 28e554d5c9..2bbe1442a1 100644 --- a/services/platform/backend/domains/sandbox/watchdogs.test.ts +++ b/services/platform/backend/domains/sandbox/watchdogs.test.ts @@ -840,10 +840,16 @@ describe('runSandboxWatchdog — settled model-endpoint request rows', () => { ); // Two rows came back from a batch of 1,000: one statement drained it. expect(sweeps).toHaveLength(1); - expect(sweeps[0]?.values).toEqual([NOW - WEEK_MS, 1_000]); + expect(sweeps[0]?.values).toEqual([ + NOW - WEEK_MS, + 1_000, + NOW - WEEK_MS, + 1_000, + 1_000, + ]); const close = indexOf(statements, "status = 'failed', finished_at_ms"); const sweep = indexOf(statements, "WHERE kind = 'model-api'"); - const settle = indexOf(statements, 'WHERE finalized_at_ms IS NOT NULL'); + const settle = indexOf(statements, 'WHERE ((finalized_at_ms IS NOT NULL'); expect(close).toBeGreaterThanOrEqual(0); expect(sweep).toBeGreaterThan(close); expect(settle).toBeGreaterThan(sweep); @@ -887,7 +893,7 @@ describe('runSandboxWatchdog — settled model-endpoint request rows', () => { failure, ); expect( - indexOf(statements, 'WHERE finalized_at_ms IS NOT NULL'), + indexOf(statements, 'WHERE ((finalized_at_ms IS NOT NULL'), ).toBeGreaterThan( indexOf(statements, 'DELETE FROM app.sandbox_session_ops'), ); diff --git a/services/platform/backend/domains/sandbox/workspace-write-shim.ts b/services/platform/backend/domains/sandbox/workspace-write-shim.ts index 39ad4b7df7..24f2cf08b6 100644 --- a/services/platform/backend/domains/sandbox/workspace-write-shim.ts +++ b/services/platform/backend/domains/sandbox/workspace-write-shim.ts @@ -10,7 +10,10 @@ import { } from '../documents/agent-write.ts'; import { readAgentTaskReviewSummaries } from '../tasks/agent-review-discovery.ts'; import { readAgentTaskReviewFiles } from '../tasks/agent-review-files.ts'; -import { readTaskWorkState } from '../tasks/agent-work-state.ts'; +import { + readTaskOccupancy, + readTaskWorkState, +} from '../tasks/agent-work-state.ts'; import { addTaskComment } from '../tasks/comments.ts'; import { upsertTaskByExternalRef } from '../tasks/external-ref.ts'; import { @@ -132,6 +135,12 @@ export function workspaceWriteShimHandlers(sql: Sql): ShimHandlers { ); }, + 'tasks/internal_queries:getTaskOccupancyForAgent': async (raw) => { + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- internal bridge passes this shape after checking the same task scope as full reads + const args = raw as Parameters[1]; + return readTaskOccupancy(sql, args); + }, + 'tasks/internal_queries:getTaskWorkStateForAgent': async (raw) => { // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- shim boundary: the bridge passes exactly this shape, after its scope check const args = raw as Parameters[1]; diff --git a/services/platform/backend/domains/tasks/agent-read-tools.integration.ts b/services/platform/backend/domains/tasks/agent-read-tools.integration.ts index ace09568d9..51c8c487b0 100644 --- a/services/platform/backend/domains/tasks/agent-read-tools.integration.ts +++ b/services/platform/backend/domains/tasks/agent-read-tools.integration.ts @@ -862,11 +862,32 @@ export async function checkAgentTaskReadTools( const retryBefore = await dispatch(m1, 'task_get', { taskId: pendingRetryTask, }); + const compactRetryBefore = await dispatch(m1, 'task_get', { + taskId: pendingRetryTask, + view: 'occupancy', + requestedRunId: pendingRetryRun.runId, + }); await sql` UPDATE app.project_agent_runs SET auto_retry_refused_at_ms = ${Date.now()} WHERE id = ${pendingRetryRun.runId} AND org_id = ${orgId} `; + const compactRetryAfter = await dispatch(m1, 'task_get', { + taskId: pendingRetryTask, + view: 'occupancy', + requestedRunId: pendingRetryRun.runId, + }); + record( + 'compact task occupancy: the exact latest failed run retains the native retry arm and its retirement', + recordAt(out(compactRetryBefore), 'requestedRun').retryPending === true && + recordAt(out(compactRetryAfter), 'requestedRun').retryPending === + false && + recordAt(out(compactRetryBefore), 'currentRun').runId === + pendingRetryRun.runId && + recordAt(out(compactRetryAfter), 'currentRun').runId === + pendingRetryRun.runId, + `before=${String(recordAt(out(compactRetryBefore), 'requestedRun').retryPending)} after=${String(recordAt(out(compactRetryAfter), 'requestedRun').retryPending)}`, + ); const retryAfter = await dispatch(m1, 'task_get', { taskId: pendingRetryTask, }); @@ -1001,6 +1022,202 @@ export async function checkAgentTaskReadTools( `foreign=${JSON.stringify(foreignRead)} member=${memberFind.ids.length}/${String(memberGet.status)}/${String(memberForeign.status)} outsider=${outsiderFind.ids.length}`, ); + // ---- compact requested/current occupancy through the authenticated door -- + const occupancyTask = await insertTask({ + projectId: projectA, + title: 'Compact occupancy fixture', + agentId: worker, + }); + const oldOccupant = await agentRun({ + agentId: worker, + taskId: occupancyTask, + status: 'failed', + failureCode: 'harness_error', + autoRetryArmedAt: now, + }); + const newOccupant = await agentRun({ + agentId: worker, + taskId: occupancyTask, + status: 'queued', + }); + const compactArgs = { + taskId: occupancyTask, + view: 'occupancy', + requestedRunId: oldOccupant.runId, + }; + const compact = await dispatch(m1, 'task_get', compactArgs); + const occupancy = out(compact); + const currentOccupant = recordAt(occupancy, 'currentRun'); + const requestedOccupant = recordAt(occupancy, 'requestedRun'); + record( + 'compact task occupancy: an exact old requested failure cannot hide a newer queued occupant or inherit its retry state', + compact.status === 'ok' && + occupancy.view === 'occupancy' && + currentOccupant.runId === newOccupant.runId && + currentOccupant.live === true && + requestedOccupant.runId === oldOccupant.runId && + requestedOccupant.live === false && + requestedOccupant.retryPending === false && + [ + 'comments', + 'project', + 'pendingReview', + 'reviewFiles', + 'idle', + 'canStart', + ].every((key) => !(key in occupancy)) && + [currentOccupant, requestedOccupant].every( + (run) => !('feedback' in run) && !('error' in run), + ) && + typeof recordAt(occupancy, 'observed').completedAt === 'string', + `current=${String(currentOccupant.runId)} requested=${String(requestedOccupant.runId)} status=${String(compact.status)}`, + ); + const unknownOccupant = await dispatch(m1, 'task_get', { + ...compactArgs, + requestedRunId: randomUUID(), + }); + const wrongTaskOccupant = await dispatch(m1, 'task_get', { + ...compactArgs, + requestedRunId: liveRun.runId, + }); + const neighbourOccupant = await dispatch(m1, 'task_get', { + ...compactArgs, + requestedRunId: outsiderRun.runId, + }); + let foreignOrgOccupant: Body; + // Deliberately corrupt only this inert fixture's org binding: even a run + // whose task foreign key points here must not pass the tenant predicate. + try { + await sql`UPDATE app.project_agent_runs SET org_id = ${`foreign-occupancy-${suffix}`} WHERE id = ${oldOccupant.runId}`; + foreignOrgOccupant = await dispatch(m1, 'task_get', compactArgs); + } finally { + await sql`UPDATE app.project_agent_runs SET org_id = ${orgId} WHERE id = ${oldOccupant.runId}`; + } + record( + 'compact task occupancy: missing, wrong-task, sibling-project and foreign-organization requested runs share the same unavailable refusal', + unknownOccupant.status === 'not_found' && + [wrongTaskOccupant, neighbourOccupant, foreignOrgOccupant].every( + (result) => + JSON.stringify(result) === JSON.stringify(unknownOccupant), + ) && + !('output' in unknownOccupant), + `statuses=${[unknownOccupant, wrongTaskOccupant, neighbourOccupant, foreignOrgOccupant].map((result) => String(result.status)).join(',')}`, + ); + const compactForeign = await dispatch(m1, 'task_get', { + taskId: foreignTask, + view: 'occupancy', + }); + const compactMissing = await dispatch(m1, 'task_get', { + taskId: randomUUID(), + view: 'occupancy', + }); + const compactAsk = out( + await dispatch(m1, 'task_get', { taskId: askTask, view: 'occupancy' }), + ); + record( + 'compact task occupancy: project scope stays closed and a workflow waiting on a person remains live', + compactForeign.status === 'not_found' && + JSON.stringify(compactForeign) === JSON.stringify(compactMissing) && + recordAt(compactAsk, 'workflowRun').runId === askRun && + recordAt(compactAsk, 'workflowRun').live === true && + recordAt(compactAsk, 'workflowRun').waitingFor === 'ask' && + !('ask' in recordAt(compactAsk, 'workflowRun')), + `foreign=${String(compactForeign.status)} waitingFor=${String(recordAt(compactAsk, 'workflowRun').waitingFor)}`, + ); + const deniedTask = await insertTask({ + projectId: projectA, + title: 'Compact read grant fixture', + agentId: manager, + }); + const deniedRun = await agentRun({ + agentId: manager, + taskId: deniedTask, + status: 'running', + grants: ['task_find'], + }); + const noReadGrant = await dispatch( + deniedRun.token, + 'task_get', + compactArgs, + ); + await settle(deniedRun.runId); + const grantedRun = await agentRun({ + agentId: manager, + taskId: deniedTask, + status: 'running', + }); + const activeRead = await dispatch( + grantedRun.token, + 'task_get', + compactArgs, + ); + await settle(grantedRun.runId); + const endedRead = await dispatch(grantedRun.token, 'task_get', compactArgs); + record( + 'compact task occupancy: the existing read grant and live session authority remain required', + activeRead.status === 'ok' && + noReadGrant.status !== 'ok' && + endedRead.status !== 'ok' && + !('output' in noReadGrant) && + !('output' in endedRead), + `missingGrant=${String(noReadGrant.status)} active=${String(activeRead.status)} ended=${String(endedRead.status)}`, + ); + + await sql`UPDATE app.tasks SET description = ${'Synthetic occupancy context. '.repeat(650)} WHERE id = ${occupancyTask}`; + const fullSample = await dispatch(m1, 'task_get', { + taskId: occupancyTask, + }); + const compactSample = await dispatch(m1, 'task_get', compactArgs); + const fullBytes = Buffer.byteLength(JSON.stringify(fullSample)); + const compactBytes = Buffer.byteLength(JSON.stringify(compactSample)); + const fullTimes: number[] = []; + const compactTimes: number[] = []; + let observationsOk = true; + for (let sample = 0; sample < 10; sample++) { + const fullStarted = performance.now(); + const fullObservation = await dispatch(m1, 'task_get', { + taskId: occupancyTask, + }); + fullTimes.push(performance.now() - fullStarted); + const compactStarted = performance.now(); + const compactObservation = await dispatch(m1, 'task_get', compactArgs); + compactTimes.push(performance.now() - compactStarted); + observationsOk &&= + fullObservation.status === 'ok' && + compactObservation.status === 'ok' && + recordAt(out(compactObservation), 'currentRun').runId === + newOccupant.runId && + recordAt(out(compactObservation), 'requestedRun').runId === + oldOccupant.runId; + } + const timing = (values: number[]) => { + const sorted = values.toSorted((a, b) => a - b); + return { + medianMs: Math.round(sorted[5] ?? 0), + p95Ms: Math.round(sorted[9] ?? 0), + }; + }; + record( + 'compact task occupancy: synthetic full-context response shrinks by at least 75 percent; twenty sequential native reads retain exact identities', + fullSample.status === 'ok' && + compactSample.status === 'ok' && + observationsOk && + compactBytes < fullBytes / 4 && + compactBytes < 4096 && + textAt(recordAt(out(fullSample), 'task'), 'description').startsWith( + 'Synthetic occupancy context.', + ) && + !('description' in recordAt(out(compactSample), 'task')), + JSON.stringify({ + fullBytes, + compactBytes, + samplesPerView: 10, + full: timing(fullTimes), + compact: timing(compactTimes), + latencyThresholdAsserted: false, + }), + ); + // ---- what stays a person's --------------------------------------------- // The answer names the task's own agent while nothing runs on the task: // the case in which a person's @mention starts a rework run. diff --git a/services/platform/backend/domains/tasks/agent-runs.test.ts b/services/platform/backend/domains/tasks/agent-runs.test.ts index 03cab31c41..47bab59895 100644 --- a/services/platform/backend/domains/tasks/agent-runs.test.ts +++ b/services/platform/backend/domains/tasks/agent-runs.test.ts @@ -727,6 +727,21 @@ describe('listTaskAgentRunSummaries — the runs an agent reading its task sees' ); }); + it('binds an exact requested run to both the organization and task', async () => { + const { sql, statements } = recording(); + await listTaskAgentRunSummaries(sql, { + organizationId: 'org-1', + taskId: 'task-1', + limit: 1, + runId: 'old-run', + }); + expect(statements[0]?.text).toContain('WHERE org_id = ? AND task_id = ?'); + expect(statements[0]?.text).toContain('AND (?::text IS NULL OR id = ?)'); + expect(statements[0]?.values).toEqual( + expect.arrayContaining(['org-1', 'task-1', 'old-run', 1]), + ); + }); + it('reads identity, status, timing and a feedback excerpt — never the transcript or the workspace', async () => { const { sql, statements } = recording(); await listTaskAgentRunSummaries(sql, { @@ -803,6 +818,7 @@ describe('listTaskAgentRunSummaries — the runs an agent reading its task sees' rows: Row[], retryHistory: Row[], beforeSeq?: number, + runId?: string, ) { const { sql, statements } = fakeSql((text) => text.includes('auto_retry_refused_at_ms::float8') ? retryHistory : rows, @@ -812,6 +828,7 @@ describe('listTaskAgentRunSummaries — the runs an agent reading its task sees' taskId: 'task-1', limit: 5, ...(beforeSeq !== undefined ? { beforeSeq } : {}), + ...(runId !== undefined ? { runId } : {}), }); return { runs, statements }; } @@ -867,6 +884,16 @@ describe('listTaskAgentRunSummaries — the runs an agent reading its task sees' expect(runs[0]?.retryPending).toBe(false); }); + it('does not lend a newer armed retry to an exact historical requested run', async () => { + const { runs } = await readRetryState( + [summary({ id: 'old-run' })], + [history()], + undefined, + 'old-run', + ); + expect(runs[0]).toMatchObject({ id: 'old-run', retryPending: false }); + }); + it('only the newest row can have a pending retry, with one budget read per page', async () => { const { runs, statements } = await readRetryState( [summary(), summary({ id: 'older-run', seq: 3 })], diff --git a/services/platform/backend/domains/tasks/agent-runs.ts b/services/platform/backend/domains/tasks/agent-runs.ts index 05a4188d03..07ae00eb14 100644 --- a/services/platform/backend/domains/tasks/agent-runs.ts +++ b/services/platform/backend/domains/tasks/agent-runs.ts @@ -1151,6 +1151,8 @@ export async function listTaskAgentRunSummaries( taskId: string; limit: number; beforeSeq?: number; + /** Exact requested run, still bound to this organization and task. */ + runId?: string; }, ): Promise { const rows = await sql< @@ -1173,6 +1175,7 @@ export async function listTaskAgentRunSummaries( false) AS "feedbackTruncated" FROM app.project_agent_runs WHERE org_id = ${args.organizationId} AND task_id = ${args.taskId} + AND (${args.runId ?? null}::text IS NULL OR id = ${args.runId ?? null}) AND (${args.beforeSeq ?? null}::bigint IS NULL OR seq < ${args.beforeSeq ?? null}::bigint) ORDER BY seq DESC diff --git a/services/platform/backend/domains/tasks/agent-work-state.test.ts b/services/platform/backend/domains/tasks/agent-work-state.test.ts index d40f5c99ae..51e5c7bcb2 100644 --- a/services/platform/backend/domains/tasks/agent-work-state.test.ts +++ b/services/platform/backend/domains/tasks/agent-work-state.test.ts @@ -11,7 +11,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { getPendingAskForRun } from '../automations/store.ts'; import { listTaskAgentRunSummaries } from './agent-runs.ts'; -import { readTaskWorkState } from './agent-work-state.ts'; +import { readTaskOccupancy, readTaskWorkState } from './agent-work-state.ts'; import { findLatestAutomationRunForTask, findLiveAutomationRunForTask, @@ -74,6 +74,73 @@ describe('readTaskWorkState', () => { vi.mocked(readTaskReviewDelegation).mockReset().mockResolvedValue(null); }); + it('keeps an exact historical run beside the newest occupant without review reads', async () => { + vi.mocked(listTaskAgentRunSummaries).mockImplementation( + async (_sql, args) => + args.runId === 'old' + ? [summary('old', 1, 'failed')] + : [summary('new', 2, 'running')], + ); + const state = await readTaskOccupancy(sql, { + ...ARGS, + requestedRunId: 'old', + }); + expect(state).toMatchObject({ + currentRun: { id: 'new', status: 'running' }, + requestedRun: { id: 'old', status: 'failed', retryPending: false }, + workflowRun: null, + }); + expect(listTaskAgentRunSummaries).toHaveBeenNthCalledWith(2, sql, { + organizationId: 'org-1', + taskId: 't-1', + limit: 1, + runId: 'old', + }); + expect(getPendingReviewForTask).not.toHaveBeenCalled(); + expect(readTaskReviewDecision).not.toHaveBeenCalled(); + expect(readTaskReviewDelegation).not.toHaveBeenCalled(); + }); + + it('reuses the exact newest requested run and preserves an armed retry', async () => { + vi.mocked(listTaskAgentRunSummaries).mockResolvedValue([ + { ...summary('new', 2, 'failed'), retryPending: true }, + ]); + const state = await readTaskOccupancy(sql, { + ...ARGS, + requestedRunId: 'new', + }); + expect(state?.requestedRun).toBe(state?.currentRun); + expect(state?.requestedRun?.retryPending).toBe(true); + expect(listTaskAgentRunSummaries).toHaveBeenCalledTimes(1); + }); + + it('refuses a missing requested run before reading workflows', async () => { + expect( + await readTaskOccupancy(sql, { ...ARGS, requestedRunId: 'missing' }), + ).toBeNull(); + expect(findLiveAutomationRunForTask).not.toHaveBeenCalled(); + expect(findLatestAutomationRunForTask).not.toHaveBeenCalled(); + expect(getPendingReviewForTask).not.toHaveBeenCalled(); + }); + + it('keeps workflow wait semantics in compact occupancy and propagates read failures', async () => { + vi.mocked(findLiveAutomationRunForTask).mockResolvedValue({ + runId: 'waiting-run', + name: 'workflow', + status: 'waiting', + version: 1, + detail: 'agent:worker', + }); + expect(await readTaskOccupancy(sql, ARGS)).toMatchObject({ + currentRun: null, + workflowRun: { runId: 'waiting-run', live: true, waitingFor: 'agent' }, + }); + vi.mocked(listTaskAgentRunSummaries).mockRejectedValue( + new Error('unavailable'), + ); + await expect(readTaskOccupancy(sql, ARGS)).rejects.toThrow('unavailable'); + }); + it('reads one run past the page to say whether an older page exists', async () => { vi.mocked(listTaskAgentRunSummaries).mockResolvedValue([ summary('run-3', 13, 'running'), diff --git a/services/platform/backend/domains/tasks/agent-work-state.ts b/services/platform/backend/domains/tasks/agent-work-state.ts index 61428f33cf..bf96cb5b92 100644 --- a/services/platform/backend/domains/tasks/agent-work-state.ts +++ b/services/platform/backend/domains/tasks/agent-work-state.ts @@ -108,9 +108,43 @@ export async function readTaskWorkState( projectId: args.projectId, taskId: args.taskId, }; + const workflowRun = await readTaskWorkflowRunState(sql, subject); + const review = await getPendingReviewForTask( + sql, + args.organizationId, + args.taskId, + ); + return { + agentRuns: runs.slice(0, runLimit), + agentRunsHasMore: runs.length > runLimit, + workflowRun, + reviewDecision: await readTaskReviewDecision(sql, subject), + reviewDelegation: await readTaskReviewDelegation(sql, subject), + pendingReview: + review === null + ? null + : { + approvalId: review.approvalId, + round: review.round, + runId: review.runId, + requestedFor: review.requestedFor, + reviewer: review.reviewer, + implementationAgentId: review.implementationAgentId, + evidenceRevision: review.evidenceRevision, + agentReviewBlockedReason: review.agentReviewBlockedReason, + createdAt: review.createdAt, + }, + }; +} + +/** The common workflow projection; compact occupancy never reads review state. */ +async function readTaskWorkflowRunState( + sql: Sql, + args: { organizationId: string; projectId: string; taskId: string }, +): Promise { const automation = - (await findLiveAutomationRunForTask(sql, subject)) ?? - (await findLatestAutomationRunForTask(sql, subject)); + (await findLiveAutomationRunForTask(sql, args)) ?? + (await findLatestAutomationRunForTask(sql, args)); let workflowRun: TaskWorkflowRunState | null = null; if (automation !== null) { const live = LIVE_AUTOMATION_STATUSES.has(automation.status); @@ -143,30 +177,46 @@ export async function readTaskWorkState( : {}), }; } - const review = await getPendingReviewForTask( - sql, - args.organizationId, - args.taskId, - ); + return workflowRun; +} + +export interface TaskOccupancyState { + currentRun: TaskAgentRunSummary | null; + requestedRun?: TaskAgentRunSummary; + workflowRun: TaskWorkflowRunState | null; +} + +/** A bounded observation, not an atomic snapshot or permission to start work. + * Missing requested identities fail the whole read instead of substituting + * the newest run or reporting an apparently idle task. */ +export async function readTaskOccupancy( + sql: Sql, + args: { + organizationId: string; + projectId: string; + taskId: string; + requestedRunId?: string; + }, +): Promise { + const subject = { organizationId: args.organizationId, taskId: args.taskId }; + const [currentRun] = await listTaskAgentRunSummaries(sql, { + ...subject, + limit: 1, + }); + let requestedRun: TaskAgentRunSummary | undefined; + if (args.requestedRunId !== undefined) { + if (currentRun?.id === args.requestedRunId) requestedRun = currentRun; + else + [requestedRun] = await listTaskAgentRunSummaries(sql, { + ...subject, + limit: 1, + runId: args.requestedRunId, + }); + if (requestedRun === undefined) return null; + } return { - agentRuns: runs.slice(0, runLimit), - agentRunsHasMore: runs.length > runLimit, - workflowRun, - reviewDecision: await readTaskReviewDecision(sql, subject), - reviewDelegation: await readTaskReviewDelegation(sql, subject), - pendingReview: - review === null - ? null - : { - approvalId: review.approvalId, - round: review.round, - runId: review.runId, - requestedFor: review.requestedFor, - reviewer: review.reviewer, - implementationAgentId: review.implementationAgentId, - evidenceRevision: review.evidenceRevision, - agentReviewBlockedReason: review.agentReviewBlockedReason, - createdAt: review.createdAt, - }, + currentRun: currentRun ?? null, + ...(requestedRun !== undefined ? { requestedRun } : {}), + workflowRun: await readTaskWorkflowRunState(sql, args), }; } diff --git a/services/platform/backend/domains/tts/budget.integration.ts b/services/platform/backend/domains/tts/budget.integration.ts new file mode 100644 index 0000000000..fce14234b1 --- /dev/null +++ b/services/platform/backend/domains/tts/budget.integration.ts @@ -0,0 +1,532 @@ +/** Real PostgreSQL admission/settlement proof, with no provider invocation. + * The normal integration harness owns outbound isolation and job execution. + * Every row, policy change and synthetic blob key here is nonce-owned. */ +import { randomUUID } from 'node:crypto'; +import { mkdir, readFile, unlink, writeFile } from 'node:fs/promises'; +import path from 'node:path'; + +import type { Sql } from 'postgres'; +import { z } from 'zod'; + +import type { RecordCheck } from '../../integration-lane-helpers.ts'; +import { clearOrgConfigCaches } from '../../lib/org-config.ts'; +import { ChatBudgetExceededError } from '../chat/budget-admission.ts'; +import { createPgTurnStore } from '../chat/store.ts'; +import { readInFlightReservations } from '../governance/budget-reservations.ts'; +import { settleSessionOpSpend } from '../sandbox/spend-settlement.ts'; +import { reserveTurnBudget } from '../sandbox/turn-budget.ts'; +import { + gcExpiredTtsChunks, + markChunkReadyAndRecordUsage, + reserveChunk, + runTtsCleanup, + runTtsWatchdog, + TtsError, +} from './service.ts'; + +type Reserved = Extract< + Awaited>, + { kind: 'reserved' } +>; +const threadResult = z.object({ id: z.string() }); + +export async function checkTtsBudgetReservations( + sql: Sql, + base: string, + ctx: { cookie: string; orgId: string; userId: string }, + record: RecordCheck, +): Promise { + const suffix = randomUUID(); + const { orgId, userId } = ctx; + const now = Date.now(); + const model = `tts-budget-${suffix}`; + const opSession = `model-api:tts-budget-${suffix}`; + const messageId = `tts-budget-${suffix}`; + const foreignOrg = `tts-budget-foreign-${suffix}`; + const chunkIds = new Set(); + const projects: string[] = []; + const threads: string[] = []; + const store = createPgTurnStore(sql); + const org = await sql< + { slug: string }[] + >`SELECT slug FROM "organization" WHERE id = ${orgId}`; + if (!org[0]) throw new Error('TTS budget fixture organization is missing'); + const directory = path.join( + process.env.TALE_CONFIG_DIR ?? '', + org[0].slug, + 'governance', + ); + const policy = path.join(directory, 'budgets.yml'); + let original: string | undefined; + try { + original = await readFile(policy, 'utf8'); + } catch (error) { + if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT')) + throw error; + } + const report = (label: string, ok: boolean, detail: unknown) => + record(`tts shared budget: ${label}`, ok, JSON.stringify(detail)); + const project = async () => { + const rows = await sql<{ id: string }[]>` + INSERT INTO app.projects (org_id, name, team_ids, team_id, shared_with_team_ids, + created_by, created_at_ms, updated_at_ms) + VALUES (${orgId}, ${`TTS budget ${suffix}`}, ${[]}, NULL, ${[]}, ${userId}, ${now}, ${now}) RETURNING id`; + if (!rows[0]) throw new Error('TTS fixture project insert failed'); + projects.push(rows[0].id); + return rows[0].id; + }; + const thread = async (projectId?: string) => { + const response = await fetch( + `${base}/api/app/chat/threads?orgId=${orgId}`, + { + method: 'POST', + headers: { + cookie: ctx.cookie, + origin: base, + 'content-type': 'application/json', + }, + body: JSON.stringify({ + title: `TTS budget ${suffix}`, + ...(projectId ? { projectId } : {}), + }), + }, + ); + const parsed = threadResult.safeParse(await response.json()); + if (!response.ok || !parsed.success) + throw new Error('TTS fixture thread creation failed'); + threads.push(parsed.data.id); + return parsed.data.id; + }; + const refile = async (threadId: string, projectId: string) => { + const response = await fetch( + `${base}/api/app/chat/threads/${threadId}/project?orgId=${orgId}`, + { + method: 'POST', + headers: { + cookie: ctx.cookie, + origin: base, + 'content-type': 'application/json', + }, + body: JSON.stringify({ projectId }), + }, + ); + if (!response.ok) throw new Error('TTS fixture refile failed'); + }; + const budget = async ( + projectId: string, + limits: { cost?: number; requests?: number }, + ) => { + await mkdir(directory, { recursive: true }); + await writeFile( + policy, + [ + 'enabled: true', + 'rules: []', + 'projectRules:', + ' - scope: project', + ` scopeId: ${projectId}`, + ' period: monthly', + ...(limits.cost === undefined + ? [] + : [` maxCostCents: ${limits.cost}`]), + ...(limits.requests === undefined + ? [] + : [` maxRequests: ${limits.requests}`]), + ].join('\n'), + ); + clearOrgConfigCaches(); + }; + const voice = async (threadId: string, index: number) => { + const outcome = await reserveChunk(sql, { + organizationId: orgId, + userId, + threadId, + messageId, + index, + text: 'x'.repeat(1000), + locale: 'en', + agentSlug: null, + prospectiveCostCentsPerMChars: 1000, + modelId: model, + providerName: 'tts-budget-fixture', + }); + if (outcome.kind === 'reserved') { + chunkIds.add(outcome.chunkId); + // Hold only our scheduled watchdogs; the lane explicitly exercises + // their real handler and must not race a wall-clock worker tick. + await sql`UPDATE pgboss.job SET start_after = now() + interval '1 hour' + WHERE name = 'tts.watchdog_chunk' AND data ->> 'chunkId' = ${outcome.chunkId}`; + } + return outcome; + }; + const requireReserved = ( + value: Awaited>, + ): Reserved => { + if (value.kind !== 'reserved') + throw new Error(`Expected TTS reservation, received ${value.kind}`); + return value; + }; + const refused = async (run: () => Promise) => { + try { + await run(); + return false; + } catch (error) { + if (error instanceof TtsError && error.code === 'BUDGET_EXCEEDED') + return true; + throw error; + } + }; + const holds = (projectIds: string[], organizationId = orgId) => + readInFlightReservations(sql, { + organizationId, + userId, + userTeamIds: [], + projectIds, + }); + const op = (projectId: string, execId: string) => + reserveTurnBudget(sql, { + organizationId: orgId, + sessionId: opSession, + execId, + kind: 'model-api', + defaultBudgetCents: 1, + subject: { userId, agentSlug: model, projectIds: [projectId] }, + modelRef: `itest/${model}`, + whole: { prospectiveTokens: 1 }, + }); + const openChat = (threadId: string, projectId: string, costCents: number) => + store.beginTurn({ + organizationId: orgId, + threadId, + userParts: [{ type: 'text', text: 'bounded budget fixture' }], + spend: { userId, tokens: 1, costCents, projectIds: [projectId] }, + }); + const settle = (reservation: Reserved, cost: number, key: string) => + markChunkReadyAndRecordUsage(sql, { + organizationId: orgId, + chunkId: reservation.chunkId, + attemptCreatedAt: reservation.attemptCreatedAt, + storageRef: `s3:itest-tts-budget-${suffix}/${key}`, + voice: 'fixture', + providerName: 'itest', + modelId: model, + format: 'mp3', + characterCount: 1000, + costEstimateCents: cost, + }); + try { + const a = await project(); + const b = await project(); + const audioThread = await thread(a); + const chatThread = await thread(a); + const nextChatThread = await thread(a); + const outside = await thread(); + await budget(a, { cost: 1.5 }); + const racers = await Promise.all( + [0, 1].map(async (index) => { + try { + return { + index, + outcome: await voice(audioThread, index), + refused: false, + }; + } catch (error) { + if (error instanceof TtsError && error.code === 'BUDGET_EXCEEDED') + return { index, outcome: null, refused: true }; + throw error; + } + }), + ); + const winners = racers.filter((row) => row.outcome?.kind === 'reserved'); + const first = winners[0]; + report( + 'distinct chunks racing cost headroom admit exactly one pending attempt', + winners.length === 1 && + racers.filter((row) => row.refused).length === 1 && + (await holds([a])).projects?.[a]?.costCents === 1, + racers, + ); + if (first?.outcome?.kind !== 'reserved') + throw new Error('TTS race has no winner'); + const duplicate = await voice(audioThread, first.index); + report( + 'same chunk returns in-flight without another reservation', + duplicate.kind === 'pending-in-flight' && + (await holds([a])).projects?.[a]?.requests === 1, + duplicate, + ); + const opAfterVoice = await op(a, 'after-voice'); + report( + 'voice pending cost refuses a whole model request before execution', + !opAfterVoice.allowed, + opAfterVoice, + ); + + // Chat's maintained gate measures existing usage, rather than voice's + // prospective cost. Add a real half-cent chat hold to reach this cap, + // then a further chat must see the voice hold as well as the chat hold. + await openChat(chatThread, a, 0.5); + let chatRefused = false; + try { + await openChat(nextChatThread, a, 0.1); + } catch (error) { + if (error instanceof ChatBudgetExceededError) chatRefused = true; + else throw error; + } + report( + 'chat sees the voice share of a mixed pending cap', + chatRefused && (await holds([a])).projects?.[a]?.costCents === 1.5, + { chatRefused }, + ); + await store.endGeneration({ organizationId: orgId, threadId: chatThread }); + await store.endGeneration({ + organizationId: orgId, + threadId: nextChatThread, + }); + for (const row of winners) + if (row.outcome?.kind === 'reserved') + await runTtsWatchdog(sql, row.outcome); + const unknownBooked = await sql<{ cost: number; requests: number }[]>` + SELECT cost_estimate_cents::float8 AS cost, request_count::float8 AS requests + FROM app.project_usage WHERE org_id = ${orgId} AND project_id = ${a} AND granularity = 'monthly'`; + const retryRefused = await refused(() => voice(audioThread, first.index)); + report( + 'watchdog books the unknown estimate once and a retry still respects the cap', + (await holds([a])).projects?.[a] === undefined && + unknownBooked[0]?.cost === 1 && + unknownBooked[0]?.requests === 1 && + retryRefused, + { unknownBooked, retryRefused }, + ); + await runTtsWatchdog(sql, first.outcome); + const duplicateUnknown = await sql<{ cost: number; requests: number }[]>` + SELECT cost_estimate_cents::float8 AS cost, request_count::float8 AS requests + FROM app.project_usage WHERE org_id = ${orgId} AND project_id = ${a} AND granularity = 'monthly'`; + report( + 'duplicate watchdog does not book the failed attempt twice', + JSON.stringify(unknownBooked) === JSON.stringify(duplicateUnknown), + duplicateUnknown, + ); + // This next scenario owns a separate headroom measurement. The previous + // assertion observed the estimate before resetting only our project. + await sql`DELETE FROM app.project_usage WHERE org_id = ${orgId} AND project_id = ${a}`; + + await openChat(chatThread, a, 1); + const voiceAfterChat = await refused(() => voice(audioThread, 2)); + report( + 'a real chat hold refuses a distinct voice request', + voiceAfterChat, + { voiceAfterChat }, + ); + await store.endGeneration({ organizationId: orgId, threadId: chatThread }); + const modelHold = await op(a, 'before-voice'); + const voiceAfterOp = await refused(() => voice(audioThread, 2)); + report( + 'a real model hold refuses a distinct voice request', + modelHold.allowed && voiceAfterOp, + { modelHold, voiceAfterOp }, + ); + await settleSessionOpSpend(sql, { + sessionId: opSession, + execId: 'before-voice', + spentCents: 0, + }); + // These buckets belong only to this nonce's project; reset the scenario + // before changing from cost to request policy, retaining the op facts. + await sql`DELETE FROM app.project_usage WHERE org_id = ${orgId} AND project_id = ${a}`; + await budget(a, { requests: 2 }); + const requestFirst = requireReserved(await voice(audioThread, 3)); + const requestSecond = await refused(() => voice(audioThread, 4)); + report( + 'pending voice holds bind the request dimension', + requestSecond && (await holds([a])).projects?.[a]?.requests === 1, + { requestSecond }, + ); + await runTtsWatchdog(sql, requestFirst); + await sql`DELETE FROM app.project_usage WHERE org_id = ${orgId} AND project_id = ${a}`; + + await budget(a, { cost: 100 }); + const drift = requireReserved(await voice(audioThread, 5)); + await refile(audioThread, b); + const driftHold = await holds([a, b]); + report( + 'refiling retains the admitted voice project hold', + driftHold.projects?.[a]?.costCents === 1 && + driftHold.projects?.[b] === undefined, + driftHold, + ); + const finished = await settle(drift, 0.75, 'ready'); + const booked = await sql< + { projectId: string; cost: number; requests: number }[] + >` + SELECT project_id AS "projectId", cost_estimate_cents::float8 AS cost, request_count::float8 AS requests + FROM app.project_usage WHERE org_id = ${orgId} AND project_id = ANY(${[a, b]}) AND granularity = 'monthly'`; + const after = await holds([a, b]); + report( + 'ready replaces the hold with actual booked cost in the admitted project', + !finished.stale && + after.projects?.[a] === undefined && + after.projects?.[b] === undefined && + booked.find((row) => row.projectId === a)?.cost === 0.75 && + booked.find((row) => row.projectId === a)?.requests === 1 && + !booked.some((row) => row.projectId === b), + { booked, after }, + ); + const beforeReplay = + await sql`SELECT * FROM app.project_usage WHERE org_id = ${orgId} AND project_id = ANY(${[a, b]}) ORDER BY project_id, granularity`; + const replay = await settle(drift, 0.75, 'unused-replay'); + const replayBooked = + await sql`SELECT * FROM app.project_usage WHERE org_id = ${orgId} AND project_id = ANY(${[a, b]}) ORDER BY project_id, granularity`; + const noProject = requireReserved(await voice(outside, 6)); + await refile(outside, b); + await settle(noProject, 0.5, 'no-project'); + const noProjectBooked = + await sql`SELECT * FROM app.project_usage WHERE org_id = ${orgId} AND project_id = ANY(${[a, b]}) ORDER BY project_id, granularity`; + report( + 'explicit no-project stays empty and duplicate settlement cannot book twice', + replay.stale && + JSON.stringify(replayBooked) === JSON.stringify(beforeReplay) && + JSON.stringify(noProjectBooked) === JSON.stringify(replayBooked), + { replay, noProjectBooked }, + ); + + const retry = requireReserved(await voice(audioThread, 7)); + await runTtsWatchdog(sql, retry); + const next = requireReserved(await voice(audioThread, 7)); + await runTtsWatchdog(sql, retry); + const staleResult = await settle(retry, 20, 'unused-stale'); + const pending = await sql<{ attempt: number; status: string }[]>` + SELECT attempt_created_at_ms::float8 AS attempt, status FROM app.tts_audio_chunks WHERE id = ${next.chunkId}`; + const retryBooked = await sql<{ cost: number; requests: number }[]>` + SELECT cost_estimate_cents::float8 AS cost, request_count::float8 AS requests + FROM app.project_usage WHERE org_id = ${orgId} AND project_id = ${b} AND granularity = 'monthly'`; + report( + 'old watchdog and provider completion cannot release or charge a retry', + next.attemptCreatedAt > retry.attemptCreatedAt && + staleResult.stale && + pending[0]?.attempt === next.attemptCreatedAt && + pending[0].status === 'pending' && + (await holds([b])).projects?.[b]?.costCents === 1 && + retryBooked[0]?.cost === 1 && + retryBooked[0]?.requests === 1, + { retry, next, staleResult, pending, retryBooked }, + ); + await settle(next, 0.25, 'retry-ready'); + + // Storage emitted by a previous writer omits both new columns. This is + // a legacy-row compatibility probe, not execution of an old binary. + const legacyId = randomUUID(); + chunkIds.add(legacyId); + await sql`INSERT INTO app.tts_audio_chunks (id, org_id, thread_id, message_id, user_id, + chunk_index, text, status, locale, created_at_ms, attempt_created_at_ms) + VALUES (${legacyId}, ${orgId}, ${outside}, ${`legacy-${suffix}`}, ${userId}, 0, + 'legacy pending', 'pending', 'en', ${now}, ${now})`; + const legacyStamp = await sql< + { projects: string[] | null; cost: number | null }[] + >` + SELECT project_ids AS projects, reserved_cost_cents AS cost + FROM app.tts_audio_chunks WHERE id = ${legacyId}`; + const beforeLegacy = await sql<{ cost: number }[]>` + SELECT cost_estimate_cents::float8 AS cost FROM app.project_usage + WHERE org_id = ${orgId} AND project_id = ${b} AND granularity = 'monthly'`; + await settle( + { kind: 'reserved', chunkId: legacyId, attemptCreatedAt: now }, + 0.5, + 'legacy-ready', + ); + const afterLegacy = await sql<{ cost: number }[]>` + SELECT cost_estimate_cents::float8 AS cost FROM app.project_usage + WHERE org_id = ${orgId} AND project_id = ${b} AND granularity = 'monthly'`; + report( + 'legacy NULL attribution retains its current-thread settlement fallback', + legacyStamp[0]?.projects === null && + legacyStamp[0].cost === null && + afterLegacy[0]?.cost === (beforeLegacy[0]?.cost ?? 0) + 0.5, + { legacyStamp, beforeLegacy, afterLegacy }, + ); + + const foreignId = randomUUID(); + chunkIds.add(foreignId); + await sql`INSERT INTO app.tts_audio_chunks (id, org_id, thread_id, message_id, user_id, + chunk_index, text, status, locale, reserved_cost_cents, project_ids, created_at_ms, attempt_created_at_ms) + VALUES (${foreignId}, ${foreignOrg}, ${`foreign-${suffix}`}, ${`foreign-${suffix}`}, ${userId}, 0, + 'foreign pending storage boundary', 'pending', 'en', 100, ${[b]}, ${now}, ${now})`; + report( + 'another tenant pending row never contributes to this tenant holds', + (await holds([b])).projects?.[b] === undefined && + (await holds([b], foreignOrg)).projects?.[b]?.costCents === 100, + { foreignId }, + ); + + const c = await project(); + const staleThread = await thread(c); + await budget(c, { cost: 1.5 }); + const abandoned = requireReserved(await voice(staleThread, 8)); + await sql`UPDATE app.tts_audio_chunks SET created_at_ms = ${now - 8 * 24 * 60 * 60 * 1000} + WHERE id = ${abandoned.chunkId}`; + await runTtsCleanup(sql, { threadId: staleThread }); + await gcExpiredTtsChunks(sql, { limit: 1 }); + const afterCleanup = await holds([c]); + report( + 'ordinary age cleanup and GC retain an unknown pending hold', + afterCleanup.projects?.[c]?.costCents === 1, + afterCleanup, + ); + const takeoverRefused = await refused(() => voice(staleThread, 8)); + const retained = await sql<{ status: string; recorded: number | null }[]>` + SELECT status, usage_recorded_at_ms::float8 AS recorded FROM app.tts_audio_chunks + WHERE id = ${abandoned.chunkId}`; + const refusedBooked = await sql`SELECT * FROM app.project_usage + WHERE org_id = ${orgId} AND project_id = ${c}`; + report( + 'refused stale takeover rolls back booking and keeps its predecessor hold', + takeoverRefused && + retained[0]?.status === 'pending' && + retained[0].recorded === null && + refusedBooked.length === 0 && + (await holds([c])).projects?.[c]?.costCents === 1, + { takeoverRefused, retained, refusedBooked }, + ); + await budget(c, { cost: 3 }); + const replacement = requireReserved(await voice(staleThread, 8)); + await runTtsWatchdog(sql, abandoned); + const late = await settle(abandoned, 50, 'stale-takeover'); + const takeoverBooked = await sql<{ cost: number; requests: number }[]>` + SELECT cost_estimate_cents::float8 AS cost, request_count::float8 AS requests + FROM app.project_usage WHERE org_id = ${orgId} AND project_id = ${c} AND granularity = 'monthly'`; + report( + 'admitted stale takeover books the predecessor once before its new hold', + replacement.attemptCreatedAt > abandoned.attemptCreatedAt && + late.stale && + takeoverBooked[0]?.cost === 1 && + takeoverBooked[0]?.requests === 1 && + (await holds([c])).projects?.[c]?.costCents === 1, + { replacement, late, takeoverBooked }, + ); + await runTtsWatchdog(sql, replacement); + } finally { + if (original === undefined) + await unlink(policy).catch((error: unknown) => { + if ( + !( + error instanceof Error && + 'code' in error && + error.code === 'ENOENT' + ) + ) + throw error; + }); + else await writeFile(policy, original); + clearOrgConfigCaches(); + for (const threadId of threads) + await store.endGeneration({ organizationId: orgId, threadId }); + await sql`DELETE FROM pgboss.job WHERE (name = 'tts.watchdog_chunk' AND data ->> 'chunkId' = ANY(${[...chunkIds]})) + OR (name = 'tts.cleanup' AND data ->> 'threadId' = ANY(${threads}))`; + await sql`DELETE FROM app.tts_audio_chunks WHERE id = ANY(${[...chunkIds]}) AND org_id = ANY(${[orgId, foreignOrg]})`; + await sql`DELETE FROM app.sandbox_session_ops WHERE org_id = ${orgId} AND session_id = ${opSession}`; + await sql`DELETE FROM app.usage_ledger WHERE org_id = ${orgId} AND (model = ${model} OR agent_slug = ${model})`; + await sql`DELETE FROM app.project_usage WHERE org_id = ${orgId} AND project_id = ANY(${projects})`; + await sql`DELETE FROM app.threads WHERE org_id = ${orgId} AND id = ANY(${threads})`; + await sql`DELETE FROM app.projects WHERE org_id = ${orgId} AND id = ANY(${projects})`; + } +} diff --git a/services/platform/backend/domains/tts/service.attempt-budget.test.ts b/services/platform/backend/domains/tts/service.attempt-budget.test.ts new file mode 100644 index 0000000000..24c6a4e953 --- /dev/null +++ b/services/platform/backend/domains/tts/service.attempt-budget.test.ts @@ -0,0 +1,283 @@ +import type { Sql } from 'postgres'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const mocks = vi.hoisted(() => ({ + ledger: vi.fn(async () => undefined), + blobs: vi.fn(async () => undefined), +})); +vi.mock('../governance/service.ts', () => ({ + incrementUsageLedger: mocks.ledger, +})); +vi.mock('../files/service.ts', () => ({ + deleteOrgBlobRefs: mocks.blobs, + putOrgBlobBytes: vi.fn(), +})); +vi.mock('../../jobs/enqueue.ts', () => ({ + addJobInTx: vi.fn(async () => 'job'), +})); +vi.mock('../../lib/rate-limit.ts', async (importOriginal) => { + const actual = + await importOriginal(); + return { ...actual, limitRate: vi.fn(async () => ({ ok: true })) }; +}); + +import { + gcExpiredTtsChunks, + markChunkReadyAndRecordUsage, + runTtsCleanup, + runTtsWatchdog, +} from './service.ts'; + +type Statement = { text: string; values: unknown[] }; +function recordingSql(answer: (statement: Statement) => unknown[]) { + const statements: Statement[] = []; + const tag = (strings: TemplateStringsArray, ...values: unknown[]) => { + const statement = { + text: strings.join('?').replace(/\s+/g, ' ').trim(), + values, + }; + statements.push(statement); + return Promise.resolve(answer(statement)); + }; + const sql = Object.assign(tag, { + unsafe: (value: string) => value, + json: (value: unknown) => value, + begin: (run: (tx: unknown) => Promise) => run(sql), + }); + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- inspect the actual postgres tag calls without a database + return { sql: sql as unknown as Sql, statements }; +} + +const SETTLE = { + chunkId: 'chunk', + attemptCreatedAt: 10, + organizationId: 'org', + storageRef: 'new-blob', + voice: 'voice', + providerName: 'provider', + modelId: 'model', + format: 'mp3', + characterCount: 100, + costEstimateCents: 7, +}; + +const ATTEMPT = { + id: 'chunk', + organizationId: 'org', + threadId: 'thread', + userId: 'user', + teamId: null, + projectIds: ['admitted'], + reservedCostCents: 9, + usageRecordedAt: null, + index: 1, + text: 'attempt', + modelId: 'model', + providerName: 'provider', + attemptCreatedAt: 11, +}; + +beforeEach(() => { + mocks.ledger.mockClear(); + mocks.blobs.mockClear(); +}); + +describe('TTS attempt hold replacement [GOV-R14]', () => { + it('books actual cost under the admitted project in the exact attempt transaction', async () => { + const { sql, statements } = recordingSql(({ text }) => + text.includes('FOR UPDATE') + ? [ + { + id: 'chunk', + organizationId: 'org', + threadId: 'thread', + userId: 'user', + teamId: null, + projectIds: ['admitted'], + reservedCostCents: 9, + index: 1, + }, + ] + : [], + ); + await expect(markChunkReadyAndRecordUsage(sql, SETTLE)).resolves.toEqual({ + stale: false, + }); + expect(mocks.ledger).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + projectIds: ['admitted'], + costEstimateCents: 7, + characterCount: 100, + }), + ); + expect( + statements.some(({ text }) => text.includes('FROM app.thread_metadata')), + ).toBe(false); + expect( + statements.some(({ text }) => + text.includes('INSERT INTO app.budget_admissions'), + ), + ).toBe(false); + expect( + statements + .find(({ text }) => text.includes('FOR UPDATE')) + ?.values.slice(1), + ).toEqual(['chunk', 'org', 10]); + }); + + it('a stale provider result cannot book or release a newer attempt', async () => { + const { sql, statements } = recordingSql(() => []); + await expect(markChunkReadyAndRecordUsage(sql, SETTLE)).resolves.toEqual({ + stale: true, + }); + expect(mocks.ledger).not.toHaveBeenCalled(); + expect(mocks.blobs).toHaveBeenCalledWith(expect.anything(), 'org', [ + 'new-blob', + ]); + expect( + statements.some(({ text }) => + text.startsWith('UPDATE app.tts_audio_chunks'), + ), + ).toBe(false); + }); + + it('a stale watchdog does nothing; the exact attempt books its unknown estimate before release', async () => { + const stale = recordingSql(() => []); + await runTtsWatchdog(stale.sql, { chunkId: 'chunk', attemptCreatedAt: 10 }); + expect( + stale.statements.some( + ({ text }) => + text.includes('budget_admissions') || text.startsWith('UPDATE'), + ), + ).toBe(false); + + const current = recordingSql(({ text }) => { + if (text.includes('FOR UPDATE')) return [ATTEMPT]; + return []; + }); + await runTtsWatchdog(current.sql, { + chunkId: 'chunk', + attemptCreatedAt: 11, + }); + expect( + current.statements.some(({ text }) => + text.includes('INSERT INTO app.budget_admissions'), + ), + ).toBe(false); + expect( + current.statements + .find(({ text }) => text.includes('FOR UPDATE')) + ?.values.slice(1), + ).toEqual(['chunk', 11]); + expect( + current.statements.find(({ text }) => text.includes("status = 'failed'")) + ?.values, + ).toEqual(['WATCHDOG_TIMEOUT', 'chunk']); + expect(mocks.ledger).toHaveBeenCalledExactlyOnceWith( + expect.anything(), + expect.objectContaining({ + costEstimateCents: 9, + projectIds: ['admitted'], + model: 'model', + provider: 'provider', + characterCount: 7, + }), + ); + const receipt = current.statements.findIndex(({ text }) => + text.includes('SET usage_recorded_at_ms'), + ); + const failure = current.statements.findIndex(({ text }) => + text.includes("SET status = 'failed'"), + ); + expect(receipt).toBeGreaterThanOrEqual(0); + expect(failure).toBeGreaterThan(receipt); + }); + + it('a duplicate watchdog cannot book an already recorded attempt again', async () => { + const { sql, statements } = recordingSql(({ text }) => + text.includes('FOR UPDATE') ? [{ ...ATTEMPT, usageRecordedAt: 20 }] : [], + ); + await runTtsWatchdog(sql, { chunkId: 'chunk', attemptCreatedAt: 11 }); + expect(mocks.ledger).not.toHaveBeenCalled(); + expect( + statements.some(({ text }) => text.includes('SET usage_recorded_at_ms')), + ).toBe(false); + }); + + it('does not invent an estimate for a legacy NULL reservation', async () => { + const { sql } = recordingSql(({ text }) => + text.includes('FOR UPDATE') + ? [{ ...ATTEMPT, reservedCostCents: null, projectIds: null }] + : [], + ); + await runTtsWatchdog(sql, { chunkId: 'chunk', attemptCreatedAt: 11 }); + expect(mocks.ledger).not.toHaveBeenCalled(); + }); + + it('keeps a deliberately empty project stamp for an unknown outcome', async () => { + const { sql, statements } = recordingSql(({ text }) => + text.includes('FOR UPDATE') ? [{ ...ATTEMPT, projectIds: [] }] : [], + ); + await runTtsWatchdog(sql, { chunkId: 'chunk', attemptCreatedAt: 11 }); + expect(mocks.ledger).toHaveBeenCalledExactlyOnceWith( + expect.anything(), + expect.not.objectContaining({ projectIds: expect.anything() }), + ); + expect( + statements.some(({ text }) => text.includes('FROM app.thread_metadata')), + ).toBe(false); + }); + + it('an expired candidate retried before GC deletion keeps its new row and blob', async () => { + const { sql, statements } = recordingSql(({ text }) => + text.startsWith('SELECT id, org_id') + ? [{ id: 'chunk', orgId: 'org', storageRef: 'old-blob' }] + : [], + ); + await expect( + gcExpiredTtsChunks(sql, { now: 1_000_000_000 }), + ).resolves.toEqual({ deleted: 0 }); + const deletion = statements.find(({ text }) => + text.startsWith('DELETE FROM app.tts_audio_chunks'), + ); + expect(deletion?.text).toContain('created_at_ms <'); + expect(deletion?.text).toContain("status <> 'pending'"); + expect( + statements.find(({ text }) => text.startsWith('SELECT id, org_id'))?.text, + ).toContain("status <> 'pending'"); + expect(deletion?.text).toContain('RETURNING storage_ref'); + expect(mocks.blobs).not.toHaveBeenCalled(); + }); + + it('the lazy age sweep rechecks pending status before deleting a selected row', async () => { + const { sql, statements } = recordingSql(({ text }) => + text.startsWith('SELECT id, org_id') + ? [{ id: 'chunk', orgId: 'org', storageRef: null }] + : [], + ); + await runTtsCleanup(sql, { threadId: 'thread' }); + for (const statement of statements.filter(({ text }) => + text.includes('app.tts_audio_chunks'), + )) + expect(statement.text).toContain("status <> 'pending'"); + expect(mocks.ledger).not.toHaveBeenCalled(); + expect(mocks.blobs).not.toHaveBeenCalled(); + }); + + it('GC reclaims only the blob returned by an actually deleted expired row', async () => { + const { sql } = recordingSql(({ text }) => { + if (text.startsWith('SELECT id, org_id')) + return [{ id: 'chunk', orgId: 'org', storageRef: 'snapshot-blob' }]; + if (text.startsWith('DELETE FROM app.tts_audio_chunks')) + return [{ storageRef: 'deleted-blob' }]; + return []; + }); + await expect( + gcExpiredTtsChunks(sql, { now: 1_000_000_000 }), + ).resolves.toEqual({ deleted: 1 }); + expect(mocks.blobs).toHaveBeenCalledWith(expect.anything(), 'org', [ + 'deleted-blob', + ]); + }); +}); diff --git a/services/platform/backend/domains/tts/service.project-budget.test.ts b/services/platform/backend/domains/tts/service.project-budget.test.ts index d3dfa914bf..f08aafa33c 100644 --- a/services/platform/backend/domains/tts/service.project-budget.test.ts +++ b/services/platform/backend/domains/tts/service.project-budget.test.ts @@ -72,6 +72,8 @@ vi.mock('../../../lib/net/safe-fetch.ts', async (importOriginal) => { }); const { synthesizeChunk } = await import('./service.ts'); +const { safeFetchBinary } = await import('../../../lib/net/safe-fetch.ts'); +const { putOrgBlobBytes } = await import('../files/service.ts'); const ORG = 'org-1'; const USER = 'user-1'; @@ -79,7 +81,16 @@ const THREAD = 'thr-1'; /** A `sql` stand-in answering by the statement's text; `begin` runs the * callback on the same tag. */ -function scriptedSql(projectId: string | null, projectSpentCents: number) { +function scriptedSql( + projectId: string | null, + projectSpentCents: number, + options: { + admittedProjects?: string[] | null; + settlementProject?: string | null; + reservedCostCents?: number; + } = {}, +) { + let projectReads = 0; const tag = (strings: TemplateStringsArray) => { const text = strings.join('?').replace(/\s+/g, ' ').trim(); if (text.includes('FROM app.threads t')) return Promise.resolve([{}]); @@ -87,7 +98,15 @@ function scriptedSql(projectId: string | null, projectSpentCents: number) { return Promise.resolve([{ one: 1 }]); } if (text.includes('SELECT project_id AS "projectId"')) { - return Promise.resolve([{ projectId }]); + projectReads += 1; + return Promise.resolve([ + { + projectId: + projectReads > 1 && options.settlementProject !== undefined + ? options.settlementProject + : projectId, + }, + ]); } if (text.includes('SELECT agent_slug AS "agentSlug"')) { return Promise.resolve([{ agentSlug: null }]); @@ -113,6 +132,18 @@ function scriptedSql(projectId: string | null, projectSpentCents: number) { userId: USER, teamId: null, index: 0, + text: 'Hello there.', + reservedCostCents: options.reservedCostCents ?? 0.018, + usageRecordedAt: null, + providerName: 'openai', + modelId: 'tts-1', + attemptCreatedAt: 10, + projectIds: + options.admittedProjects === undefined + ? projectId === null + ? [] + : [projectId] + : options.admittedProjects, }, ]); } @@ -165,6 +196,96 @@ describe('synthesizeChunk in a project’s thread [GOV-R14]', () => { ); }); + it('keeps the admitted project when the conversation moves before settlement', async () => { + await synthesizeChunk( + scriptedSql('project-1', 0, { + admittedProjects: ['project-1'], + settlementProject: 'project-2', + }), + CHUNK, + ); + expect(mocks.incrementUsageLedger).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + projectIds: ['project-1'], + costEstimateCents: 0.018, + }), + ); + }); + + it('keeps deliberate no-project attribution after a later project binding', async () => { + await synthesizeChunk( + scriptedSql(null, 0, { + admittedProjects: [], + settlementProject: 'project-2', + }), + CHUNK, + ); + expect(mocks.incrementUsageLedger).toHaveBeenCalledWith( + expect.anything(), + expect.not.objectContaining({ projectIds: expect.anything() }), + ); + }); + + it('books the saved estimate once when the provider outcome is unknown', async () => { + vi.mocked(safeFetchBinary).mockRejectedValueOnce( + new Error('provider outcome unknown'), + ); + await expect( + synthesizeChunk( + scriptedSql('project-1', 0, { + admittedProjects: ['project-1'], + settlementProject: 'project-2', + }), + CHUNK, + ), + ).resolves.toMatchObject({ status: 'failed' }); + expect(mocks.incrementUsageLedger).toHaveBeenCalledExactlyOnceWith( + expect.anything(), + expect.objectContaining({ + projectIds: ['project-1'], + costEstimateCents: 0.018, + model: 'tts-1', + provider: 'openai', + }), + ); + }); + + it('keeps the resolved successful-call cost when blob storage later fails', async () => { + vi.mocked(putOrgBlobBytes).mockRejectedValueOnce( + new Error('owned storage unavailable'), + ); + await expect( + synthesizeChunk( + scriptedSql('project-1', 0, { + reservedCostCents: 9, + }), + CHUNK, + ), + ).resolves.toMatchObject({ status: 'failed' }); + expect(mocks.incrementUsageLedger).toHaveBeenCalledExactlyOnceWith( + expect.anything(), + expect.objectContaining({ + costEstimateCents: 0.018, + projectIds: ['project-1'], + }), + ); + }); + + it('preserves the current-thread fallback only for legacy unstamped chunks', async () => { + await synthesizeChunk( + scriptedSql('project-1', 0, { + admittedProjects: null, + settlementProject: 'project-2', + }), + CHUNK, + ); + expect(mocks.incrementUsageLedger).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ projectIds: ['project-2'] }), + ); + }); + it('refuses it once the project’s cap is reached, before the provider is called', async () => { mocks.budgets = { enabled: true, diff --git a/services/platform/backend/domains/tts/service.reserve.test.ts b/services/platform/backend/domains/tts/service.reserve.test.ts index 389e38981c..26bef7ccdc 100644 --- a/services/platform/backend/domains/tts/service.reserve.test.ts +++ b/services/platform/backend/domains/tts/service.reserve.test.ts @@ -9,7 +9,12 @@ */ import type { Sql } from 'postgres'; -import { describe, expect, it, vi } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const mocks = vi.hoisted(() => ({ + budgets: null as unknown, + ledger: vi.fn(async () => undefined), +})); vi.mock('../../lib/rate-limit.ts', async (importOriginal) => { const actual = @@ -25,7 +30,9 @@ vi.mock('../../auth/membership.ts', () => ({ getUserTeamIds: vi.fn(async () => []), })); vi.mock('../../lib/org-config.ts', () => ({ - readGovernancePolicyForOrg: vi.fn(async () => null), + readGovernancePolicyForOrg: vi.fn(async (_sql: unknown, _org, type) => + type === 'budgets' ? mocks.budgets : null, + ), readSettingsForOrg: vi.fn(async () => null), })); vi.mock('../../jobs/enqueue.ts', () => ({ @@ -35,6 +42,9 @@ vi.mock('../files/service.ts', () => ({ deleteOrgBlobRefs: vi.fn(async () => undefined), putOrgBlobBytes: vi.fn(), })); +vi.mock('../governance/service.ts', () => ({ + incrementUsageLedger: mocks.ledger, +})); import { reserveChunk } from './service.ts'; @@ -68,8 +78,15 @@ const ARGS = { locale: 'en', agentSlug: null, prospectiveCostCentsPerMChars: undefined, + providerName: 'provider', + modelId: 'model', }; +beforeEach(() => { + mocks.budgets = null; + mocks.ledger.mockClear(); +}); + describe('reserveChunk — per-(message, index) serialization [TTS-R3]', () => { it('takes the advisory lock before the FOR UPDATE read on a fresh chunk, then inserts', async () => { const { sql, statements } = recordingSql((text) => @@ -81,8 +98,11 @@ describe('reserveChunk — per-(message, index) serialization [TTS-R3]', () => { const outcome = await reserveChunk(sql, ARGS); expect(outcome).toMatchObject({ kind: 'reserved', chunkId: 'chunk-1' }); + const budgetIndex = statements.findIndex((s) => + s.text.includes('INSERT INTO app.budget_admissions'), + ); const lockIndex = statements.findIndex((s) => - s.text.includes('pg_advisory_xact_lock'), + s.text.includes("hashtextextended('tts:'"), ); const readIndex = statements.findIndex( (s) => @@ -90,9 +110,21 @@ describe('reserveChunk — per-(message, index) serialization [TTS-R3]', () => { s.text.includes('FOR UPDATE'), ); expect(lockIndex).toBeGreaterThanOrEqual(0); + expect(budgetIndex).toBeGreaterThanOrEqual(0); + expect(lockIndex).toBeGreaterThan(budgetIndex); expect(readIndex).toBeGreaterThan(lockIndex); // The lock key is the chunk identity the unique index guards. expect(statements[lockIndex]?.values).toEqual(['msg-1', '3']); + const insert = statements.find((s) => + s.text.includes('INSERT INTO app.tts_audio_chunks'), + ); + expect(insert?.text).toContain( + 'provider_name, model_id, reserved_cost_cents, project_ids', + ); + expect(insert?.values).toContain('provider'); + expect(insert?.values).toContain('model'); + expect(insert?.values.at(-1)).toEqual([]); + expect(insert?.values.at(-2)).toBe(0.018); }); it('answers in-flight, without inserting, once the winner’s pending row is visible', async () => { @@ -124,4 +156,129 @@ describe('reserveChunk — per-(message, index) serialization [TTS-R3]', () => { ), ).toBe(false); }); + + it('replaces only the exact prior hold and advances a same-millisecond retry identity', async () => { + const now = Date.now(); + const clock = vi.spyOn(Date, 'now').mockReturnValue(now); + try { + const { sql, statements } = recordingSql((text) => { + if ( + text.includes('FROM app.tts_audio_chunks') && + text.includes('FOR UPDATE') + ) + return [ + { + id: 'chunk-1', + organizationId: ARGS.organizationId, + threadId: ARGS.threadId, + status: 'failed', + storageRef: null, + createdAt: now, + attemptCreatedAt: now, + reservedCostCents: null, + usageRecordedAt: null, + }, + ]; + if (text.includes('SELECT project_id AS "projectId"')) + return [{ projectId: 'project-1' }]; + return []; + }); + const outcome = await reserveChunk(sql, ARGS); + expect(outcome).toEqual({ + kind: 'reserved', + chunkId: 'chunk-1', + attemptCreatedAt: now + 1, + }); + const holds = statements.find((s) => s.text.includes('WITH holds AS')); + expect(holds?.values).toContain('chunk-1'); + expect(holds?.values).toContain(now); + const update = statements.find((s) => + s.text.includes('UPDATE app.tts_audio_chunks SET'), + ); + expect(update?.text).toContain('reserved_cost_cents ='); + expect(update?.text).toContain('project_ids ='); + expect(update?.values).toContainEqual(['project-1']); + expect(update?.values).toContain(now + 1); + } finally { + clock.mockRestore(); + } + }); + + it('books a stale attempt before budget evaluation, and refuses a replacement beyond the cap', async () => { + mocks.budgets = { + enabled: true, + rules: [], + projectRules: [ + { + scope: 'project', + scopeId: 'project-1', + period: 'monthly', + maxCostCents: 1.5, + }, + ], + }; + const { sql, statements } = recordingSql((text) => { + if ( + text.includes('FROM app.tts_audio_chunks') && + text.includes('FOR UPDATE') + ) + return [ + { + id: 'chunk-1', + organizationId: ARGS.organizationId, + threadId: ARGS.threadId, + userId: ARGS.userId, + status: 'pending', + storageRef: null, + createdAt: 1, + attemptCreatedAt: 1, + reservedCostCents: 1, + usageRecordedAt: null, + projectIds: ['project-1'], + teamId: null, + modelId: 'old-model', + providerName: 'old-provider', + text: 'old', + }, + ]; + if (text.includes('SELECT project_id AS "projectId"')) + return [{ projectId: 'project-1' }]; + if (text.includes('FROM app.project_usage')) + return [ + { + totalTokens: 0, + costEstimate: mocks.ledger.mock.calls.length, + requestCount: 1, + }, + ]; + return []; + }); + await expect( + reserveChunk(sql, { + ...ARGS, + text: 'x'.repeat(1000), + prospectiveCostCentsPerMChars: 1000, + }), + ).rejects.toMatchObject({ code: 'BUDGET_EXCEEDED' }); + expect(mocks.ledger).toHaveBeenCalledExactlyOnceWith( + expect.anything(), + expect.objectContaining({ + costEstimateCents: 1, + projectIds: ['project-1'], + model: 'old-model', + provider: 'old-provider', + }), + ); + expect( + statements.some(({ text }) => text.includes("SET status = 'pending'")), + ).toBe(false); + const stamped = statements.findIndex(({ text }) => + text.includes('SET usage_recorded_at_ms'), + ); + const read = statements.findIndex(({ text }) => + text.includes('WITH holds AS'), + ); + expect(read).toBeGreaterThan(stamped); + // The real PG lane owns the transaction rollback/retained-hold assertion. + }); }); diff --git a/services/platform/backend/domains/tts/service.ts b/services/platform/backend/domains/tts/service.ts index f5dcf667e4..810fd1614d 100644 --- a/services/platform/backend/domains/tts/service.ts +++ b/services/platform/backend/domains/tts/service.ts @@ -45,9 +45,14 @@ import { loadOwnedThread, readThreadProjectId } from '../chat/threads.ts'; import { deleteOrgBlobRefs, putOrgBlobBytes } from '../files/service.ts'; import { checkOrgBudget, + findBudgetViolation, loadBudgetSubject, type OrgBudgetSubject, } from '../governance/budget-gate.ts'; +import { + lockBudgetAdmission, + readInFlightReservations, +} from '../governance/budget-reservations.ts'; import { incrementUsageLedger } from '../governance/service.ts'; /** @@ -116,6 +121,8 @@ interface ChunkRow { storageRef: string | null; characterCount: number | null; costEstimateCents: number | null; + reservedCostCents: number | null; + projectIds: string[] | null; usageRecordedAt: number | null; createdAt: number; attemptCreatedAt: number; @@ -128,6 +135,7 @@ const CHUNK_COLUMNS = ` voice, provider_name AS "providerName", model_id AS "modelId", format, storage_ref AS "storageRef", character_count::float8 AS "characterCount", cost_estimate_cents AS "costEstimateCents", + reserved_cost_cents AS "reservedCostCents", project_ids AS "projectIds", usage_recorded_at_ms::float8 AS "usageRecordedAt", created_at_ms::float8 AS "createdAt", attempt_created_at_ms::float8 AS "attemptCreatedAt" @@ -281,6 +289,8 @@ export async function reserveChunk( locale: string; agentSlug: string | null; prospectiveCostCentsPerMChars: number | undefined; + providerName?: string; + modelId?: string; }, ): Promise { if ( @@ -295,6 +305,9 @@ export async function reserveChunk( } return sql.begin(async (tx) => { + // Every spending lane takes this before its own row locks, then writes + // its hold before releasing it. Distinct voice chunks share the cap. + await lockBudgetAdmission(tx, args.organizationId); // Serialize reserves per (message, index) BEFORE the row read. The unique // row is the race arbiter once it exists, but `FOR UPDATE` over zero rows // locks nothing: two first-time reserves of one chunk both saw no row and @@ -349,6 +362,10 @@ export async function reserveChunk( } // Stale pending — the attempt crashed; fall through to overwrite. } + // A timeout is not evidence that the provider did no work. Preserve + // the old estimate before evaluating or replacing its reservation. + // A refused replacement rolls back this booking and retains its hold. + await recordUnknownAttemptEstimate(tx, existing); } // Per-message character cap across every counted chunk (terminally @@ -439,21 +456,33 @@ export async function reserveChunk( args.text.length, args.prospectiveCostCentsPerMChars ?? PROSPECTIVE_TTS_CENTS_PER_M_CHARS, ); - const budget = await checkTtsBudget(tx, { - ...subject, + const violation = await findBudgetViolation(tx, subject, { + reservations: await readInFlightReservations( + tx, + subject, + existing !== undefined + ? { + tts: { + chunkId: existing.id, + attemptCreatedAt: existing.attemptCreatedAt, + }, + } + : {}, + ), prospectiveCostCents, prospectiveRequests: 1, }); - if (!budget.allowed) { - throw new TtsError( - 'BUDGET_EXCEEDED', - budget.reason ?? - 'TTS budget exceeded for this period. Contact your administrator.', - 429, - ); + if (violation !== null) { + throw new TtsError('BUDGET_EXCEEDED', violation.reason, 429); } - const attemptCreatedAt = Date.now(); + // A failed retry can occur in the same millisecond. Its watchdog and + // provider result must never match the attempt it replaces. + const attemptCreatedAt = Math.max( + Date.now(), + (existing?.attemptCreatedAt ?? 0) + 1, + ); + const projectIds = projectId !== undefined ? [projectId] : []; let chunkId: string; if (existing) { // Overwrite to retry: reset every result-bearing field, and reclaim a @@ -466,9 +495,12 @@ export async function reserveChunk( status = 'pending', error = NULL, text = ${args.text}, locale = ${args.locale}, created_at_ms = ${attemptCreatedAt}, attempt_created_at_ms = ${attemptCreatedAt}, - usage_recorded_at_ms = NULL, voice = NULL, provider_name = NULL, - model_id = NULL, format = NULL, storage_ref = NULL, + usage_recorded_at_ms = NULL, voice = NULL, + provider_name = ${args.providerName ?? null}, + model_id = ${args.modelId ?? null}, format = NULL, storage_ref = NULL, character_count = NULL, cost_estimate_cents = NULL, + reserved_cost_cents = ${prospectiveCostCents}, + project_ids = ${projectIds}, user_id = ${args.userId}, team_id = NULL, agent_slug = ${args.agentSlug ?? tx.unsafe('agent_slug')} WHERE id = ${existing.id} @@ -479,12 +511,15 @@ export async function reserveChunk( INSERT INTO app.tts_audio_chunks ( org_id, thread_id, message_id, user_id, team_id, agent_slug, chunk_index, text, status, locale, created_at_ms, - attempt_created_at_ms + attempt_created_at_ms, provider_name, model_id, + reserved_cost_cents, project_ids ) VALUES ( ${args.organizationId}, ${args.threadId}, ${args.messageId}, ${args.userId}, NULL, ${args.agentSlug}, ${args.index}, ${args.text}, 'pending', ${args.locale}, - ${attemptCreatedAt}, ${attemptCreatedAt} + ${attemptCreatedAt}, ${attemptCreatedAt}, + ${args.providerName ?? null}, ${args.modelId ?? null}, + ${prospectiveCostCents}, ${projectIds} ) RETURNING id `; @@ -511,9 +546,56 @@ export async function reserveChunk( // ----------------------------------------------------------------- settle +/** The caller holds this exact row through booking and release/replacement. + * A durable reservation can have an unknown provider outcome; record its + * saved estimate once rather than treating cancellation as free. This is + * estimated usage, not a claim that the provider confirmed a charge. */ +async function recordUnknownAttemptEstimate( + tx: TransactionSql, + row: ChunkRow, + knownCostEstimateCents?: number, +): Promise { + // Previous writers did not persist a price. Never invent a legacy charge. + if (row.usageRecordedAt !== null || row.reservedCostCents === null) return; + const legacyProjectId = + row.projectIds === null + ? await readThreadProjectId(tx, row.organizationId, row.threadId) + : undefined; + const projectIds = + row.projectIds ?? (legacyProjectId !== undefined ? [legacyProjectId] : []); + const now = Date.now(); + const costEstimateCents = knownCostEstimateCents ?? row.reservedCostCents; + await incrementUsageLedger(tx, { + organizationId: row.organizationId, + userId: row.userId, + ...(row.teamId !== null ? { teamId: row.teamId } : {}), + ...(projectIds.length > 0 ? { projectIds } : {}), + agentSlug: TTS_SLUG, + ...(row.modelId !== null ? { model: row.modelId } : {}), + ...(row.providerName !== null ? { provider: row.providerName } : {}), + inputTokens: 0, + outputTokens: 0, + costEstimateCents, + characterCount: row.text.length, + timestamp: now, + }); + await tx` + UPDATE app.tts_audio_chunks SET usage_recorded_at_ms = ${now}, + cost_estimate_cents = ${costEstimateCents}, + character_count = ${row.text.length} + WHERE id = ${row.id} AND attempt_created_at_ms = ${row.attemptCreatedAt} + AND usage_recorded_at_ms IS NULL + `; +} + async function markChunkFailed( sql: Sql, - args: { chunkId: string; attemptCreatedAt: number; error: string }, + args: { + chunkId: string; + attemptCreatedAt: number; + error: string; + knownCostEstimateCents?: number; + }, ): Promise<{ stale: boolean }> { if (!ERROR_CODES.has(args.error)) { // The closed vocabulary is the PII firewall — free-form text never @@ -521,9 +603,8 @@ async function markChunkFailed( throw new Error(`[tts] not a TtsErrorCode: ${args.error}`); } return sql.begin(async (tx) => { - const rows = await tx<{ id: string; index: number; threadId: string }[]>` - SELECT id, chunk_index AS "index", thread_id AS "threadId" - FROM app.tts_audio_chunks + const rows = await tx` + SELECT ${tx.unsafe(CHUNK_COLUMNS)} FROM app.tts_audio_chunks WHERE id = ${args.chunkId} AND status = 'pending' AND attempt_created_at_ms = ${args.attemptCreatedAt} LIMIT 1 @@ -531,6 +612,7 @@ async function markChunkFailed( `; const row = rows[0]; if (!row) return { stale: true }; + await recordUnknownAttemptEstimate(tx, row, args.knownCostEstimateCents); await tx` UPDATE app.tts_audio_chunks SET status = 'failed', error = ${args.error} WHERE id = ${row.id} @@ -542,7 +624,8 @@ async function markChunkFailed( }); } -async function markChunkReadyAndRecordUsage( +/** Also used by the real-PG budget/attempt proof; synthesis owns the app door. */ +export async function markChunkReadyAndRecordUsage( sql: Sql, args: { chunkId: string; @@ -560,7 +643,8 @@ async function markChunkReadyAndRecordUsage( return sql.begin(async (tx) => { const rows = await tx` SELECT ${tx.unsafe(CHUNK_COLUMNS)} FROM app.tts_audio_chunks - WHERE id = ${args.chunkId} AND status = 'pending' + WHERE id = ${args.chunkId} AND org_id = ${args.organizationId} + AND status = 'pending' AND attempt_created_at_ms = ${args.attemptCreatedAt} LIMIT 1 FOR UPDATE @@ -584,16 +668,20 @@ async function markChunkReadyAndRecordUsage( `; // Ledger rows for TTS always bucket under the TTS_SLUG sentinel so // voice cost surfaces as its own row, never folded into the agent. - const projectId = await readThreadProjectId( - tx, - row.organizationId, - row.threadId, - ); + // [] deliberately admitted no project. Only a legacy NULL stamp may + // use the pre-reservation behavior of reading the thread at settlement. + const legacyProjectId = + row.projectIds === null + ? await readThreadProjectId(tx, row.organizationId, row.threadId) + : undefined; + const projectIds = + row.projectIds ?? + (legacyProjectId !== undefined ? [legacyProjectId] : []); await incrementUsageLedger(tx, { organizationId: row.organizationId, userId: row.userId, ...(row.teamId !== null ? { teamId: row.teamId } : {}), - ...(projectId !== undefined ? { projectIds: [projectId] } : {}), + ...(projectIds.length > 0 ? { projectIds } : {}), agentSlug: TTS_SLUG, model: args.modelId, provider: args.providerName, @@ -732,6 +820,8 @@ export async function synthesizeChunk( locale: args.locale, agentSlug: meta[0]?.agentSlug ?? null, prospectiveCostCentsPerMChars: modelData.centsPerMillionCharacters, + providerName: modelData.providerName, + modelId: modelData.modelId, }); if (reservation.kind === 'ready') return { status: 'ready' }; if (reservation.kind === 'pending-in-flight') return { status: 'in-flight' }; @@ -740,11 +830,15 @@ export async function synthesizeChunk( const markFailedAndReturn = async ( code: TtsErrorCode, retryAfterMs?: number, + knownCostEstimateCents?: number, ): Promise => { const result = await markChunkFailed(sql, { chunkId, attemptCreatedAt, error: code, + ...(knownCostEstimateCents !== undefined + ? { knownCostEstimateCents } + : {}), }); if (result.stale) return { status: 'in-flight' }; return { @@ -772,6 +866,7 @@ export async function synthesizeChunk( const url = `${modelData.baseUrl.replace(/\/+$/, '')}/audio/speech`; const mime = AUDIO_MIME_BY_FORMAT[modelData.audioFormat] ?? 'application/octet-stream'; + let knownCostEstimateCents: number | undefined; try { const response = await safeFetchBinary(url, { allowPrivateAddresses: privateProviderHostsAllowed(), @@ -810,6 +905,12 @@ export async function synthesizeChunk( `TTS API ${response.status}: provider call failed`, ); } + // The request succeeded; a later body/storage failure must not replace + // its resolved rate with the admission fallback estimate. + knownCostEstimateCents = estimateTtsCostCents( + text.length, + modelData.centsPerMillionCharacters, + ); if (response.body.size < MIN_TTS_AUDIO_BYTES) { console.warn('[tts] provider returned implausibly small body', { bytes: response.body.size, @@ -817,7 +918,7 @@ export async function synthesizeChunk( }); throw new SafeFetchError( 'response_too_small', - `Provider returned ${response.body.size} bytes (< ${MIN_TTS_AUDIO_BYTES}); refusing to bill for empty audio`, + `Provider returned ${response.body.size} bytes (< ${MIN_TTS_AUDIO_BYTES}); refusing empty audio`, response.status, ); } @@ -850,7 +951,7 @@ export async function synthesizeChunk( code, detail: sanitizeError(error), }); - return markFailedAndReturn(code, retryAfterMs); + return markFailedAndReturn(code, retryAfterMs, knownCostEstimateCents); } } @@ -974,13 +1075,21 @@ export async function runTtsCleanup( SELECT id, org_id AS "orgId", storage_ref AS "storageRef" FROM app.tts_audio_chunks WHERE thread_id = ${payload.threadId} AND created_at_ms < ${cutoff} + AND status <> 'pending' LIMIT ${CLEANUP_PASS_LIMIT} `; for (const row of rows) { await sql.begin(async (tx) => { - await tx`DELETE FROM app.tts_audio_chunks WHERE id = ${row.id}`; - if (row.storageRef !== null) { - await deleteOrgBlobRefs(tx, row.orgId, [row.storageRef]); + const deleted = await tx<{ storageRef: string | null }[]>` + DELETE FROM app.tts_audio_chunks + WHERE id = ${row.id} AND org_id = ${row.orgId} + AND created_at_ms < ${cutoff} + AND status <> 'pending' + RETURNING storage_ref AS "storageRef" + `; + const removed = deleted[0]; + if (removed?.storageRef != null) { + await deleteOrgBlobRefs(tx, row.orgId, [removed.storageRef]); } }); } @@ -1008,7 +1117,7 @@ export async function gcExpiredTtsChunks( >` SELECT id, org_id AS "orgId", storage_ref AS "storageRef" FROM app.tts_audio_chunks - WHERE created_at_ms < ${cutoff} + WHERE created_at_ms < ${cutoff} AND status <> 'pending' ORDER BY created_at_ms LIMIT ${options.limit ?? 500} `; @@ -1018,13 +1127,21 @@ export async function gcExpiredTtsChunks( // back a batch, and a row that survives its blob is the recoverable // direction (the next tick retries it). try { - await sql.begin(async (tx) => { - await tx`DELETE FROM app.tts_audio_chunks WHERE id = ${row.id}`; - if (row.storageRef !== null) { - await deleteOrgBlobRefs(tx, row.orgId, [row.storageRef]); + const removed = await sql.begin(async (tx) => { + const deletedRows = await tx<{ storageRef: string | null }[]>` + DELETE FROM app.tts_audio_chunks + WHERE id = ${row.id} AND org_id = ${row.orgId} + AND created_at_ms < ${cutoff} + AND status <> 'pending' + RETURNING storage_ref AS "storageRef" + `; + const chunk = deletedRows[0]; + if (chunk?.storageRef != null) { + await deleteOrgBlobRefs(tx, row.orgId, [chunk.storageRef]); } + return chunk !== undefined; }); - deleted += 1; + if (removed) deleted += 1; } catch (error) { console.warn('[tts] chunk GC failed for one row:', error); } diff --git a/services/platform/backend/integration-check.ts b/services/platform/backend/integration-check.ts index fe2635ec9c..5d490420d7 100644 --- a/services/platform/backend/integration-check.ts +++ b/services/platform/backend/integration-check.ts @@ -95,6 +95,7 @@ import { import { checkMessageHeldBlobs } from './domains/files/message-held-blobs.integration.ts'; import { checkRejectedUploadReclaim } from './domains/files/reject-blob.integration.ts'; import { checkHubFolderWriteRole } from './domains/folders/write-role.integration.ts'; +import { checkImmutableBudgetProjects } from './domains/governance/immutable-projects.integration.ts'; import { checkProjectBudgets } from './domains/governance/project-budget.integration.ts'; import { checkUsageMetricsBuckets } from './domains/governance/usage-metrics.integration.ts'; import { checkEmailedAttachments } from './domains/knowledge/attachment-mail.integration.ts'; @@ -159,6 +160,7 @@ import { checkAgentRunFailureNotice } from './domains/tasks/run-failure-notice.i import { checkTaskRunStartFence } from './domains/tasks/run-start.integration.ts'; import { checkTaskSourceThread } from './domains/tasks/source-thread.integration.ts'; import { checkTaskWorkflowParentMoves } from './domains/tasks/workflow-parent-moves.integration.ts'; +import { checkTtsBudgetReservations } from './domains/tts/budget.integration.ts'; import { checkVideoLinkComposerChips } from './domains/video_links/composer-chips.integration.ts'; import { checkRenderFailedCreate } from './domains/websites/render-failed-create.integration.ts'; import { closeServerGracefully } from './http-shutdown.ts'; @@ -12267,7 +12269,12 @@ async function checkAutomations( JSON.stringify({ object: 'list', data: [ - { id: 'itest-llm', object: 'model', context_length: 32_768 }, + { + id: 'itest-llm', + object: 'model', + context_length: 32_768, + pricing: { prompt: '0.000001', completion: '0.000002' }, + }, ], }), ); @@ -62280,6 +62287,14 @@ async function main(): Promise { 'checkProjectBudgets', () => checkProjectBudgets(sql, baseUrl, authCtx, record), ], + [ + 'checkImmutableBudgetProjects', + () => checkImmutableBudgetProjects(sql, baseUrl, authCtx, record), + ], + [ + 'checkTtsBudgetReservations', + () => checkTtsBudgetReservations(sql, baseUrl, authCtx, record), + ], [ 'checkOrphanedOrgRowsBackfill', () => checkOrphanedOrgRowsBackfill(sql, authCtx, record), diff --git a/services/platform/backend/jobs/automation-floor.integration.ts b/services/platform/backend/jobs/automation-floor.integration.ts index b824e88b01..034e4b46a9 100644 --- a/services/platform/backend/jobs/automation-floor.integration.ts +++ b/services/platform/backend/jobs/automation-floor.integration.ts @@ -3,9 +3,19 @@ * or Docker host access is required; the CLI's real bounded psql transport has * separate command tests. */ import { randomUUID } from 'node:crypto'; +import { readdirSync } from 'node:fs'; import postgres, { type Sql } from 'postgres'; +import { + AUTOMATION_CUTOVER_CENSUS_SQL, + AUTOMATION_CUTOVER_ISOLATION, + AUTOMATION_CUTOVER_LOCK_SQL, + AUTOMATION_CUTOVER_PROBE_SQL, + AUTOMATION_CUTOVER_SESSION_SQL, + cutoverLockOwned, + emptyLegacyCutoverCensus, +} from '../../../../tools/cli/src/lib/deployment/automation-cutover-sql.ts'; import { AUTOMATION_LEDGER_QUERY, automationFloor, @@ -16,6 +26,149 @@ import { resolvePostgresConnection } from '../db/ssl.ts'; type Recorder = (name: string, ok: boolean, detail: string) => void; +async function ledgerValue(reader: Pick): Promise { + const rows = await reader.unsafe(AUTOMATION_LEDGER_QUERY).values(); + if (rows.length !== 1 || rows[0].length !== 1) + throw new Error('Unexpected catalog census'); + const statement = checkedAutomationLedgerQuery(rows[0][0]); + const result = await reader.unsafe(statement).values(); + if (result.length !== 1 || result[0].length !== 1) + throw new Error('Unexpected ledger census'); + return result[0][0]; +} + +/** The actual CLI SQL is exercised in the required Backend integration lane, + * in this helper's owned database, with a separate competing connection. */ +async function checkCutover( + db: Sql, + peer: Sql, + record: Recorder, +): Promise { + const ids = readdirSync(new URL('../db/migrations/', import.meta.url)) + .filter( + (name) => + /^\d{4}_[a-z0-9_]+\.(sql|ts)$/.test(name) && + Number(name.slice(0, 4)) <= 153, + ) + .sort(); + await db`ALTER TABLE tale.app_migrations ADD PRIMARY KEY (name)`; + await db`DELETE FROM tale.app_migrations`; + await db`INSERT INTO tale.app_migrations ${db(ids.map((name) => ({ name })))}`; + await db`CREATE SCHEMA app`; + await db`CREATE TABLE app.automation_runs (id text PRIMARY KEY, org_id text NOT NULL, status text NOT NULL)`; + const census = async (tx: Pick) => { + const ledger = await ledgerValue(tx); + const result = await tx.unsafe(AUTOMATION_CUTOVER_CENSUS_SQL).values(); + if (result.length !== 1 || result[0].length !== 1) + throw new Error('Unexpected cutover census'); + return emptyLegacyCutoverCensus( + `${JSON.stringify(ledger)}\n${JSON.stringify(result[0][0])}`, + ); + }; + await db.begin(AUTOMATION_CUTOVER_ISOLATION, async (tx) => { + await tx.unsafe(AUTOMATION_CUTOVER_SESSION_SQL); + await tx.unsafe(AUTOMATION_CUTOVER_LOCK_SQL); + record( + 'automation cutover holds the exact legacy all-org zero census', + await census(tx), + 'source ledger and owned SHARE lock', + ); + let blocked = false; + try { + await peer.begin(async (writer) => { + await writer`SET LOCAL statement_timeout = '300ms'`; + await writer`INSERT INTO app.automation_runs VALUES ('competing', 'second-org', 'queued')`; + }); + } catch (error) { + blocked = + error instanceof postgres.PostgresError && error.code === '57014'; + } + const [count] = + await tx`SELECT count(*)::int AS value FROM app.automation_runs`; + record( + 'automation cutover blocks a competing legacy admission while zero is held', + blocked && count.value === 0, + 'competing INSERT hit its statement bound; zero retained', + ); + }); + // A newly booted released bundled DB uses public; migrated deployments may + // retain tale. Both must bind the same unique validated ledger and exact IDs. + await db`ALTER TABLE tale.app_migrations SET SCHEMA public`; + await db.begin(AUTOMATION_CUTOVER_ISOLATION, async (tx) => { + await tx.unsafe(AUTOMATION_CUTOVER_SESSION_SQL); + await tx.unsafe(AUTOMATION_CUTOVER_LOCK_SQL); + record( + 'automation cutover accepts the released public ledger with held zero', + await census(tx), + 'actual released default layout; unchanged immutable migration IDs', + ); + }); + await db`CREATE TABLE tale.app_migrations (name text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())`; + await db.begin(AUTOMATION_CUTOVER_ISOLATION, async (tx) => { + await tx.unsafe(AUTOMATION_CUTOVER_SESSION_SQL); + await tx.unsafe(AUTOMATION_CUTOVER_LOCK_SQL); + record( + 'automation cutover refuses ambiguous public and tale ledgers', + !(await census(tx)), + 'schema support never permits a second shadow migration ledger', + ); + }); + await db`DROP TABLE tale.app_migrations`; + await peer`INSERT INTO app.automation_runs VALUES ('after-release', 'second-org', 'queued')`; + await db.begin(AUTOMATION_CUTOVER_ISOLATION, async (tx) => { + await tx.unsafe(AUTOMATION_CUTOVER_SESSION_SQL); + await tx.unsafe(AUTOMATION_CUTOVER_LOCK_SQL); + record( + 'automation cutover refuses unfinished work in another organization', + !(await census(tx)), + 'released lock permits admission; the next census refuses', + ); + }); + await peer`DELETE FROM app.automation_runs`; + await peer.begin(async (writer) => { + await writer`INSERT INTO app.automation_runs VALUES ('uncommitted', 'second-org', 'queued')`; + let refused = false; + try { + await db.begin(AUTOMATION_CUTOVER_ISOLATION, async (tx) => { + await tx.unsafe(AUTOMATION_CUTOVER_SESSION_SQL); + await tx.unsafe(AUTOMATION_CUTOVER_LOCK_SQL); + }); + } catch (error) { + refused = + error instanceof postgres.PostgresError && error.code === '55P03'; + } + record( + 'automation cutover refuses a prior uncommitted admission', + refused, + 'NOWAIT never manufactures zero by stopping its writer', + ); + await writer`DELETE FROM app.automation_runs WHERE id = 'uncommitted'`; + }); + let revoked = false; + let lost = false; + try { + await db.begin(AUTOMATION_CUTOVER_ISOLATION, async (tx) => { + await tx.unsafe(AUTOMATION_CUTOVER_SESSION_SQL); + await tx.unsafe(AUTOMATION_CUTOVER_LOCK_SQL); + const [owner] = await tx`SELECT pg_backend_pid() AS pid`; + await peer`SELECT pg_terminate_backend(${owner.pid})`; + try { + const result = await tx.unsafe(AUTOMATION_CUTOVER_PROBE_SQL).values(); + revoked = !cutoverLockOwned(JSON.stringify(result[0]?.[0])); + } catch { + revoked = true; + } + }); + } catch { + lost = true; + } + record( + 'automation cutover session loss revokes its lock proof', + revoked && lost, + 'terminated only this owned transaction; no stale zero is authority', + ); +} + function connect(raw: string): Sql { const url = new URL(raw); url.searchParams.set( @@ -41,25 +194,21 @@ export async function checkAutomationProtocolFloor( target.pathname = `/${name}`; let owned = false; let sql: Sql | undefined; + let peer: Sql | undefined; let failure: unknown; try { await admin`CREATE DATABASE ${admin(name)}`; owned = true; sql = connect(target.toString()); + peer = connect(target.toString()); const db = sql; const read = () => db.begin('read only', async (tx) => { - const rows = await tx.unsafe(AUTOMATION_LEDGER_QUERY).values(); - if (rows.length !== 1 || rows[0].length !== 1) - throw new Error('Unexpected catalog census'); // A returned string is not authority to execute SQL. Admit only the exact // fixed SELECT the source query can generate, including its null refusal. - const statement = checkedAutomationLedgerQuery(rows[0][0]); - const result = await tx.unsafe(statement).values(); - if (result.length !== 1 || result[0].length !== 1) - throw new Error('Unexpected ledger census'); + const result = await ledgerValue(tx); try { - return automationFloor(JSON.stringify(result[0][0])); + return automationFloor(JSON.stringify(result)); } catch { return null; } @@ -104,6 +253,7 @@ export async function checkAutomationProtocolFloor( await db`ALTER TABLE tale.app_migrations DISABLE ROW LEVEL SECURITY`; await db`ALTER TABLE tale.app_migrations DROP CONSTRAINT app_migrations_pkey`; await prove('automation floor refuses malformed ledger identity', null); + await checkCutover(db, peer, record); } catch (error) { failure = error; } finally { @@ -111,7 +261,7 @@ export async function checkAutomationProtocolFloor( // A failed shutdown leaves that owned DB for diagnosis; never FORCE others. let stopped = sql === undefined; try { - await sql?.end({ timeout: 8 }); + await Promise.all([sql?.end({ timeout: 8 }), peer?.end({ timeout: 8 })]); stopped = true; } catch (error) { failure ??= error; diff --git a/services/platform/backend/rest/error-codes.test.ts b/services/platform/backend/rest/error-codes.test.ts index b8b8b94595..4b45d1b85b 100644 --- a/services/platform/backend/rest/error-codes.test.ts +++ b/services/platform/backend/rest/error-codes.test.ts @@ -457,6 +457,9 @@ const APP_ONLY_CODES: ReadonlySet = new Set([ // an unknown slug `ORG_SLUG_INVALID` and never creates or deletes one. 'ORG_NOT_FOUND', 'ORG_SLUG_RETIRING', + // The app's organization delete refuses unresolved legacy automation + // holds; REST mounts no organization-deletion door. + 'ORG_LEGACY_AUTOMATION_HELD', // The skill bundle's zip upload lane; the REST save writes SKILL.md // through the file layer, whose failure is a 500, never this code. 'WRITE_FAILED', diff --git a/services/platform/lib/chat/turn.test.ts b/services/platform/lib/chat/turn.test.ts index dbd2ba13d1..02082f864a 100644 --- a/services/platform/lib/chat/turn.test.ts +++ b/services/platform/lib/chat/turn.test.ts @@ -396,6 +396,7 @@ describe('runTurn — the happy path', () => { expect(spends).toEqual([ { userId: 'user_1', + projectIds: [], apiKeyId: 'key_1', tokens: expect.any(Number), costCents: expect.any(Number), diff --git a/services/platform/lib/chat/turn.ts b/services/platform/lib/chat/turn.ts index e0a825db3d..8009908f6e 100644 --- a/services/platform/lib/chat/turn.ts +++ b/services/platform/lib/chat/turn.ts @@ -328,6 +328,9 @@ export interface TurnStore { * booked usage replaces it once the turn settles. */ export interface TurnSpend { readonly userId: string; + /** The projects captured with this request, also used by its settlement. + * An empty array is authoritative: refiling never changes a live bill. */ + readonly projectIds?: readonly string[]; /** The API key that authenticated the turn, when one did. */ readonly apiKeyId?: string; readonly tokens: number; @@ -1339,6 +1342,7 @@ export async function runTurn( // alone says has room. spend: { userId: request.userId, + projectIds: request.projectId !== undefined ? [request.projectId] : [], ...(request.apiKeyId !== undefined ? { apiKeyId: request.apiKeyId } : {}), tokens: context.estimatedTokens + (request.budget?.reserveOutputTokens ?? 0), diff --git a/services/platform/lib/engine/core/syntax/parse.ts b/services/platform/lib/engine/core/syntax/parse.ts index 04a3971554..10668d662f 100644 --- a/services/platform/lib/engine/core/syntax/parse.ts +++ b/services/platform/lib/engine/core/syntax/parse.ts @@ -129,42 +129,64 @@ function prepareAst(root: unknown, offset: number): boolean { /** Locate a lexical template closer within the expression budget. The caller * validates the complete span; returning an AST end would lose trailing - * comments and make their braces look like template delimiters again. */ -export function expressionEnd(text: string, start: number): number | undefined { - const end = Math.min(text.length, start + MAX_SOURCE_SIZE + 2); - try { - // Locate the template closer lexically before budgeting: braces inside - // strings, comments and nested expressions are not template delimiters. - // Stop before plain text after the closer enters the token/depth budget. - let depth = 0; - let count = 0; - for (const token of tokenizer(text.slice(start, end), OPTIONS)) { - const label = token.type.label; - if ( - label === '}' && - depth === 0 && - text.slice(start + token.start, start + token.start + 2) === '}}' - ) { - return start + token.start; + * comments and make their braces look like template delimiters again. Return + * the trimmed source boundary too, so validation never rescans long padding. */ +export function createExpressionEndReader( + text: string, +): (start: number) => { close: number; sourceEnd: number } | undefined { + // Template starts advance monotonically. Reuse a whitespace island rather + // than rescanning its unbounded suffix after every failed legacy span. + // The interval belongs to this field only; no source survives its scan. + let whitespaceStart = -1; + let whitespaceEnd = -1; + return (start) => { + const end = Math.min(text.length, start + MAX_SOURCE_SIZE + 2); + try { + // Locate the template closer lexically before budgeting: braces inside + // strings, comments and nested expressions are not template delimiters. + // Stop before plain text after the closer enters the token/depth budget. + let depth = 0; + let count = 0; + for (const token of tokenizer(text.slice(start, end), OPTIONS)) { + const label = token.type.label; + if ( + label === '}' && + depth === 0 && + text.slice(start + token.start, start + token.start + 2) === '}}' + ) { + const close = start + token.start; + return { + close, + sourceEnd: start + text.slice(start, close).trimEnd().length, + }; + } + if (++count > MAX_PARSE_TOKENS) return undefined; + if (['(', '[', '{', '${'].includes(label)) { + if (++depth > MAX_PARSE_DEPTH) return undefined; + } else if ([')', ']', '}'].includes(label)) + depth = Math.max(0, depth - 1); } - if (++count > MAX_PARSE_TOKENS) return undefined; - if (['(', '[', '{', '${'].includes(label)) { - if (++depth > MAX_PARSE_DEPTH) return undefined; - } else if ([')', ']', '}'].includes(label)) - depth = Math.max(0, depth - 1); + // The size limit applies to trimmed code, not surrounding whitespace. + // Only whitespace may extend past the bounded tokenization window. + // The final full-span parse still enforces the trimmed source budget. + let close = end; + if (end >= whitespaceStart && end <= whitespaceEnd) { + close = whitespaceEnd; + } else { + whitespaceStart = end; + while (whitespaceStart > start && /\s/.test(text[whitespaceStart - 1])) + whitespaceStart--; + while (close < text.length && /\s/.test(text[close])) close++; + whitespaceEnd = close; + } + return depth === 0 && text.slice(close, close + 2) === '}}' + ? { close, sourceEnd: Math.max(start, whitespaceStart) } + : undefined; + } catch (e) { + if (!(e instanceof SyntaxError) && !(e instanceof RangeError)) throw e; + return undefined; } - // The size limit applies to trimmed code, not surrounding whitespace. - // Only whitespace may extend past the bounded tokenization window. - // The final full-span parse still enforces the trimmed source budget. - let close = end; - while (close < text.length && /\s/.test(text[close])) close++; - return depth === 0 && text.slice(close, close + 2) === '}}' - ? close - : undefined; - } catch (e) { - if (!(e instanceof SyntaxError) && !(e instanceof RangeError)) throw e; - return undefined; - } + }; } /** acorn's nodes ARE ESTree nodes; its typings are a parallel declaration. */ diff --git a/services/platform/lib/engine/core/syntax/tokens.test.ts b/services/platform/lib/engine/core/syntax/tokens.test.ts index 6c9dc696d2..0ed0aca086 100644 --- a/services/platform/lib/engine/core/syntax/tokens.test.ts +++ b/services/platform/lib/engine/core/syntax/tokens.test.ts @@ -2,8 +2,9 @@ import vm from 'node:vm'; -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; +import { MAX_SOURCE_SIZE } from './parse'; import { conditionKind, exprSegments, @@ -130,6 +131,149 @@ describe('tokenizeTemplate — the compatibility matrix', () => { }); }); +describe('tokenizeTemplate — bounded whitespace recovery', () => { + function measured(value: string) { + const testSpy = vi.spyOn(RegExp.prototype, 'test'); + const trimSpy = vi.spyOn(String.prototype, 'trimEnd'); + try { + const result = tokenizeTemplate(value); + const whitespaceChecks = testSpy.mock.contexts.filter( + (context) => context instanceof RegExp && context.source === '\\s', + ).length; + const longTrimmedCharacters = trimSpy.mock.contexts.reduce( + (total, context) => + total + + (typeof context === 'string' && context.length > MAX_SOURCE_SIZE + 2 + ? context.length + : 0), + 0, + ); + return { + result, + counts: () => ({ whitespaceChecks, longTrimmedCharacters }), + }; + } finally { + testSpy.mockRestore(); + trimSpy.mockRestore(); + } + } + + it.each([ + ['line comment', '{{//}}', ''], + ['closed comment', '{{1/*}}', '*/'], + ['malformed prefix and closed comment', '{{1+/*}}', '*/'], + ])( + 'scans a shared padding suffix once after %s failures', + (_name, prefix, tail) => { + for (const count of [16, 64]) { + for (const closer of ['', '}}']) { + const value = + prefix.repeat(count) + tail + ' '.repeat(16384) + closer; + const { result, counts } = measured(value); + if (prefix === '{{1/*}}' && closer) { + // Closing the block comment makes the entire recovered span valid. + expect(exprSegments(result)).toEqual([ + { + kind: 'expr', + start: 0, + end: value.length, + exprStart: 2, + exprEnd: prefix.length * count + tail.length, + source: (prefix.repeat(count) + tail).slice(2), + parsed: true, + }, + ]); + } else { + expect( + exprSegments(result).map(({ start, end, source }) => ({ + start, + end, + source, + })), + ).toEqual(legacy(value)); + expect( + exprSegments(result).every((segment) => !segment.parsed), + ).toBe(true); + } + expect( + result.segments + .map((segment) => value.slice(segment.start, segment.end)) + .join(''), + ).toBe(value); + expect(counts().whitespaceChecks).toBeLessThan(value.length * 2); + expect(counts().longTrimmedCharacters).toBeLessThan(value.length * 2); + } + } + }, + ); + + it('keeps separate whitespace islands and fresh templates independent', () => { + const padding = ' \t'.repeat(8192); + const value = + '{{//}}'.repeat(32) + + padding + + '\nseparator ' + + '{{1+/*}}'.repeat(32) + + '*/' + + padding + + '}}'; + for (const input of [ + value, + '{{//}}'.repeat(16) + '\t'.repeat(20000) + '}}', + value, + ]) { + const { result, counts } = measured(input); + expect( + exprSegments(result).map(({ start, end, source }) => ({ + start, + end, + source, + })), + ).toEqual(legacy(input)); + expect(exprSegments(result).every((segment) => !segment.parsed)).toBe( + true, + ); + expect( + result.segments + .map((segment) => input.slice(segment.start, segment.end)) + .join(''), + ).toBe(input); + expect(counts().whitespaceChecks).toBeLessThan(input.length * 2); + expect(counts().longTrimmedCharacters).toBeLessThan(input.length * 2); + } + }); + + it('preserves a valid quoted closer with long padding after failed spans', () => { + const prefix = '{{//}}'.repeat(32) + '\n'; + const expression = "'a}}b' /* trailing comment */"; + const value = + prefix + + '{{' + + ' '.repeat(20000) + + expression + + '\t'.repeat(20000) + + '}}'; + const { result, counts } = measured(value); + const expressions = exprSegments(result); + expect( + expressions + .slice(0, -1) + .map(({ start, end, source }) => ({ start, end, source })), + ).toEqual(legacy(prefix)); + expect(expressions.at(-1)).toEqual({ + kind: 'expr', + start: prefix.length, + end: value.length, + exprStart: prefix.length + 20002, + exprEnd: prefix.length + 20002 + expression.length, + source: expression, + parsed: true, + }); + expect(counts().whitespaceChecks).toBeLessThan(value.length * 2); + expect(counts().longTrimmedCharacters).toBeLessThan(value.length * 4); + }); +}); + describe('isSingleTemplate / conditionKind', () => { it('one expression with only whitespace around keeps its type', () => { const v = ' {{ input.n }}\n'; diff --git a/services/platform/lib/engine/core/syntax/tokens.ts b/services/platform/lib/engine/core/syntax/tokens.ts index ef8096b5da..3c0ceecbd6 100644 --- a/services/platform/lib/engine/core/syntax/tokens.ts +++ b/services/platform/lib/engine/core/syntax/tokens.ts @@ -17,7 +17,7 @@ * is listed in `unterminated` so validation can say so. */ -import { expressionEnd, parseExpressionIn } from './parse'; +import { createExpressionEndReader, parseExpressionIn } from './parse'; export interface TemplateSegment { kind: 'text' | 'expr'; @@ -82,18 +82,20 @@ function matchTemplate( value: string, open: number, close: number, + readEnd: ReturnType, ): TemplateSegment { if (parsesIn(value, open + 2, close)) { return exprSegment(value, open, close, true); } const [start] = trimmedSpan(value, open + 2, close); - const later = expressionEnd(value, start); + const later = readEnd(start); if ( later !== undefined && - later > close && - parsesIn(value, open + 2, later) + later.close > close && + later.sourceEnd > start && + parseExpressionIn(value, start, later.sourceEnd).ok ) { - return exprSegment(value, open, later, true); + return exprSegment(value, open, later.close, true); } return exprSegment(value, open, close, false); } @@ -101,6 +103,7 @@ function matchTemplate( export function tokenizeTemplate(value: string): Tokenized { const segments: TemplateSegment[] = []; const unterminated: Array<[number, number]> = []; + const readEnd = createExpressionEndReader(value); let textStart = 0; const lastClose = value.lastIndexOf('}}'); let open = value.indexOf('{{'); @@ -115,7 +118,7 @@ export function tokenizeTemplate(value: string): Tokenized { open = value.indexOf('{{', open + 2); continue; } - const segment = matchTemplate(value, open, close); + const segment = matchTemplate(value, open, close, readEnd); if (open > textStart) { segments.push({ kind: 'text', start: textStart, end: open }); } diff --git a/services/platform/messages/de/governance.yml b/services/platform/messages/de/governance.yml index b2c04e80b2..69e6b85d91 100644 --- a/services/platform/messages/de/governance.yml +++ b/services/platform/messages/de/governance.yml @@ -1492,6 +1492,7 @@ dataSubjectRequests: wfExecutionsErased: Gelöschte Automatisierungsläufe startedAt: Gestartet completedAt: Abgeschlossen + legacyAutomationHold: Einige Automationsläufe wurden aufbewahrt, weil ihre früheren externen Aktionen noch nicht überprüft wurden. Ein erneuter Versuch hebt diese Sperren nicht auf. errorMessage: Fehler errorState: title: Diese Anfrage konnte nicht geladen werden @@ -1528,6 +1529,7 @@ dataSubjectRequests: gdpr_erasure_rejected: Zurückgewiesen gdpr_erasure_cancelled: Abgebrochen categories: + modelApiRequests: Modellanfragen userMemories: Persönliche Memos userPreferences: Nutzereinstellungen messageFeedback: Nachrichten-Feedback diff --git a/services/platform/messages/de/settings.yml b/services/platform/messages/de/settings.yml index 310d70ab6f..134eb4fab3 100644 --- a/services/platform/messages/de/settings.yml +++ b/services/platform/messages/de/settings.yml @@ -263,6 +263,7 @@ organization: deleteLoading: Lösche… deleteSuccess: Organisation gelöscht deleteFailed: Organisation konnte nicht gelöscht werden + deleteBlockedByLegacyAutomation: Automationsläufe bleiben gesperrt, weil ihre früheren externen Aktionen noch nicht überprüft wurden. Deine Organisation wurde nicht gelöscht. Eine Stopp-Anfrage hebt diese Sperren nicht auf. deleteBlockedByLegalHold: Ein aktiver Legal Hold bewahrt die Daten dieser Organisation. Gib alle Holds unter Richtlinien > Legal Hold frei und versuch es dann erneut. deleteTypeNameLabel: Tippe den Namen der Organisation zur Bestätigung deleteConfirmNameMismatch: Die Bestätigung stimmt nicht mit dem Namen der Organisation überein. Lade die Seite neu und versuch es erneut. diff --git a/services/platform/messages/en/governance.yml b/services/platform/messages/en/governance.yml index 01fda99fa3..0e41933098 100644 --- a/services/platform/messages/en/governance.yml +++ b/services/platform/messages/en/governance.yml @@ -1442,6 +1442,7 @@ dataSubjectRequests: wfExecutionsErased: Automation runs erased startedAt: Started completedAt: Completed + legacyAutomationHold: Some automation runs were preserved because their earlier external actions have not been verified. Retrying does not release these holds. errorMessage: Error errorState: title: Could not load this request @@ -1474,6 +1475,7 @@ dataSubjectRequests: gdpr_erasure_rejected: Rejected gdpr_erasure_cancelled: Cancelled categories: + modelApiRequests: Model requests userMemories: Personal memories userPreferences: User preferences messageFeedback: Message feedback diff --git a/services/platform/messages/en/settings.yml b/services/platform/messages/en/settings.yml index 462908dab3..27b681701b 100644 --- a/services/platform/messages/en/settings.yml +++ b/services/platform/messages/en/settings.yml @@ -253,6 +253,7 @@ organization: deleteLoading: Deleting… deleteSuccess: Organization deleted deleteFailed: Couldn't delete organization + deleteBlockedByLegacyAutomation: Automation runs are on hold because their earlier external actions have not been verified. Your organization was preserved. A stop request does not release these holds. deleteBlockedByLegalHold: An active legal hold is preserving this organization's data. Release every hold under Governance > Legal hold, then try again. deleteTypeNameLabel: Type the organization name to confirm deleteConfirmNameMismatch: The confirmation doesn't match the organization name. Reload the page and try again. diff --git a/services/platform/messages/fr/governance.yml b/services/platform/messages/fr/governance.yml index c9e7206aea..5c6d91174e 100644 --- a/services/platform/messages/fr/governance.yml +++ b/services/platform/messages/fr/governance.yml @@ -1536,6 +1536,7 @@ dataSubjectRequests: wfExecutionsErased: Exécutions d'automatisation effacées startedAt: Démarré completedAt: Terminé + legacyAutomationHold: Certaines exécutions d'automatisation ont été conservées car leurs actions externes antérieures n'ont pas encore été vérifiées. Réessayer ne lève pas ces blocages. errorMessage: Erreur errorState: title: Impossible de charger cette demande @@ -1569,6 +1570,7 @@ dataSubjectRequests: gdpr_erasure_rejected: Rejetée gdpr_erasure_cancelled: Annulée categories: + modelApiRequests: Requêtes aux modèles userMemories: Mémoires personnelles userPreferences: Préférences utilisateur messageFeedback: Retours sur messages diff --git a/services/platform/messages/fr/settings.yml b/services/platform/messages/fr/settings.yml index 6d8cb5d43d..b9f36b40d4 100644 --- a/services/platform/messages/fr/settings.yml +++ b/services/platform/messages/fr/settings.yml @@ -265,6 +265,7 @@ organization: deleteLoading: Suppression… deleteSuccess: Organisation supprimée deleteFailed: Échec de la suppression de l'organisation + deleteBlockedByLegacyAutomation: Des exécutions d'automatisation restent bloquées car leurs actions externes antérieures n'ont pas encore été vérifiées. Ton organisation a été conservée. Une demande d'arrêt ne lève pas ces blocages. deleteBlockedByLegalHold: Une conservation légale active préserve les données de cette organisation. Lève chaque conservation dans Gouvernance > Conservation légale, puis réessaie. deleteTypeNameLabel: Tape le nom de l'organisation pour confirmer deleteConfirmNameMismatch: La confirmation ne correspond pas au nom de l'organisation. Recharge la page et réessaie. diff --git a/services/platform/tests/guards/turbo-inputs.guard.test.ts b/services/platform/tests/guards/turbo-inputs.guard.test.ts index efefcefdfe..38e908ed32 100644 --- a/services/platform/tests/guards/turbo-inputs.guard.test.ts +++ b/services/platform/tests/guards/turbo-inputs.guard.test.ts @@ -196,6 +196,11 @@ const OUTSIDE_READS = [ /** Every outside repo module the platform's sources import, and who imports it. */ const STATIC_IMPORTS = [ + { + path: 'tools/cli/src/lib/deployment/automation-cutover-sql.ts', + importers: + 'backend/jobs/automation-floor.integration.ts proves the maintained CLI admission lock and census', + }, { path: 'services/web/app/content/product-screenshots.ts', importers: diff --git a/services/platform/tests/integration/container-smoke-test.ts b/services/platform/tests/integration/container-smoke-test.ts index f0626d81e9..e1f5bf94e0 100644 --- a/services/platform/tests/integration/container-smoke-test.ts +++ b/services/platform/tests/integration/container-smoke-test.ts @@ -334,6 +334,40 @@ async function main(): Promise { // Platform: Vite server with platform-ready marker. const platformContainer = await compose.containerName('platform'); + + // The deployment control channel is docker-exec localhost, never public. + // The plain edge refusal distinguishes it from a backend token refusal. + for (const path of [ + '/api/control', + '/api/control/', + '/api/control/drain-status?probe=1', + '/api/%63ontrol/drain-status', + ]) { + const probe = await capture([ + 'docker', + 'exec', + platformContainer, + // nosemgrep: tools.opengrep.rules.trailofbits.generic.curl-insecure.curl-insecure -- Isolated smoke network and self-signed proxy; no credentials or external traffic. + 'curl', + '--insecure', + '--silent', + '--show-error', + '--max-time', + '10', + '--connect-to', + 'localhost:443:proxy:443', + '--write-out', + '\n%{http_code}', + `https://localhost${path}`, + ]); + const label = `Public proxy refuses deployment control ${path}`; + if (probe.exitCode === 0 && probe.stdout === 'Not found\n404') { + r.pass(label); + } else { + r.fail(label); + } + } + const viteCode = await httpStatus('http://localhost:13000/api/health', 10); if (viteCode === '200') { r.pass(`Platform /api/health: HTTP ${viteCode}`); diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index bc9967a0d7..0e1116065a 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -4,8 +4,24 @@ Manual effort is expensive; spend it where a headless run cannot judge. Read this before hand-verifying anything, and read the seam notes before running a suite alongside the automated ones — they drive the same stack. +Legacy automation holds during erasure and organization deletion are covered by +`backend/domains/automations/legacy-protocol.integration.ts`, +`backend/domains/erasure/service.lifecycle.test.ts`, +`backend/domains/organizations/service.test.ts` and +`backend/domains/organizations/routes.test.ts`. The receipt +drawer test verifies that preserved runs are counted separately and their reason +is explained. `backend/core/governance/erasure_counts.test.ts` and the receipt read +regression keep summary and breakdown counts consistent for both stored shapes. These checks do not claim a retirement or hold-release mechanism. + ## Coverage map +Docker package-cache permission setup uses an immutable multi-architecture helper +image. `services/sandbox/src/volume.test.ts` checks the actual CLI arguments for +new caches and in-use cache repairs, preserves mode `1777`, and verifies that +Renovate discovers the production pin. This fake-CLI coverage does not prove a +registry pull or native helper execution; first-use registry availability remains +a deployment check. + The docs screenshot runner's locale selection, stable English paths, isolated state directory precedence, invalid argument rejection, and asynchronous native label isolation are covered by `tests/docs-screenshots/capture-options.test.ts` @@ -357,7 +373,7 @@ Legend: ✅ fully automated · 🔶 partially automated · ⛔ manual-only (no s | [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | Every door answers a refused task limit with the shared sentence. An agent's empty or whitespace-only `task_comment` body gets the empty-comment sentence (1 to 10,000 UTF-16 code units), and a blank `task_upsert_by_external_ref` title gets the empty-title sentence `task_create` answers. Both are refused before any read or write; they used to get generic "needs {…}" text. The app's label create and rename answer an empty name, or one over 50 code units, with the domain's label-name sentence; their schema capped a name at 100, and `''` or 101+ got a bare `invalid body`. The external-issue intake refuses a blank title and more than 50 labels with the domain's sentences, and cuts an over-long title and description instead of answering its old caps (500, 50,000). An imported description is cut to 20,000 code units ending in "…", like its title, on every import lane: the agent's upsert, the workflow natives and the intake. `workspace_status` says so, and the REST intake still refuses one by name. A cut never splits a grapheme (next row). The refusal guard also reads every `ProjectError` a projects-domain function reached from a task door throws. The REST reference names the description, label and comment-body caps, and its 400 example, in the unit the answers use | ✅ unit + Postgres | `backend/core/tasks/helpers.test.ts`, `backend/domains/tasks/external-ref.test.ts`, `backend/domains/tasks/routes.limits.test.ts`, `backend/domains/tasks/errors.test.ts`, `backend/core/node_only/sandbox/workspace_tools_bridge.test.ts`, `backend/integration-check.ts` (`checkAutomationRunToolLane`: an empty comment and a blank sync title through `/api/tools/execute`, nothing written; an over-long synced description stored cut on the create and the reconcile) | | [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | An imported title or description is cut on a grapheme boundary (`Intl.Segmenter`): a ZWJ family, a flag, a skin-tone modifier, a keycap or a letter with its combining mark is kept whole or dropped whole, never split, and one grapheme longer than the cap leaves only the "…". The workflow natives `task.upsert` and `task.upsert_issues` answer a blank title with the shared empty-title sentence before any write (a batch names the item, `issues.:`), and return the title the task carries — cut on a create, the stored one after a source-snapshot reconcile — never the title sent; their connector mocks cut alike and refuse with the same sentence, which a test run reports under `MOCK_BODY_FAILED` where a live run answers `INPUT_INVALID`, and the action schema no longer pre-empts `''` with a generic `minLength`. The GitHub and GlitchTip importers seed a task's description with the domain's own cut, never a local 50,000-unit slice. The refusal guard also reads every `AutomationError` an automations-domain function reached from a task door throws, and every `AutomationError`, `ProjectError`, `RestRefusal` and `FolderError` a door's own file builds: `AUTOMATION_PROJECT_FORBIDDEN` no longer repeats the `workflowSlug` sent and is one shared sentence at both throw sites, and the REST task door's `AUTOMATION_NOT_DEPLOYED` no longer repeats the slug either. The board names the caps a save breaks: a description draft over 20,000 code units names the cap under the field — a sentence that stays the same while the draft stays over, so a screen reader hears it once — shows a `used / max` counter outside that live region — the trimmed length a save keeps, grouped in the reader's language, and describing the field so it is read on focus — and holds **Save** and **Create task**; `TASK_TITLE_INVALID` and `TASK_DESCRIPTION_INVALID` toast the cap in the reader's language instead of the generic error; the inline title takes at most 200; the label pickers use the shared label caps; the EN/DE/FR task pages state the two caps the domain holds. REST `data.issues` names a string cap in UTF-16 code units, as the OpenAPI and Markdown references' example does | 🔶 unit + Postgres | `backend/core/tasks/helpers.test.ts`, `lib/connectors/natives/platform-tasks.test.ts` (the mocks run in the node-vm runner against the domain helpers), `backend/domains/tasks/external-ref.test.ts`, `backend/domains/connectors/task-store.upsert.test.ts`, `backend/domains/tasks/errors.test.ts`, `backend/domains/automations/store.begin-run.test.ts`, `backend/rest/shared.test.ts`, `backend/rest/v1-tasks.test.ts`, `lib/connectors/dispatcher.test.ts`, `lib/connectors/issue-import.test.ts`, `lib/engine/core/validate/schema.test.ts`, `app/features/tasks/components/editable-description.test.tsx`, `app/features/tasks/components/task-modal.limits.test.tsx`, `packages/ui/src/components/forms/textarea.test.tsx`, `backend/core/tasks/limits_docs.test.ts`, `app/features/tasks/lib/task-limit-refusal.test.ts`, `backend/integration-check.ts` (`checkTaskExternalIssueSync`: a source reconcile and a batch create answer the stored title); how the over-cap line reads and wraps stays manual (`TASK-B11`) | | [tasks](../suites/tasks.md) | Native settled-review repair is a separate tagged `resumeFrom` branch: strict old-boundary refusal, stored decision readback, exact source and unchanged human intent, current delegation authority on new admissions and same-manager replay, original issuer provenance, concurrent dedupe, ordinary next-review completion, busy/dependency/hourly limits, and rollback of run, queue and status if receipt persistence fails. A newer human or pending review hides the historical native decision. No UI or model judgment is inferred. | ✅ unit + real PostgreSQL + native HTTP | `backend/core/node_only/sandbox/workspace_tools_bridge.repair.test.ts`, `backend/domains/tasks/review-decision.test.ts`, `backend/domains/tasks/review-repair.integration.ts` (through `checkAgentTaskReviews`), existing `checkDelegatedAgentStartTool` question controls | -| [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | An agent's task reads cover a whole queue: `task_find` answers pages of at most 50 with `isDone` and a signed `continueCursor` bound to its order, filters and scope (another filter, order, project or organization, and a malformed, cut or edited cursor, answer `invalid_args`, never a first page), `totalFound` only when one page holds every match, and walks 260 tasks tied on rank and creation millisecond each once in the database's own `(status, rank, id)` or `(created_at, id)` order; in created order a pass lists a task at most once while the board moves, in board order a task moved past the cursor is listed again and one moved behind it is skipped. `task_get` names subtasks, blockers and comments by id (never another project's task), pages comments past the newest 50 with `commentCursor` and project-agent runs newest-created first with `runCursor`, reads a queued or running run as `live`, a finished one with `settledAt` and `failureCode`, and explicit `retryPending` using the task card's shared retry calculation (armed versus unarmed, retired, spent, superseded, historical and deleted-agent failures; an absent field on an older reader stays unknown), an automation run's `waitingFor` `ask`/`approval` and a `pendingReview`, with a 500-character feedback excerpt and no transcript, error text, result or workspace handle; a failed run read answers `error`, never an idle task. The routine-question protocol's read half: a worker's agent-authored question starts nothing (its @mention is inert), the manager's answer reads back as its comment, `done` stays refused and the review pending, and a pass checkpoint saved in a comment is found past the newest 50 by a later run, whose cursor resumes the pass so both legs list every task exactly once | ✅ unit + real Postgres | `backend/core/node_only/sandbox/workspace_tools_bridge.task_reads.test.ts`, `backend/domains/tasks/service.agent-list.test.ts`, `backend/domains/tasks/agent-work-state.test.ts`, `backend/domains/tasks/agent-runs.test.ts`, `backend/domains/chat/shim.test.ts`, `backend/domains/tasks/agent-read-tools.integration.ts` (`checkAgentTaskReadTools` in `backend:integration`); the restart itself (`task_start_agent`) is its own lane's | +| [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | An agent's task reads cover a whole queue: `task_find` answers pages of at most 50 with `isDone` and a signed `continueCursor` bound to its order, filters and scope (another filter, order, project or organization, and a malformed, cut or edited cursor, answer `invalid_args`, never a first page), `totalFound` only when one page holds every match, and walks 260 tasks tied on rank and creation millisecond each once in the database's own `(status, rank, id)` or `(created_at, id)` order; in created order a pass lists a task at most once while the board moves, in board order a task moved past the cursor is listed again and one moved behind it is skipped. `task_get` names subtasks, blockers and comments by id (never another project's task), pages comments past the newest 50 with `commentCursor` and project-agent runs newest-created first with `runCursor`, reads a queued or running run as `live`, a finished one with `settledAt` and `failureCode`, and explicit `retryPending` using the task card's shared retry calculation (armed versus unarmed, retired, spent, superseded, historical and deleted-agent failures; an absent field on an older reader stays unknown), an automation run's `waitingFor` `ask`/`approval` and a `pendingReview`, with a 500-character feedback excerpt and no transcript, error text, result or workspace handle; a failed run read answers `error`, never an idle task. Opt-in `view: "occupancy"` retains the exact requested run beside the newest occupant and the selected workflow, omits context/review bodies, preserves scope, unavailable reads and native retry state, and reports a non-atomic read interval without an admission verdict; synthetic response bytes and native sequential-read timings are measured. The routine-question protocol's read half: a worker's agent-authored question starts nothing (its @mention is inert), the manager's answer reads back as its comment, `done` stays refused and the review pending, and a pass checkpoint saved in a comment is found past the newest 50 by a later run, whose cursor resumes the pass so both legs list every task exactly once | ✅ unit + real Postgres | `backend/core/node_only/sandbox/workspace_tools_bridge.task_reads.test.ts`, `backend/domains/tasks/service.agent-list.test.ts`, `backend/domains/tasks/agent-work-state.test.ts`, `backend/domains/tasks/agent-runs.test.ts`, `backend/domains/chat/shim.test.ts`, `backend/domains/tasks/agent-read-tools.integration.ts` (`checkAgentTaskReadTools` in `backend:integration`); the restart itself (`task_start_agent`) is its own lane's | | [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | `workspace_status` names the release label of the backend that answered: `platform.version` is that process's `TALE_VERSION` (the image's build stamp unless the environment overrides it), trimmed, when it has the release shape (`0.5.64`, a prerelease such as `0.6.0-rc.1`), and `null` with a fixed note otherwise — an unset or blank stamp, `dev`, the Build workflow's `candidate-sha-…`, `pr-…-sha-…` and `sha-…` images, a `v`-prefixed or partial label — whose label is never echoed. The door adds it after the session-token check, beside the tool listing it answers unchanged (the grants, or the no-tools note); nothing but the bearer token is read from the request, so a forged body, query or header changes nothing, and a refused token still gets the bare 401. The in-sandbox bridge relays the answer byte for byte and sends `{}` whatever the model passes. A mistakenly nested `workspace_tool({tool:"workspace_status"})` uses that same authenticated status door, never the execution grant gate or an execution fallback; authentication failures remain failures, ordinary task calls remain grant-gated, and near-miss or missing names keep their existing refusals. Guidance names the separate `workspace_status` MCP tool with `{}`, never a new grant. Its tool description calls the value a label of that backend, not proof of what is deployed or of its health | ✅ unit + Postgres | `backend/domains/sandbox/dispatch-routes.test.ts`, `lib/shared/release-version.test.ts`, `services/sandbox-runtime/daemon/src/tale-connectors-mcp.test.ts`, `backend/integration-check.ts` (`checkSandboxSpawner`: a release stamp, a no-grants token, a forged body, an expired token and a candidate stamp through `/api/tools/status`) | | [accessibility](../suites/accessibility.md) / [tasks](../suites/tasks.md) | Error labels and explanations retain AA contrast on page, card and muted form surfaces in both themes; destructive alerts and actions remain readable | ✅ Chromium | `packages/ui/src/components/forms/label.browser.test.tsx`; over-cap copy wrapping remains manual (`TASK-B11`) | | [auth](../suites/auth.md) | Authenticator label and issuer name the client, the product and a non-production environment (`Example plus Tale Platform TE`; `Tale Platform` with neither set) in both enrollment and existing-secret URIs; re-display preserves the secret, and invalid client names or environment labels are refused. The web tier hands the page both settings, normalized, and leaves out one the backend would refuse; backup codes download under the same words from the enrollment wall and from Account | ✅ backend + server + component + e2e | `lib/shared/authenticator-name.test.ts`, `backend/auth/auth.totp-issuer.test.ts`, `backend/env.test.ts`, `server.test.ts`, `vite-plugins/inject-env.test.ts`, `app/features/settings/account/lib/download-backup-codes.test.ts`, `tests/e2e/specs/auth-account.spec.ts` (*enrolls with a generated TOTP code*); `AUTH-F31` checks a real authenticator app, `AUTH-F32` the saved file. | diff --git a/services/platform/tests/manual/reference/automation/automations.md b/services/platform/tests/manual/reference/automation/automations.md index 989c577f26..0379bac92f 100644 --- a/services/platform/tests/manual/reference/automation/automations.md +++ b/services/platform/tests/manual/reference/automation/automations.md @@ -8,9 +8,10 @@ Rows for [`automations`](../../suites/automations.md) boxes that moved out of th | [automations](../../suites/automations.md) | Version picker remains at the right of the tabs at 320, 390 and 1280px, shows messages and test results, marks the selected version, and opens a version from General | ✅ automated | `app/features/automations/components/automation-editor.browser.test.tsx`; draft confirmation remains covered by `automation-editor.test.tsx` | | [automations](../../suites/automations.md) | A Gmail triage digest carries subject, sender, time and snippet per row: the fan-out behind `conversation.list_mailbox_messages` lists bare ids (`users.messages.list`) and fetches each one's metadata with the credential that listed it, Outlook and IMAP read their envelopes off the listing alone, a message gone between the list and the fetch is skipped, and every fetch failing fails that mailbox instead of reading as an empty inbox | ✅ unit | `backend/core/conversations/sync_mailbox.test.ts` (`listMailboxMessages`) | | [automations](../../suites/automations.md) | The Editor's Problems surface: the author-gated draft check (`POST /api/app/automations/:name/validate` answers members 403 and writes nothing) and refusals that carry their errors and warnings under `data`; the check waits for a pause in the edits, withdraws an older request, keeps the last list while the next runs and fails without a toast; issues get stable ids, document order, per-node counts, crumbs and a go-to target; node boxes count their problems and say them after their name; a field's problem describes its control and never alerts; a node's problems without a field of their own list at the top of its fields; go to focuses the field with the offending text selected, under the canvas on a desktop and through the sheets on a tablet; the dock and the inspector pass axe's contrast check in light and dark; Save waits with its reason (a visible line on a phone); a save or deploy refused for errors lands in Problems on its first error, without a toast, on every problem whatever the filter was left on, and is said once (the deploy alert names it, the announcer counts); a draft's check is announced only when its counts change, and one that hangs fails after 15 s so Save never waits on it; a reopened sheet starts on All with focus inside it; on a phone, Show problems beside the Save reason opens the list on its first error; types read as words and an unknown code keeps the engine's English in Technical details; ⌘S with errors keeps the browser's page save shut and shows the reason | ✅ unit + component + Chromium | `backend/domains/automations/routes.validate.test.ts`, `backend/domains/automations/routes.authoring.test.ts`, `app/features/automations/hooks/use-automation-validation.test.tsx`, `app/features/automations/lib/issues.test.ts`, `app/features/automations/lib/issue-text.test.ts`, `app/features/automations/lib/errors.test.ts`, `app/features/automations/components/automation-node.test.tsx`, `app/features/automations/components/node-inspector.test.tsx`, `app/features/automations/components/automation-editor.test.tsx`, `app/features/automations/components/automation-editor.browser.test.tsx`, `packages/ui/src/components/editor/editor-actions.test.tsx`, `packages/ui/src/components/feedback/issue-summary.browser.test.tsx`; translation quality, a screen reader's actual speech and the live round trip stay manual (`AUTO-F62`–`AUTO-F68`, `AUTO-B15`, `AUTO-B16`, `AUTO-A7`–`AUTO-A10`) | -| [automations](../../suites/automations.md) | Analysis refuses oversized source, token streams and deep syntax before recursive consumers; binary operations on BigInt are not constant-folded, unreachable item/index reads do not become scope errors, and shadowed globals stay unknown. Valid boundary expressions retain quoted/comment/regex/template-literal closers and plain suffixes through the real runner; an installed runner cannot bypass an analysis refusal. Limit messages render in EN/DE/FR with de-CH fallback. | ✅ unit + real code runner | `lib/engine/core/syntax/limits.test.ts`, `constant.test.ts`, `tokens.test.ts`, `parse.test.ts`, `lib/engine/core/analysis/rules/names.test.ts`, `app/features/automations/lib/issue-text.test.ts`; limits deliberately restrict previously valid large or deep code, and rendered translations remain a browser check | +| [automations](../../suites/automations.md) | Analysis refuses oversized source, token streams and deep syntax before recursive consumers; binary operations on BigInt are not constant-folded, unreachable item/index reads do not become scope errors, and shadowed globals stay unknown. Failed template recovery scans shared whitespace padding once per field, preserving legacy spans, separate whitespace islands and valid long padding; deterministic operation counts cover suffixes with and without a final closer. Valid boundary expressions retain quoted/comment/regex/template-literal closers and plain suffixes through the real runner; an installed runner cannot bypass an analysis refusal. Limit messages render in EN/DE/FR with de-CH fallback. | ✅ unit + real code runner | `lib/engine/core/syntax/limits.test.ts`, `constant.test.ts`, `tokens.test.ts`, `parse.test.ts`, `lib/engine/core/analysis/rules/names.test.ts`, `app/features/automations/lib/issue-text.test.ts`; limits deliberately restrict previously valid large or deep code, and rendered translations remain a browser check | | [automations](../../suites/automations.md) | Deploy and rollback check the installed automation protocol before mutation, bind capable backend images to immutable source/digest evidence, refuse unknown or custom DB custody, and inspect resumed writers. Catalog reads reject shadow or malformed ledgers. | ✅ CLI + real Postgres | `tools/cli/src/lib/deployment/automation-protocol.test.ts`, `automation-floor.test.ts`, `tools/cli/src/lib/actions/rollback.test.ts`, `tools/cli/scripts/automation-image-protocol.test.ts`, `backend/jobs/automation-floor.integration.ts` (owned database; CREATE DATABASE required); published image labels and full live deployment remain release acceptance checks | | [automations](../../suites/automations.md) | Legacy holds remain distinct from queued/running/finished states; unknown effects stay visible; acknowledged stop requests pin the hold identity, reject refreshed confirmations, preserve the hold after acceptance, and expose one recoverable refusal; task panels hide ordinary start/cancel/approval while held | 🔶 component with real mutation adapter and synthetic transport; live browser and migration outcome remain separate checks | `app/features/automations/components/run-quarantine-card.test.tsx`, `run-status-badge.test.tsx`, `run-detail.test.tsx`, `app/features/automations/lib/run-view.test.ts`, `app/features/tasks/components/task-subject-panel.test.tsx` | | [automations](../../suites/automations.md) / [tasks](../../suites/tasks.md) | Protocol cutover holds unfinished legacy runs without inventing effect outcomes. The real boot transaction and its schema-bound ledger fence stale snapshots; old claim/progress writes, held-task starts and destructive evidence changes refuse. An exact-identity acknowledged stop request records one operator decision while retaining the hold, task exclusion and original asks. | ✅ unit + real PostgreSQL | `backend/domains/automations/legacy-protocol.integration.ts`, `backend/domains/automations/legacy-quarantine.test.ts`, `backend/domains/automations/routes.project-scope.test.ts`, `backend/domains/tasks/retire.test.ts`, `tests/guards/automation-legacy-fixture.test.ts`, `backend/domains/automations/legacy-agent-flow.integration.ts`, `tests/guards/automation-legacy-agent-flow.test.ts` (complete released start/resume bodies and actual old run/ask SQL; external ports record requested effects only); already-admitted effects are not asserted undone, and requested token expiry does not prove gateway-key retirement | | [automations](../../suites/automations.md) | Five logical execution jobs use one protocol-to-physical queue mapping. Independent old/new workers cannot consume each other's execution jobs; enqueue, get/cancel, handover, recovery and drain keep their existing budgets and truthful legacy census. | ✅ unit + real PostgreSQL | `backend/jobs/automation-protocol.test.ts`, `backend/jobs/automation-protocol.integration.ts`, `backend/domains/control/service.test.ts`, `backend/domains/sandbox/recovery.test.ts`; the native helpers run before ordinary workers | | [automations](../../suites/automations.md) | Public run API projects safe legacy hold facts in organization and project scopes; stop requests require the exact hold identity and acknowledgement, authenticated actor and existing write authority; stale and wrong-scope requests refuse without releasing the hold | 🔶 REST contract and OpenAPI tests; native stop and migration outcomes remain separate integration proofs | `backend/rest/v1-automations.contract.test.ts`, `backend/rest/v1-automations.project-scope.test.ts`, `scripts/openapi/spec.test.ts` | +| [automations](../../suites/automations.md) | Managed protocol cutover accepts the uniquely validated released public or retained tale migration ledger with the exact legacy source hash, refuses shadow ledgers, and holds a source-bound all-organization zero census while stopping exact legacy backend writers; competing admissions block, existing uncommitted admissions refuse acquisition, lock loss prevents startup, and interrupted retries require fresh identity and census checks. Existing tag deployments cannot bypass this barrier. | ✅ CLI + real Postgres | `backend/jobs/automation-floor.integration.ts` (required Backend integration; the actual shared CLI lock/census SQL), `tools/cli/src/lib/deployment/automation-cutover.test.ts`, `automation-protocol.test.ts`, `automation-session.test.ts` (real pipe backpressure, output bound and private error refusal), `automation-cutover.integration.test.ts` (opt in with `TALE_CUTOVER_PG_IMAGE=sha256:`; owns one disposable tmpfs container without ports or pulls); physical released backend shutdown and the complete deployed cutover remain release acceptance checks. Historical external effects and independent agent sessions are outside this guarantee. | diff --git a/services/platform/tests/manual/reference/automation/chat.md b/services/platform/tests/manual/reference/automation/chat.md index 87dd4d5e83..34b5245347 100644 --- a/services/platform/tests/manual/reference/automation/chat.md +++ b/services/platform/tests/manual/reference/automation/chat.md @@ -6,3 +6,4 @@ Rows for [`chat`](../../suites/chat.md) boxes that moved out of the suite. Read | Suite | Automated slice | Coverage | Specs | | --- | --- | --- | --- | | [chat](../../suites/chat.md) | Attachment permissions are checked before parking and before rebuilding history or regenerating a turn; preflight failures retain text only, metadata uses the current organization and reader, and denied document reads do not queue indexing. Real PostgreSQL probes cover same-organization and cross-organization audio denial through captured model requests, with an allowed own-audio control. | ✅ unit + real PostgreSQL | `backend/domains/chat/attachment-privacy.test.ts`, `deferred-sends.test.ts` and the `checkChatDeferredAuto` lane in `backend/integration-check.ts`; existing REST and arena suites cover surrounding caller contracts; door-level privacy execution remains separate | +| [chat](../../suites/chat.md) / [governance](../../suites/governance.md) | Moving a hidden branch ends the root's project share; a destination member can read it only after a fresh explicit share. Erasure retires existing automation runs before deleting settled model requests or pseudonymizing pending ones, so late direct-model settlement books once under the erased subject and the retired run cannot admit another call. A failed or held-off prerequisite leaves a Partial receipt. | 🔶 unit + real PostgreSQL | `backend/domains/chat/threads.test.ts`, `backend/domains/erasure/service.lifecycle.test.ts`, and the sharing/erasure cases in `backend/domains/governance/project-budget.integration.ts`; rendered sharing controls and production erasure remain separate observations. | diff --git a/services/platform/tests/manual/reference/automation/settings.md b/services/platform/tests/manual/reference/automation/settings.md index d0f7e4dd07..d3a84417c0 100644 --- a/services/platform/tests/manual/reference/automation/settings.md +++ b/services/platform/tests/manual/reference/automation/settings.md @@ -7,3 +7,7 @@ Rows for [`settings`](../../suites/settings.md) boxes that moved out of the suit | --- | --- | --- | --- | | [settings](../../suites/settings.md) / [tasks](../../suites/tasks.md) | Sandbox CPU growth: cleanup matches retained executions through one set of per-round process indexes, preserving group and descendant ownership; failed runnerd output readers cancel and unlock before repeated attaches can accumulate producers; settings views visit each historical operation once and project only displayed operation details, with bounded progress tails and unchanged spend, running order and task ownership | 🔶 unit + real Postgres | `services/sandbox-runtime/daemon/src/process-reaper.test.ts`, `services/sandbox/src/session/runnerd-client.test.ts`, `backend/domains/sandbox/sessions.views.test.ts`, `checkSandboxSettingsViews` in `backend:integration`; sustained deployment CPU under real agent workloads remains an operator measurement | | [settings](../../suites/settings.md) | Docker filesystem observation verifies the read-only data-root mount; inherited startup cancellation bounds cleanup; optional mounts and backend agent settings reach generated Compose | ✅ automated | `services/sandbox/src/docker-data-disk.test.ts`, `services/sandbox/src/spawn-util.test.ts`, `tools/cli/src/lib/compose/services/create-sandbox-service.test.ts`, `tools/cli/src/lib/compose/services/compose-parity.test.ts`; actual hard disk quotas remain storage-backend dependent | +| [settings](../../suites/settings.md) | Managed Git acquisition reports finite source kind, stage, validated exit status and redacted disk/DNS/timeout/output hints; unknown private stderr stays hidden, each command is bounded, runtime acquisition never uses the client key, and failures remove only owned temporary files without retrying | ✅ CLI unit + local subprocess | `tools/cli/src/lib/deployment/sources.test.ts`, `inputs.test.ts`, `tools/cli/src/commands/operational-failure.test.ts`, `tools/cli/src/lib/docker/bounded-output.test.ts`; actual runner network and disk remain deployment diagnostics | +| [settings](../../suites/settings.md) | Public deployment-control paths are refused by the proxy while the CLI keeps its authenticated in-container channel | ✅ automated | `tests/integration/container-smoke-test.ts` (root, descendants, query and encoded path through the real proxy), `tools/cli/src/lib/compose/services/compose-parity.test.ts`, `tools/cli/src/lib/docker/control-call.test.ts` | +| [settings](../../suites/settings.md) / [chat](../../suites/chat.md) | `APIKEY-R6`: the real chat executor and sandbox dispatcher compose with the central SQL shim gates; a project API key cannot search or list organization-wide knowledge entries, and the low-level entry reader is never called. Its project document search/list remains scoped and available; member, team-owned and organization-owned keys retain entry reads. | ✅ composed backend unit | `backend/domains/chat/shim.knowledge-scope.test.ts` | +| [settings](../../suites/settings.md) / [chat](../../suites/chat.md) / [automations](../../suites/automations.md) | Shared admission counts pending voice and direct automation model reservations; captured projects survive chat movement and installation changes, including an explicitly empty project list. Exact attempts settle once; failed or unknown voice and direct-model outcomes retain a conservative estimate before retry. Pending voice cleanup defers to its watchdog, while authorized erasure remains unchanged. | 🔶 unit + real PostgreSQL | `backend/domains/governance/immutable-projects.integration.ts`, `backend/domains/tts/budget.integration.ts`, `backend/domains/governance/project-budget.integration.ts` (`checkImmutableBudgetProjects`, `checkTtsBudgetReservations`, `checkProjectBudgets` in `backend:integration`); corresponding chat, sandbox, voice and automation unit suites cover refusal and settlement. Provider charges, historical usage completeness and production throughput remain separate observations. | diff --git a/services/platform/tests/manual/reference/error-codes.md b/services/platform/tests/manual/reference/error-codes.md index 2885e312e8..163ef324db 100644 --- a/services/platform/tests/manual/reference/error-codes.md +++ b/services/platform/tests/manual/reference/error-codes.md @@ -30,6 +30,7 @@ provokes it and the recovery the surface offers. | Deleted automation (`automations.detail.deleted.banner`, backend `AUTOMATION_DELETED` 404 with `data.deletedAt`) | Delete an automation that has runs, then open one of its run URLs (AUTO-F49). The app door `GET /api/app/automations/{name}` answers the tombstone's date; the Runs pages render under the banner. Not answered on REST v1, whose `GET /automations/{name}` keeps `AUTOMATION_NOT_FOUND`. | | Missing automation version (`automations.editor.versionNotFound.title`, backend `AUTOMATION_VERSION_UNKNOWN` 404 with `data.latestVersion`) | Open an existing automation's editor with `?version=99` (a number it never saved). The editor keeps the automation's tabs and shows "Version 99 doesn't exist" with **Open latest**; an unknown slug still answers the plain `automation not found` 404 and the automation-level empty state. | | Organization delete without its name (`settings.organization.deleteConfirmNameMismatch`, backend `ORG_CONFIRM_NAME_MISMATCH` 400) | `POST /api/app/organizations/{id}/delete` with no `confirmName`, or one that is not the organization's name (trimmed, case-insensitive). The UI never sends it: the **Delete organization** confirm keeps its button disabled until the name is typed exactly. Nothing is written; the hold gate is not even reached. | +| Organization delete preserves unresolved automation holds (`settings.organization.deleteBlockedByLegacyAutomation`, backend `ORG_LEGACY_AUTOMATION_HELD` 409) | In an isolated upgrade fixture, preserve an active pre-protocol automation run through migration 0163. As an owner, send `POST /api/app/organizations/{id}/delete` with the correct `confirmName`. The organization is preserved before audit or cleanup work starts. A stop request leaves this refusal in place; there is currently no hold-release action. | | Team name taken (`settings.teams.teamNameTaken`, backend `TEAM_NAME_TAKEN` 409) | In Settings > Teams, create a team whose name another team of the organization already reads as — `finance ` beside `Finance` — or rename one onto such a name via **Edit**. The sentence sits under **Team name**, the dialog stays open and nothing is written; re-saving a team's own name (in any case) goes through. SCIM answers the same rule as a 409 `uniqueness` on a Group's `displayName`. | | Archived project refuses a write (`projects.errors.PROJECT_ARCHIVED`, `tasks.errors.PROJECT_ARCHIVED`, backend `PROJECT_ARCHIVED` 403) | Archive a project on **General**, then race a write against it: keep a second tab open on its Agents tab from before the archive and submit **New agent**, or **Create task** from a stale board, or drop a file on its stale Files tab — or delete / detach one of its files, comment on one of its tasks, save a secret on its stale Secrets tab, or bind it to an automation / start a run in it. The toast names the archived project; the fresh page hides every write control and shows the **This project is archived** banner; the banner carries no action — **Restore** (`projects.rowActions.restore`) is on **General** for admins. | | Folder rename in a synced tree refused (`documents.folder.renameSyncManaged`, backend `FOLDER_SYNC_MANAGED` 409) | The row menu offers no **Rename** for a folder at, inside or above a synced folder. To reach the refusal, open **Rename** on a parent folder, start syncing a folder below it from another tab, then submit. The dialog keeps the name and names the rule on the field; nothing is renamed. | diff --git a/services/platform/turbo.json b/services/platform/turbo.json index 4d05e5c6dd..32328485c2 100644 --- a/services/platform/turbo.json +++ b/services/platform/turbo.json @@ -12,6 +12,7 @@ "$TURBO_ROOT$/services/sandbox-runtime/daemon/src/file-ops.ts", "$TURBO_ROOT$/services/sandbox-runtime/daemon/src/protocol.ts", "$TURBO_ROOT$/tools/cli/src/lib/deployment/automation-floor.ts", + "$TURBO_ROOT$/tools/cli/src/lib/deployment/automation-cutover-sql.ts", "$TURBO_ROOT$/tools/cli/src/lib/deployment/automation-model.ts", "$TURBO_ROOT$/tools/cli/src/lib/deployment/migration-model.ts" ] @@ -51,6 +52,7 @@ "$TURBO_ROOT$/services/sandbox/src/config.ts", "$TURBO_ROOT$/.github/ci-scope.yml", "$TURBO_ROOT$/tools/cli/src/lib/deployment/automation-floor.ts", + "$TURBO_ROOT$/tools/cli/src/lib/deployment/automation-cutover-sql.ts", "$TURBO_ROOT$/tools/cli/src/lib/deployment/automation-model.ts", "$TURBO_ROOT$/tools/cli/src/lib/deployment/migration-model.ts" ] @@ -199,6 +201,7 @@ "$TURBO_ROOT$/services/sandbox-runtime/daemon/src/file-ops.ts", "$TURBO_ROOT$/services/sandbox-runtime/daemon/src/protocol.ts", "$TURBO_ROOT$/tools/cli/src/lib/deployment/automation-floor.ts", + "$TURBO_ROOT$/tools/cli/src/lib/deployment/automation-cutover-sql.ts", "$TURBO_ROOT$/tools/cli/src/lib/deployment/automation-model.ts", "$TURBO_ROOT$/tools/cli/src/lib/deployment/migration-model.ts" ] diff --git a/services/proxy/docker-entrypoint.sh b/services/proxy/docker-entrypoint.sh index a66e347dc8..544796513e 100644 --- a/services/proxy/docker-entrypoint.sh +++ b/services/proxy/docker-entrypoint.sh @@ -245,8 +245,8 @@ sed -i "s|{[\$]DOCS_ORIGIN:[^}]*}|${DOCS_URL}|" "$CADDYFILE" # Everything the pg backend owns is listed here explicitly — auth, the app # API, the hint stream, both machine doors, SSO/SCIM/trusted-headers on BOTH # their 0.5-native and 0.4 `/http_api/...` paths (registered IdP redirect -# URIs carry the old ones), the control channel the CLI drains through, the -# cloud-import OAuth callbacks and the WebDAV protocol door. +# URIs carry the old ones), the cloud-import OAuth callbacks and the WebDAV +# protocol door. Deployment control stays internal to the backend container. # # BACKEND_UPSTREAM began life as the cutover's reversibility switch (unset ⇒ # lanes fall back to Convex). The Convex runtime is gone, so an unset value @@ -338,8 +338,14 @@ BACKEND_BLOCK=$(cat <): Promise { } describe('per-organization cache volumes', () => { + test.each([false, true])( + 'permission setup executes an immutable helper for an in-use cache: %s', + async (inUse) => { + const name = npmCacheVolumeName(cfg, nextOrg()); + if (inUse) await plantUnlabelled(name, true); + const warn = spyOn(console, 'warn').mockImplementation(() => {}); + try { + await ensureCacheVolume(name); + const runs = (await calls()).filter((call) => call.startsWith('run ')); + expect(runs).toHaveLength(1); + expect(runs[0]?.split(' ')[8]).toMatch( + /^busybox:[^\s@]+@sha256:[a-f0-9]{64}$/, + ); + expect(await volume(name)).toEqual({ + labelled: !inUse, + mode: '1777', + }); + } finally { + warn.mockRestore(); + } + }, + ); + + test('Renovate discovers the one production helper pin', async () => { + const managers = renovate.customManagers.filter((manager) => + manager.managerFilePatterns.includes( + '/^services/sandbox/src/volume\\.ts$/', + ), + ); + expect(managers).toHaveLength(1); + const manager = managers[0]; + if (manager === undefined) throw new Error('Cache helper updater missing'); + expect(manager.datasourceTemplate).toBe('docker'); + expect(manager.versioningTemplate).toBe('docker'); + const source = await readFile( + new URL('./volume.ts', import.meta.url), + 'utf8', + ); + const matches = manager.matchStrings.flatMap((pattern) => + Array.from(source.matchAll(new RegExp(pattern, 'g'))), + ); + expect(matches).toHaveLength(1); + expect(matches[0]?.groups).toEqual({ + depName: 'busybox', + currentValue: expect.stringMatching(/^\d+\.\d+(?:\.\d+)?$/), + currentDigest: expect.stringMatching(/^sha256:[a-f0-9]{64}$/), + }); + }); + test('a volume made ready is not asked about again on the next create', async () => { const name = npmCacheVolumeName(cfg, nextOrg()); const now = 1_000_000; @@ -290,7 +340,11 @@ describe('a cache volume Docker made itself', () => { inspectCall(name), `volume rm ${name}`, `volume create --label tale.sandbox-cache=1 ${name}`, - `run --rm --user 0:0 --label tale.sandbox-staging=1 --mount type=volume,src=${name},dst=/cache busybox:1.36 chmod 1777 /cache`, + expect.stringMatching( + new RegExp( + `^run --rm --user 0:0 --label tale\\.sandbox-staging=1 --mount type=volume,src=${name},dst=/cache busybox:[^\\s@]+@sha256:[a-f0-9]{64} chmod 1777 /cache$`, + ), + ), ]); // Labelled, it is the organization's again: its teardown removes it. expect(await removeCacheVolumes(cfg, org)).toBe(1); diff --git a/services/sandbox/src/volume.ts b/services/sandbox/src/volume.ts index 10de02b0e5..7680c0fefa 100644 --- a/services/sandbox/src/volume.ts +++ b/services/sandbox/src/volume.ts @@ -41,6 +41,10 @@ export function bunCacheVolumeName( } const CACHE_LABEL = 'tale.sandbox-cache'; +/** Multi-architecture index: root cache setup must not execute a mutable tag. + * The scoped Renovate manager keeps this tag and digest together. */ +const CACHE_PERMISSION_IMAGE = + 'busybox:1.36@sha256:73aaf090f3d85aa34ee199857f03fa3a95c8ede2ffd4cc2cdb5b94e566b11662'; /** Whether a volume under a cache name is missing, the spawner's (it carries * the cache label), or one the spawner did not make: Docker creates a volume @@ -274,7 +278,7 @@ async function setCacheVolumeMode(name: string): Promise { 'tale.sandbox-staging=1', '--mount', `type=volume,src=${name},dst=/cache`, - 'busybox:1.36', + CACHE_PERMISSION_IMAGE, 'chmod', '1777', '/cache', diff --git a/tools/cli/README.md b/tools/cli/README.md index 8e903e7194..1117c3bda7 100644 --- a/tools/cli/README.md +++ b/tools/cli/README.md @@ -94,9 +94,7 @@ it with the corresponding platform version and encryption secrets. `tale update` changes the CLI and project files, staying in the current `x.y` line unless you select another version. `tale deploy` rolls application containers; `--stop` also permits stop-gated updates with downtime. Blue-green rollout does not -make every operation downtime-free. After the rollout it removes Tale's -images of versions older than the new version and the rollback target, leaving any -image a container still uses. +make every operation downtime-free. `tale rollback` is limited to a recorded compatible patch version. Recovery across minor or major migrations uses a snapshot and its matching version; see the @@ -126,6 +124,14 @@ Preparation checks configurations before it pulls runtime images. It refuses a pack that declares fields this CLI does not know and names those fields, so pin a CLI at least as new as the Tale your packs target. +Git acquisition failures identify the runtime or configuration source, the Git +stage and its exit status when available. The fixed failure hint distinguishes +disk space, name resolution, timeout and output-limit failures; `unknown` retains +no unrecognized Git text. Hints narrow the investigation without proving a cause. +Check the preparation runner at the reported stage before retrying. Each Git +command has a five-minute deadline and a 1 MiB combined output limit; diagnostics +omit repository URLs, local paths, credentials and raw Git output. + ```bash tale deploy prepare --spec "$TALE_DEPLOY_SPEC" --output "$TALE_DEPLOY_BUNDLE" --json tale deploy verify-bundle --bundle "$TALE_DEPLOY_BUNDLE" --cli-ref "$TALE_CLI_COMMIT" --json @@ -138,6 +144,33 @@ bundle commands require POSIX custody checks and are unavailable on Windows. Retain the bundle, source pins and receipts together. Serialize competing deployments externally: a local lock does not coordinate separate hosts. +The protocol-1 to protocol-2 automation upgrade uses a bounded admission barrier +for the bundled database and the verified `b4931db4` legacy runtime. It requires +the complete legacy migration inventory in one validated `public` or `tale` +ledger and zero unfinished automation runs across every organization. A second +or malformed ledger refuses admission. A held database lock blocks new legacy admissions and +claims while the CLI gracefully stops every recorded backend API and worker +container. The CLI observes those exact containers exited before releasing the +lock; the new images install their protocol fence before serving requests or +starting workers. Busy or unsupported sources and database layouts refuse the +upgrade before any backend stop. Existing protocol-1 tag deployments must use +this managed upgrade first; fresh installations and compatible later deployments +do not need the legacy barrier. + +If the lock connection drops, a stop times out, or identities change, the CLI +leaves the runtime pending and starts no new containers. Keep the bundle and +`.tale/automation-cutover.json` receipt, then retry the same managed deployment. +Before another legacy handoff, the retry verifies the recorded identities and +takes a fresh locked census. If Compose already created some target containers, +it can resume only with every retained old writer still exactly stopped, each +replacement on the prepared target image, complete backend roles and the same +database incarnation. Unknown identities or missing roles require reconciliation +of the pending deployment. Elapsed time never authorizes a retry. The CLI does not +force-kill or automatically restart old writers. Do not run an older CLI or +manually restart containers during this transition. Terminal legacy runs may +still have historical external effects; this barrier does not claim those +effects have retired or cancel independent project agents. + After a completed rollout, `tale --json deploy accept --bundle "$TALE_DEPLOY_BUNDLE" --cli-ref "$TALE_CLI_COMMIT" --deployment-ref "$DEPLOYMENT_COMMIT" --expected-version "$TALE_RELEASE_VERSION"` collects current read-only acceptance. diff --git a/tools/cli/src/lib/actions/deploy.ts b/tools/cli/src/lib/actions/deploy.ts index 1f26534404..5b5ff1de12 100644 --- a/tools/cli/src/lib/actions/deploy.ts +++ b/tools/cli/src/lib/actions/deploy.ts @@ -42,7 +42,6 @@ import { getContainerVersion } from '../docker/get-container-version'; import { isContainerRunning } from '../docker/is-container-running'; import { composeCreatedContainerFilters } from '../docker/list-service-containers'; import { migrateConfigVolume } from '../docker/migrate-config-volume'; -import { pruneSupersededImages } from '../docker/prune-superseded-images'; import { pullImage } from '../docker/pull-image'; import { waitForHealthy } from '../docker/wait-for-healthy'; import { waitForServiceHealthy } from '../docker/wait-for-service-healthy'; @@ -54,7 +53,6 @@ import { } from '../state/flip-pending'; import { getCurrentColor } from '../state/get-current-color'; import { getNextColor } from '../state/get-next-color'; -import { getPreviousVersion } from '../state/get-previous-version'; import { setCurrentColor } from '../state/set-current-color'; import { setPreviousVersion } from '../state/set-previous-version'; import { withLock } from '../state/with-lock'; @@ -841,15 +839,6 @@ export async function deploy(options: DeployOptions): Promise { }); } - // Each deploy pulls its images by version tag, so the versions it - // replaced keep their tags and stay on the host until removed here. The - // live version and the rollback target stay. - await pruneSupersededImages( - env.GHCR_REGISTRY, - [version, await getPreviousVersion(env.DEPLOY_DIR)], - { dryRun }, - ); - if (!dryRun) { logger.success(`Deployment complete! Version ${version} is now live`); } diff --git a/tools/cli/src/lib/compose/services/compose-parity.test.ts b/tools/cli/src/lib/compose/services/compose-parity.test.ts index fc8e2465c2..90ea7b3260 100644 --- a/tools/cli/src/lib/compose/services/compose-parity.test.ts +++ b/tools/cli/src/lib/compose/services/compose-parity.test.ts @@ -571,6 +571,25 @@ describe('blob-backend parity (the deployment cannot accept an upload without it expect(entrypoint).not.toContain('-n "${BACKEND_UPSTREAM'); }); + test('public control paths are refused before the generic API fallback', () => { + const entrypoint = readFileSync( + resolve(repoRoot, 'services/proxy/docker-entrypoint.sh'), + 'utf8', + ); + for (const path of ['/api/control', '/api/control/*']) { + const handle = entrypoint.split(`handle ${path} {`)[1]?.split('\n\t}')[0]; + expect(handle).toBeDefined(); + expect(handle).toContain('respond "Not found" 404'); + expect(handle).not.toContain('reverse_proxy'); + } + // Removing the explicit control route alone leaves /api/* forwarding it. + const caddyfile = readFileSync( + resolve(repoRoot, 'services/proxy/Caddyfile'), + 'utf8', + ); + expect(caddyfile).toContain('handle /api/* {'); + }); + test('nothing routes to the retired runtime any more', () => { // The proxy used to fall back to `convex:*` for everything the backend // list did not name. That service is gone, so a fallback is a 502 — every diff --git a/tools/cli/src/lib/config/platform-docs.test.ts b/tools/cli/src/lib/config/platform-docs.test.ts index 6e37805c35..aaa1cbf7a0 100644 --- a/tools/cli/src/lib/config/platform-docs.test.ts +++ b/tools/cli/src/lib/config/platform-docs.test.ts @@ -4,7 +4,9 @@ import { tmpdir } from 'node:os'; import { relative, resolve, sep } from 'node:path'; import { fileURLToPath } from 'node:url'; +import picomatch from 'picomatch'; import ts from 'typescript'; +import { parse } from 'yaml'; import { z } from 'zod'; import { deploymentSpecSchema } from '../deployment/model'; @@ -381,6 +383,39 @@ test('turbo re-runs the suites when an install page or another outside file they expect(unhashed).toEqual([]); }); +test('native CLI scopes cover every imported platform backend module', () => { + const graph = cliModuleGraph(); + expect(graph.unresolved).toEqual([]); + const filters = z + .object({ cli: z.array(z.string()).min(1) }) + .parse( + parse(readFileSync(resolve(REPO_ROOT, '.github/ci-scope.yml'), 'utf8')), + ); + const workflow = z + .object({ + on: z.object({ push: z.object({ paths: z.array(z.string()).min(1) }) }), + }) + .parse( + parse( + readFileSync(resolve(REPO_ROOT, '.github/workflows/cli.yml'), 'utf8'), + ), + ); + const backend = [...graph.files] + .map((file) => relative(REPO_ROOT, file).split(sep).join('/')) + .filter((file) => file.startsWith('services/platform/backend/')); + expect(backend.length).toBeGreaterThan(20); + for (const [name, patterns] of [ + ['PR', filters.cli], + ['push', workflow.on.push.paths], + ] as const) { + const matches = picomatch(patterns, { dot: true }); + expect( + backend.filter((file) => !matches(file)).sort(), + `${name}: imported backend changes must run native CLI validation`, + ).toEqual([]); + } +}); + test('cached CLI checks hash every imported module and generated source tree', () => { const graph = cliModuleGraph(); expect(graph.unresolved).toEqual([]); diff --git a/tools/cli/src/lib/deployment/acceptance-migrations.ts b/tools/cli/src/lib/deployment/acceptance-migrations.ts index fb29ea4932..5693764a8a 100644 --- a/tools/cli/src/lib/deployment/acceptance-migrations.ts +++ b/tools/cli/src/lib/deployment/acceptance-migrations.ts @@ -38,6 +38,16 @@ export function acceptanceMigrationScript( export function migrationReadScript( service: 'db' | 'knowledge-db', sql: string, +): string { + return `${migrationSessionCommand(service)} <<'TALE_ACCEPTANCE_SQL' +${sql} +TALE_ACCEPTANCE_SQL +`; +} + +/** A held cutover transaction uses the same local credential boundary. */ +export function migrationSessionCommand( + service: 'db' | 'knowledge-db', ): string { const database = service === 'db' ? 'tale_app' : 'tale_knowledge'; return `set -eu @@ -45,10 +55,7 @@ user="\${DB_USER:-\${POSTGRES_USER:-}}" case "$user" in ''|*[!a-zA-Z0-9_]*) exit 1;; esac unset PGHOST PGHOSTADDR PGSERVICE PGSERVICEFILE PGDATABASE PGUSER PGOPTIONS PGPASSFILE export PGCONNECT_TIMEOUT=5 -exec psql -X -q -A -t -v ON_ERROR_STOP=1 -h /var/run/postgresql -U "$user" -d ${database} <<'TALE_ACCEPTANCE_SQL' -${sql} -TALE_ACCEPTANCE_SQL -`; +exec psql -X -q -A -t -v ON_ERROR_STOP=1 -h /var/run/postgresql -U "$user" -d ${database}`; } export function acceptedMigrations( expected: MigrationInventory, diff --git a/tools/cli/src/lib/deployment/automation-cutover-sql.ts b/tools/cli/src/lib/deployment/automation-cutover-sql.ts new file mode 100644 index 0000000000..fd6995bbc7 --- /dev/null +++ b/tools/cli/src/lib/deployment/automation-cutover-sql.ts @@ -0,0 +1,67 @@ +import { createHash } from 'node:crypto'; + +import { z } from 'zod'; + +import { AUTOMATION_LEDGER_QUERY } from './automation-floor'; + +export const LEGACY_CUTOVER_LEDGER_SHA256 = + '1fda736a1123667df24f63c3d78f2e0048491ebc4b8482293f6046ac3253e324'; +export const AUTOMATION_CUTOVER_ISOLATION = 'isolation level read committed'; +export const AUTOMATION_CUTOVER_SESSION_SQL = `SET LOCAL statement_timeout = '5s'; +SET LOCAL lock_timeout = '1s'; +SET LOCAL idle_in_transaction_session_timeout = '10s';`; +// An existing uncommitted writer refuses acquisition. After acquisition, +// READ COMMITTED sees all committed runs while SHARE excludes new admissions. +export const AUTOMATION_CUTOVER_LOCK_SQL = + 'LOCK TABLE app.automation_runs IN SHARE MODE NOWAIT;'; +export const AUTOMATION_CUTOVER_CENSUS_SQL = `SELECT json_build_object( + 'safeTable', EXISTS (SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'app' AND c.relname = 'automation_runs' AND c.relkind = 'r' AND NOT c.relrowsecurity AND NOT c.relforcerowsecurity), + 'unfinished', EXISTS (SELECT 1 FROM app.automation_runs WHERE status NOT IN ('success', 'failed', 'cancelled') OR status IS NULL), + 'owned', EXISTS (SELECT 1 FROM pg_catalog.pg_locks WHERE pid = pg_backend_pid() + AND relation = 'app.automation_runs'::regclass AND mode = 'ShareLock' AND granted));`; +export const AUTOMATION_CUTOVER_PROBE_SQL = `SELECT json_build_object('owned', EXISTS ( + SELECT 1 FROM pg_catalog.pg_locks WHERE pid = pg_backend_pid() + AND relation = 'app.automation_runs'::regclass AND mode = 'ShareLock' AND granted));`; + +/** The CLI psql transport and the required backend integration use these same + * source-owned statements; no user value becomes executable SQL. */ +export const AUTOMATION_CUTOVER_ACQUIRE_SQL = `BEGIN ${AUTOMATION_CUTOVER_ISOLATION}; +${AUTOMATION_CUTOVER_SESSION_SQL} +${AUTOMATION_CUTOVER_LOCK_SQL} +${AUTOMATION_LEDGER_QUERY.slice(0, -1)} +\\gexec +${AUTOMATION_CUTOVER_CENSUS_SQL}`; + +export function emptyLegacyCutoverCensus(raw: string): boolean { + try { + const lines = raw.trim().split('\n'); + if (lines.length !== 2) return false; + const ledger = z + .strictObject({ + schema: z.enum(['public', 'tale']), + ids: z.array(z.string()).max(2048), + }) + .parse(JSON.parse(lines[0])); + z.strictObject({ + safeTable: z.literal(true), + unfinished: z.literal(false), + owned: z.literal(true), + }).parse(JSON.parse(lines[1])); + return ( + createHash('sha256').update(JSON.stringify(ledger.ids)).digest('hex') === + LEGACY_CUTOVER_LEDGER_SHA256 + ); + } catch { + return false; + } +} + +export function cutoverLockOwned(raw: string): boolean { + try { + return z.strictObject({ owned: z.literal(true) }).parse(JSON.parse(raw)) + .owned; + } catch { + return false; + } +} diff --git a/tools/cli/src/lib/deployment/automation-cutover.integration.test.ts b/tools/cli/src/lib/deployment/automation-cutover.integration.test.ts new file mode 100644 index 0000000000..660c6f3f85 --- /dev/null +++ b/tools/cli/src/lib/deployment/automation-cutover.integration.test.ts @@ -0,0 +1,202 @@ +import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; +import { randomBytes, randomUUID } from 'node:crypto'; +import { readdirSync } from 'node:fs'; + +import { exec } from '../docker/exec'; +import { migrationSessionCommand } from './acceptance-migrations'; +import { + AUTOMATION_CUTOVER_ACQUIRE_SQL, + AUTOMATION_CUTOVER_PROBE_SQL, + requireEmptyLegacyCensus, +} from './automation-cutover'; +import { automationSession } from './automation-session'; +import { runtimeProcessEnvironment } from './runtime-command'; + +// Opt in with a local immutable tale-db image; no pull/build, persistent volume, +// published port or pre-existing container is used. This tests the real session +// and PostgreSQL lock, not the provenance of a newly built candidate image. +const image = process.env.TALE_CUTOVER_PG_IMAGE; +const integration = describe.skipIf(!image); +let container = ''; +const command = async ( + args: string[], + stdin?: string, + env?: Record, +) => { + const result = await exec('docker', args, { + silent: true, + timeout: 60, + maxOutputBytes: 1_048_576, + env: env ?? runtimeProcessEnvironment(), + ...(stdin === undefined ? {} : { stdin }), + }); + if (!result.success) throw new Error('Owned cutover fixture command failed.'); + return result.stdout; +}; + +integration('physical PostgreSQL automation cutover admission barrier', () => { + beforeAll(async () => { + if (!image || !/^sha256:[a-f0-9]{64}$/.test(image)) + throw new Error('Use an existing immutable local DB image ID.'); + container = await command( + [ + 'run', + '-d', + '--pull', + 'never', + '--name', + `tale-cutover-test-${randomUUID()}`, + '--label', + 'dev.tale.test=automation-cutover', + '--memory', + '1g', + '--cpus', + '2', + '--shm-size', + '128m', + '--tmpfs', + '/var/lib/postgresql/data:rw,size=1g', + '-e', + 'DB_PASSWORD', + '-e', + 'DB_USER=tale', + '-e', + 'DB_NAME=tale', + '-e', + 'TALE_DB_ROLE=platform', + '-e', + 'DB_SHARED_BUFFERS=128MB', + '-e', + 'DB_WORK_MEM=8MB', + '-e', + 'DB_MAINTENANCE_WORK_MEM=64MB', + image, + ], + undefined, + { + ...runtimeProcessEnvironment(), + DB_PASSWORD: randomBytes(24).toString('hex'), + }, + ); + if (!/^[a-f0-9]{64}$/.test(container)) + throw new Error('Owned fixture identity missing.'); + let ready = false; + for (let attempt = 0; attempt < 90; attempt++) { + try { + await command([ + 'exec', + container, + 'sh', + '-c', + 'test -f /tmp/.db_ready && pg_isready -U tale -d tale_app >/dev/null', + ]); + ready = true; + break; + } catch { + await Bun.sleep(500); + } + } + if (!ready) + throw new Error('Owned PostgreSQL fixture did not become ready.'); + const ids = readdirSync( + new URL( + '../../../../../services/platform/backend/db/migrations/', + import.meta.url, + ), + ) + .filter( + (name) => + /^\d{4}_[a-z0-9_]+\.(sql|ts)$/.test(name) && + Number(name.slice(0, 4)) <= 153, + ) + .sort(); + await command( + ['exec', '-i', container, 'sh', '-c', migrationSessionCommand('db')], + `CREATE SCHEMA app; +CREATE TABLE public.app_migrations (name text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now()); +CREATE TABLE app.automation_runs (id text PRIMARY KEY, org_id text NOT NULL, status text NOT NULL); +COPY public.app_migrations(name) FROM STDIN; +${ids.join('\n')} +\\. +`, + ); + }, 90_000); + afterAll(async () => { + if (/^[a-f0-9]{64}$/.test(container)) + await command(['rm', '-f', container]); + }, 15_000); + + test('a held zero prevents a competing admission; release permits it again', async () => { + const held = await automationSession(container); + const writer = await automationSession(container); + try { + requireEmptyLegacyCensus( + await held.query(AUTOMATION_CUTOVER_ACQUIRE_SQL), + ); + await expect( + writer.query( + "SET statement_timeout = '300ms'; INSERT INTO app.automation_runs VALUES ('competing', 'other-org', 'queued');", + ), + ).rejects.toThrow('lock session'); + expect( + JSON.parse(await held.query(AUTOMATION_CUTOVER_PROBE_SQL)), + ).toEqual({ owned: true }); + } finally { + await writer.close(); + await held.close(); + } + const next = await automationSession(container); + try { + await next.query( + "INSERT INTO app.automation_runs VALUES ('after-release', 'other-org', 'queued');", + ); + expect( + await next.query( + "SELECT count(*) FROM app.automation_runs WHERE id = 'after-release';", + ), + ).toBe('1'); + await next.query( + "DELETE FROM app.automation_runs WHERE id = 'after-release';", + ); + } finally { + await next.close(); + } + }); + + test('an uncommitted old admission refuses acquisition instead of manufacturing zero', async () => { + const writer = await automationSession(container); + const held = await automationSession(container); + try { + await writer.query( + "BEGIN; INSERT INTO app.automation_runs VALUES ('uncommitted', 'other-org', 'queued');", + ); + await expect(held.query(AUTOMATION_CUTOVER_ACQUIRE_SQL)).rejects.toThrow( + 'lock session', + ); + expect(held.healthy()).toBe(false); + } finally { + await held.close(); + await writer.close(); + } + }); + + test('server-side session loss revokes lock ownership and refuses further operations', async () => { + const held = await automationSession(container); + const killer = await automationSession(container); + try { + requireEmptyLegacyCensus( + await held.query(AUTOMATION_CUTOVER_ACQUIRE_SQL), + ); + await killer.query( + "SELECT pg_terminate_backend(pid) FROM pg_catalog.pg_locks WHERE relation = 'app.automation_runs'::regclass AND mode = 'ShareLock' AND granted;", + ); + await expect(held.query(AUTOMATION_CUTOVER_PROBE_SQL)).rejects.toThrow( + 'lock session', + ); + expect(held.healthy()).toBe(false); + } finally { + await held.close(); + await killer.close(); + } + }); +}); diff --git a/tools/cli/src/lib/deployment/automation-cutover.test.ts b/tools/cli/src/lib/deployment/automation-cutover.test.ts new file mode 100644 index 0000000000..c3c4660836 --- /dev/null +++ b/tools/cli/src/lib/deployment/automation-cutover.test.ts @@ -0,0 +1,436 @@ +import { afterEach, expect, spyOn, test } from 'bun:test'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import * as logger from '../../utils/logger'; +import { + AUTOMATION_CUTOVER_ACQUIRE_SQL, + AUTOMATION_CUTOVER_PROBE_SQL, + cutoverLegacyAutomation, + LEGACY_CUTOVER_LEDGER_SHA256, + LEGACY_CUTOVER_REVISION, + requireEmptyLegacyCensus, +} from './automation-cutover'; +import { AUTOMATION_PROTOCOL_LABEL } from './automation-model'; +import { hash, type RuntimeDependencies } from './runtime-model'; + +const directories: string[] = []; +afterEach(() => { + for (const directory of directories.splice(0)) + rmSync(directory, { recursive: true, force: true }); +}); +const ledger = readdirSync( + new URL( + '../../../../../services/platform/backend/db/migrations/', + import.meta.url, + ), +) + .filter( + (name) => + /^\d{4}_.*\.(sql|ts)$/.test(name) && Number(name.slice(0, 4)) <= 153, + ) + .sort(); +const census = (unfinished = false) => + JSON.stringify({ schema: 'tale', ids: ledger }) + + '\n' + + JSON.stringify({ safeTable: true, unfinished, owned: true }); +const ok = (value: unknown) => ({ + success: true, + exitCode: 0, + stdout: typeof value === 'string' ? value : JSON.stringify(value), + stderr: '', +}); + +function fixture() { + const stateDirectory = mkdtempSync(join(tmpdir(), 'tale-cutover-test-')); + directories.push(stateDirectory); + mkdirSync(join(stateDirectory, '.tale')); + const labels = (service: string) => ({ + 'com.docker.compose.project': 'example', + 'com.docker.compose.service': service, + 'com.docker.compose.container-number': '1', + 'com.docker.compose.oneoff': 'False', + }); + const database = { + Id: 'a'.repeat(64), + Image: `sha256:${'b'.repeat(64)}`, + RestartCount: 0, + Config: { Image: 'synthetic-db', Labels: labels('db') }, + State: { Running: true, StartedAt: '2026-10-08T00:00:00Z' }, + }; + const writers = ['backend-api', 'backend-worker'].map((service, index) => ({ + Id: (index ? 'd' : 'c').repeat(64), + Image: `sha256:${'e'.repeat(64)}`, + RestartCount: 0, + State: { + Running: true, + StartedAt: '2026-10-08T00:00:00Z', + Pid: index + 1000, + Status: 'running', + Dead: false, + }, + HostConfig: { RestartPolicy: { Name: 'unless-stopped' } }, + Config: { + Labels: labels(service), + Env: [ + 'DATABASE_URL=postgresql://synthetic:unused@db:5432/tale_app', + 'SECRET=must-not-escape', + ], + }, + })); + const events: string[] = []; + let healthy = true; + let revision = LEGACY_CUTOVER_REVISION; + let unfinished = false; + let onStop: (() => void) | undefined; + let onAcquire: (() => void) | undefined; + let installed = 1; + let sourceProtocol = 1; + const targetId = `sha256:${'7'.repeat(64)}`; + const targetReference = `ghcr.io/tale-project/tale/tale-platform@sha256:${'6'.repeat(64)}`; + const dependencies: RuntimeDependencies = { + exec: async (_command, args) => { + if (args[0] === 'ps') + return ok( + args.includes('label=com.docker.compose.project=example') + ? writers + .map( + (w) => + `${w.Id}\t${w.Config.Labels['com.docker.compose.service']}`, + ) + .join('\n') + : '', + ); + if (args[0] === 'image') + return ok( + args.slice(2).map((reference) => { + const Id = reference === targetReference ? targetId : reference; + return { + Id, + RepoDigests: Id === targetId ? [targetReference] : [], + Config: { + Labels: { + 'org.opencontainers.image.revision': + Id === targetId ? options.targetRevision : revision, + [AUTOMATION_PROTOCOL_LABEL]: + Id === targetId ? '2' : String(sourceProtocol), + }, + }, + }; + }), + ); + if (args[0] === 'container') + return ok( + args[2] === database.Id + ? [database] + : writers.filter((w) => args.includes(w.Id)), + ); + if (args[0] === 'exec') + return ok({ + schema: 'tale', + ids: + installed === 2 + ? [...ledger, '0163_automation_legacy_protocol.sql'] + : ledger, + }); + if (args[0] === 'stop') { + events.push('stop'); + expect(args).toEqual([ + 'stop', + '--time=-1', + ...writers.filter((w) => w.State.Running).map((w) => w.Id), + ]); + expect(events.includes('acquire')).toBe(true); + expect( + JSON.parse( + readFileSync( + join(stateDirectory, '.tale/automation-cutover.json'), + 'utf8', + ), + ).phase, + ).toBe('stopping'); + onStop?.(); + for (const writer of writers) + Object.assign(writer.State, { + Running: false, + Pid: 0, + Status: 'exited', + }); + return ok(''); + } + throw new Error('Unexpected fixture command'); + }, + automationSession: async () => ({ + healthy: () => healthy, + query: async (sql) => { + if (!healthy) throw new Error('synthetic secret must not escape'); + if (sql === AUTOMATION_CUTOVER_ACQUIRE_SQL) { + events.push('acquire'); + onAcquire?.(); + return census(unfinished); + } + expect(sql).toBe(AUTOMATION_CUTOVER_PROBE_SQL); + events.push('probe'); + return '{"owned":true}'; + }, + close: async () => { + events.push('close'); + }, + }), + }; + const options = { + databaseId: database.Id, + project: 'example', + stateDirectory, + targetRevision: 'f'.repeat(40), + targetBackendImages: [targetReference], + }; + return { + options, + dependencies, + events, + writers, + database, + receipt: () => + JSON.parse( + readFileSync( + join(stateDirectory, '.tale/automation-cutover.json'), + 'utf8', + ), + ), + run: () => cutoverLegacyAutomation(options, dependencies), + lose: () => { + healthy = false; + }, + reconnect: () => { + healthy = true; + }, + busy: () => { + unfinished = true; + }, + wrongSource: () => { + revision = '0'.repeat(40); + }, + protocol: (floor: number, image: number) => { + installed = floor; + sourceProtocol = image; + }, + replaceWithTargetWriters: (indices = [0, 1]) => { + writers.forEach((writer, index) => { + if (!indices.includes(index)) return; + writer.Id = (index ? '8' : '9').repeat(64); + writer.Image = targetId; + Object.assign(writer.State, { + Running: true, + Pid: index + 2000, + Status: 'running', + }); + }); + }, + onStop: (hook: () => void) => { + onStop = hook; + }, + onAcquire: (hook: () => void) => { + onAcquire = hook; + }, + }; +} + +test('supported census binds all 152 immutable legacy migration names', () => { + expect(ledger.length).toBe(152); + expect(hash(JSON.stringify(ledger))).toBe(LEGACY_CUTOVER_LEDGER_SHA256); + expect(() => requireEmptyLegacyCensus(census())).not.toThrow(); + expect(() => + requireEmptyLegacyCensus(census().replace('"tale"', '"public"')), + ).not.toThrow(); + for (const raw of [ + '', + census(true), + census().replace('"safeTable":true', '"safeTable":false'), + census().replace('"owned":true', '"owned":false'), + census().replace('0153_', '0154_'), + census().replace('"tale"', '"unrecognized"'), + ]) + expect(() => requireEmptyLegacyCensus(raw)).toThrow('zero unfinished'); +}); + +test('held zero, durable identity, exact graceful stop and stopped readback precede lock release', async () => { + const f = fixture(); + await f.run(); + expect(f.events[0]).toBe('acquire'); + expect(f.events.at(-1)).toBe('close'); + expect(f.events.indexOf('stop')).toBeGreaterThan(f.events.indexOf('probe')); + expect(f.writers.every((w) => !w.State.Running)).toBe(true); + expect(f.receipt().phase).toBe('stopped'); + expect(JSON.stringify(f.receipt())).not.toContain('unused'); + expect(JSON.stringify(f.receipt())).not.toContain('SECRET'); +}); + +test('nonzero all-org census refuses before journal or stop', async () => { + const f = fixture(); + f.busy(); + await expect(f.run()).rejects.toThrow('zero unfinished'); + expect(f.events).toEqual(['acquire', 'close']); + expect( + existsSync(join(f.options.stateDirectory, '.tale/automation-cutover.json')), + ).toBe(false); +}); + +test('unsupported source, restart policy and external database refuse before lock or stop', async () => { + for (const kind of ['source', 'restart', 'database'] as const) { + const f = fixture(); + if (kind === 'source') f.wrongSource(); + if (kind === 'restart') + f.writers[0].HostConfig.RestartPolicy.Name = 'always'; + if (kind === 'database') + f.writers[0].Config.Env[0] = + 'DATABASE_URL=postgresql://synthetic@external:5432/tale_app'; + await expect(f.run()).rejects.toThrow(); + expect(f.events).toEqual([]); + } +}); + +test('container or DB incarnation drift after census refuses before stopping', async () => { + for (const kind of ['writer', 'database'] as const) { + const f = fixture(); + f.onAcquire(() => { + if (kind === 'writer') f.writers[0].RestartCount++; + else f.database.RestartCount++; + }); + await expect(f.run()).rejects.toThrow('identities changed'); + expect(f.events).toEqual(['acquire', 'close']); + } +}); + +test('lost lock during stop leaves pending recovery and never admits startup', async () => { + const f = fixture(); + f.onStop(f.lose); + await expect(f.run()).rejects.toThrow('lock was lost'); + expect(f.receipt().phase).toBe('stopping'); + f.reconnect(); + f.onStop(() => {}); + f.events.length = 0; + await f.run(); + expect(f.events[0]).toBe('acquire'); + expect(f.events).not.toContain('stop'); + expect(f.receipt().phase).toBe('stopped'); +}); + +test('uncertain graceful stop is recoverable only after a fresh held census', async () => { + const f = fixture(); + f.onStop(() => { + Object.assign(f.writers[0].State, { + Running: false, + Pid: 0, + Status: 'exited', + }); + throw new Error('stop interrupted'); + }); + await expect(f.run()).rejects.toThrow('Automation cutover is pending'); + expect(f.receipt().phase).toBe('stopping'); + f.onStop(() => {}); + f.busy(); + f.events.length = 0; + await expect(f.run()).rejects.toThrow('zero unfinished'); + expect(f.events).toEqual(['acquire', 'close']); +}); + +test('partial stop failure gives redacted recovery guidance after a progress notice', async () => { + for (const kind of ['throw', 'unsuccessful'] as const) { + const f = fixture(); + const progress = spyOn(logger, 'info').mockImplementation(() => {}); + const original = f.dependencies.exec!; + f.dependencies.exec = async (command, args, options) => { + if (args[0] !== 'stop') return original(command, args, options); + expect(progress).toHaveBeenCalledWith( + 'Automation cutover: holding admission while gracefully stopping legacy backend writers (up to 60 seconds).', + ); + expect(f.receipt().phase).toBe('stopping'); + Object.assign(f.writers[0].State, { + Running: false, + Pid: 0, + Status: 'exited', + }); + if (kind === 'throw') throw new Error('private Docker exception'); + return { + success: false, + exitCode: 1, + stdout: 'private Docker output', + stderr: 'private Docker error', + }; + }; + try { + const failure = await f.run().catch((error: unknown) => error); + expect(failure).toBeInstanceOf(Error); + const message = (failure as Error).message; + expect(message).toContain('Automation cutover is pending'); + expect(message).toContain('Keep the deployment bundle'); + expect(message).toContain('.tale/automation-cutover.json receipt'); + expect(message).toContain('retry the same managed deployment'); + expect(message).toContain('Do not manually restart containers'); + expect(message).not.toContain('private Docker'); + expect(f.receipt().phase).toBe('stopping'); + expect(f.writers[0].State.Running).toBe(false); + expect(f.writers[1].State.Running).toBe(true); + expect(f.events.at(-1)).toBe('close'); + } finally { + progress.mockRestore(); + } + } +}); + +test('restart or target drift cannot reuse a prior stopped receipt', async () => { + for (const kind of ['restart', 'target'] as const) { + const f = fixture(); + await f.run(); + f.events.length = 0; + if (kind === 'restart') f.writers[0].RestartCount++; + else f.options.targetRevision = '0'.repeat(40); + await expect(f.run()).rejects.toThrow('recovery identities changed'); + expect(f.events).toEqual([]); + } +}); + +test('same-protocol upgrade does not take a legacy lock', async () => { + const f = fixture(); + f.protocol(2, 2); + await f.run(); + expect(f.events).toEqual([]); +}); + +test('created new writers can resume only the exact recorded stopped-writer handoff', async () => { + const absent = fixture(); + absent.protocol(1, 2); + await expect(absent.run()).rejects.toThrow('recovery receipt'); + expect(absent.events).toEqual([]); + const f = fixture(); + await f.run(); + f.events.length = 0; + f.replaceWithTargetWriters(); + await f.run(); + expect(f.events).toEqual([]); + f.options.targetRevision = '0'.repeat(40); + await expect(f.run()).rejects.toThrow('stopped-writer handoff'); +}); + +test('partial Compose replacement resumes only with retained exact stopped legacy writers', async () => { + const f = fixture(); + await f.run(); + f.events.length = 0; + f.replaceWithTargetWriters([0]); + await f.run(); + expect(f.events).toEqual([]); + f.writers[1].State.Running = true; + f.writers[1].State.Pid = 1234; + f.writers[1].State.Status = 'running'; + await expect(f.run()).rejects.toThrow('stopped-writer handoff'); + expect(f.events).toEqual([]); +}); diff --git a/tools/cli/src/lib/deployment/automation-cutover.ts b/tools/cli/src/lib/deployment/automation-cutover.ts new file mode 100644 index 0000000000..a706ad71af --- /dev/null +++ b/tools/cli/src/lib/deployment/automation-cutover.ts @@ -0,0 +1,374 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; + +import { z } from 'zod'; + +import { externalDepError, preconditionError } from '../../utils/fail'; +import * as logger from '../../utils/logger'; +import { stableJson } from '../config/releases/identity'; +import { + AUTOMATION_CUTOVER_ACQUIRE_SQL, + AUTOMATION_CUTOVER_PROBE_SQL, + cutoverLockOwned, + emptyLegacyCutoverCensus, +} from './automation-cutover-sql'; +export { + AUTOMATION_CUTOVER_ACQUIRE_SQL, + AUTOMATION_CUTOVER_PROBE_SQL, + LEGACY_CUTOVER_LEDGER_SHA256, +} from './automation-cutover-sql'; +import { AUTOMATION_PROTOCOL_LABEL } from './automation-model'; +import { + bundledBackendIdentity, + databaseIdentitySchema, + installedAutomationProtocol, + protocolRead, +} from './automation-protocol'; +import { automationSession } from './automation-session'; +import { runtimeCommand } from './runtime-command'; +import { + atomicRuntimeFile, + readRegular, + requireRuntime, + type RuntimeDependencies, +} from './runtime-model'; + +export const LEGACY_CUTOVER_REVISION = + 'b4931db4b48bdfde37afe1af2a1479e6640a0799'; +const writerSchema = z.strictObject({ + id: z.string().regex(/^[a-f0-9]{64}$/), + image: z.string().regex(/^sha256:[a-f0-9]{64}$/), + revision: z.literal(LEGACY_CUTOVER_REVISION), + protocol: z.literal(1), + restarts: z.number().int().nonnegative(), + running: z.boolean(), + pid: z.number().int().nonnegative(), + status: z.enum(['running', 'exited']), + dead: z.literal(false), + startedAt: z.string(), + restartPolicy: z.literal('unless-stopped'), + project: z.string(), + service: z.enum(['backend-api', 'backend-worker']), +}); +const cutoverReceiptSchema = z.strictObject({ + schemaVersion: z.literal(1), + phase: z.enum(['stopping', 'stopped']), + targetRevision: z.string().regex(/^[a-f0-9]{40}$/), + project: z.string(), + database: databaseIdentitySchema, + writers: z.array(writerSchema).min(2).max(96), +}); + +export function requireEmptyLegacyCensus(raw: string): void { + requireRuntime( + emptyLegacyCutoverCensus(raw), + 'Automation cutover requires the supported legacy schema and zero unfinished runs across all organizations. Keep the old runtime; retry after the existing runs finish.', + ); +} + +/** Invoked only by managed apply, under its deployment custody, after images and + * Compose validate. Stopped old writers bridge lock release to protocol-2 boot; + * the latter installs migration0163 before it starts workers or serves requests. + * A terminal legacy row is not proof that historical external work has retired. */ +export async function cutoverLegacyAutomation( + options: { + databaseId: string; + project: string; + stateDirectory: string; + targetRevision: string; + targetBackendImages: readonly string[]; + }, + dependencies: RuntimeDependencies, +): Promise { + const { databaseId, project } = options; + const inventory = () => + bundledBackendIdentity( + [project, `${project}-blue`, `${project}-green`], + dependencies, + ); + const before = await inventory(); + const floor = await installedAutomationProtocol( + databaseId, + project, + dependencies, + ); + if (floor === 2) return; + const readDatabase = async () => { + try { + const values = z + .array(databaseIdentitySchema) + .length(1) + .parse( + JSON.parse( + await protocolRead( + ['container', 'inspect', databaseId], + dependencies, + ), + ), + ); + const value = values[0]; + const labels = value.Config.Labels; + requireRuntime( + value.Id === databaseId && + labels['com.docker.compose.project'] === project && + labels['com.docker.compose.service'] === 'db' && + labels['com.docker.compose.container-number'] === '1' && + labels['com.docker.compose.oneoff']?.toLowerCase() === 'false', + 'Cutover database custody changed.', + ); + // Persist custody facts only; unrelated Docker labels are not public + // deployment evidence and can contain operator-provided metadata. + return { + ...value, + Config: { + Image: value.Config.Image, + Labels: Object.fromEntries( + [ + 'com.docker.compose.project', + 'com.docker.compose.service', + 'com.docker.compose.container-number', + 'com.docker.compose.oneoff', + ].map((name) => [name, labels[name]]), + ), + }, + }; + } catch { + throw preconditionError( + 'Automation cutover database identity is unreadable.', + ); + } + }; + const database = await readDatabase(); + const receiptFile = join( + options.stateDirectory, + '.tale', + 'automation-cutover.json', + ); + const readPrior = () => { + try { + return cutoverReceiptSchema.parse( + JSON.parse(readRegular(receiptFile).toString('utf8')), + ); + } catch { + throw preconditionError( + 'The automation cutover recovery receipt is unreadable; keep the pending runtime.', + ); + } + }; + if (before.protocol === 2) { + // A created protocol-2 image raises the rollback floor, but is not itself + // proof this legacy transition ever held a zero census. Resume only our + // stopped-writer handoff for this exact target and DB incarnation. + const prior = readPrior(); + const references = [...new Set(options.targetBackendImages)]; + requireRuntime( + references.length > 0 && + references.length <= 2 && + references.every((reference) => + /^ghcr\.io\/tale-project\/tale\/tale-platform@sha256:[a-f0-9]{64}$/.test( + reference, + ), + ), + 'Cutover recovery requires exact prepared backend image references.', + ); + let targetIds: string[]; + try { + const images = z + .array( + z.object({ + Id: z.string().regex(/^sha256:[a-f0-9]{64}$/), + RepoDigests: z.array(z.string()), + Config: z.object({ Labels: z.record(z.string(), z.string()) }), + }), + ) + .length(references.length) + .parse( + JSON.parse( + await protocolRead( + ['image', 'inspect', ...references], + dependencies, + ), + ), + ); + requireRuntime( + references.every( + (reference) => + images.filter((image) => image.RepoDigests.includes(reference)) + .length === 1, + ) && + images.every( + (image) => + image.Config.Labels['org.opencontainers.image.revision'] === + options.targetRevision && + image.Config.Labels[AUTOMATION_PROTOCOL_LABEL] === '2', + ), + 'Target image capability differs.', + ); + targetIds = images.map((image) => image.Id); + } catch { + throw preconditionError( + 'Automation cutover recovery cannot verify the prepared target images.', + ); + } + requireRuntime( + prior.phase === 'stopped' && + prior.targetRevision === options.targetRevision && + prior.project === project && + stableJson(prior.database) === stableJson(database) && + before.writers.every((writer) => { + const old = prior.writers.find( + (retained) => retained.id === writer.id, + ); + return old + ? stableJson(writer) === + stableJson( + Object.assign({}, old, { + running: false, + pid: 0, + status: 'exited', + }), + ) + : writer.protocol === 2 && + writer.revision === options.targetRevision && + writer.project === project && + targetIds.includes(writer.image); + }) && + before.identity === (await inventory()).identity && + stableJson(database) === stableJson(await readDatabase()), + 'Interrupted automation cutover lacks a matching stopped-writer handoff or has mixed old and new writers. Keep the pending managed deployment.', + ); + return; + } + const parsed = z.array(writerSchema).min(2).max(96).safeParse(before.writers); + requireRuntime( + parsed.success, + 'Automation cutover supports only the verified b493 legacy runtime with unless-stopped backend writers. Keep this runtime and use a supported managed upgrade.', + ); + const writers = parsed.data; + requireRuntime( + writers.every((writer) => + writer.running + ? writer.status === 'running' && writer.pid > 0 + : writer.status === 'exited' && writer.pid === 0, + ), + 'Automation cutover writer process state is uncertain.', + ); + requireRuntime( + writers.every((writer) => writer.project === project), + 'Automation cutover requires the single managed Compose project; blue/green writers are outside its custody.', + ); + const receipt = { + schemaVersion: 1 as const, + phase: 'stopping' as const, + targetRevision: options.targetRevision, + project, + database, + writers, + }; + if (existsSync(receiptFile)) { + const prior = readPrior(); + const normalize = (value: typeof writers) => + value.map((writer) => ({ + ...writer, + running: false, + pid: 0, + status: 'exited', + })); + requireRuntime( + prior.targetRevision === options.targetRevision && + prior.project === project && + stableJson(prior.database) === stableJson(database) && + stableJson(normalize(prior.writers)) === stableJson(normalize(writers)), + 'Automation cutover recovery identities changed. Keep the pending runtime and reconcile its recorded writers.', + ); + } + const session = await (dependencies.automationSession ?? automationSession)( + databaseId, + ); + let heartbeat: ReturnType | undefined; + let heartbeatWork = Promise.resolve(); + let lost = false; + const probe = async () => { + requireRuntime( + !lost && session.healthy(), + 'The automation cutover lock was lost. No runtime was started.', + ); + try { + requireRuntime( + cutoverLockOwned(await session.query(AUTOMATION_CUTOVER_PROBE_SQL)), + 'Cutover lock ownership differs.', + ); + } catch { + lost = true; + throw preconditionError( + 'The automation cutover lock was lost. No runtime was started.', + ); + } + }; + try { + requireEmptyLegacyCensus( + await session.query(AUTOMATION_CUTOVER_ACQUIRE_SQL), + ); + requireRuntime( + before.identity === (await inventory()).identity && + stableJson(database) === stableJson(await readDatabase()), + 'Automation cutover identities changed before stopping writers.', + ); + await probe(); + atomicRuntimeFile(receiptFile, JSON.stringify(receipt)); + heartbeat = setInterval(() => { + heartbeatWork = heartbeatWork.then(probe).catch(() => { + lost = true; + }); + }, 2_000); + const running = writers + .filter((writer) => writer.running) + .map((writer) => writer.id); + if (running.length) { + logger.info( + 'Automation cutover: holding admission while gracefully stopping legacy backend writers (up to 60 seconds).', + ); + try { + await runtimeCommand(['stop', '--time=-1', ...running], dependencies, { + timeout: 60, + maxOutputBytes: 1_048_576, + }); + } catch { + throw externalDepError( + 'Automation cutover is pending: the graceful stop did not complete. Keep the deployment bundle and .tale/automation-cutover.json receipt, then retry the same managed deployment. Do not manually restart containers.', + ); + } + } + clearInterval(heartbeat); + heartbeat = undefined; + await heartbeatWork; + await probe(); + const after = await inventory(); + requireRuntime( + stableJson(after.writers) === + stableJson( + writers.map((writer) => + Object.assign({}, writer, { + running: false, + pid: 0, + status: 'exited', + }), + ), + ) && stableJson(database) === stableJson(await readDatabase()), + 'Automation cutover did not observe every exact old writer stopped. Keep the pending deployment; do not start the new runtime.', + ); + await probe(); + atomicRuntimeFile( + receiptFile, + JSON.stringify({ ...receipt, phase: 'stopped' }), + ); + requireRuntime( + session.healthy() && !lost, + 'Automation cutover lock was lost before handoff. Retry the same managed deployment.', + ); + } finally { + if (heartbeat) clearInterval(heartbeat); + await heartbeatWork; + await session.close(); + } +} diff --git a/tools/cli/src/lib/deployment/automation-protocol.test.ts b/tools/cli/src/lib/deployment/automation-protocol.test.ts index 9c9748020c..fe59c3c858 100644 --- a/tools/cli/src/lib/deployment/automation-protocol.test.ts +++ b/tools/cli/src/lib/deployment/automation-protocol.test.ts @@ -143,6 +143,16 @@ test('tag admission binds source and digest and all backend roles consume that d }; const deps: RuntimeDependencies = { exec: async () => ok([metadata]) }; expect(await admitTagAutomationImage(config, 2, deps)).toBe(reference); + await expect( + admitTagAutomationImage(config, 1, { + exec: async (_c, args) => (args[0] === 'ps' ? ok(db.Id) : ok([metadata])), + }), + ).rejects.toThrow('cutover barrier'); + expect( + await admitTagAutomationImage(config, 1, { + exec: async (_c, args) => (args[0] === 'ps' ? ok('') : ok([metadata])), + }), + ).toBe(reference); const compose = parse( generateColorCompose({ ...config, platformImage: reference }, 'green'), ); @@ -406,6 +416,64 @@ test('tag floor never substitutes the bundled ledger for a current or removed ex } }); +test('managed apply cannot start protocol two over an unsupported legacy writer', async () => { + const fixture = runtimeFixture(); + fixtures.push(fixture); + const docker = new RuntimeDockerFixture(fixture); + const prepare = () => + prepareRuntime( + { + repoRoot: fixture.repoRoot, + revision: fixture.revision, + output: fixture.options.bundleDirectory, + platform: 'linux/amd64', + }, + docker.dependencies(), + ); + await prepare(); + installLegacy(fixture, docker); + writeFileSync( + join(fixture.repoRoot, AUTOMATION_PROTOCOL_SOURCE), + 'export const ENGINE_PROTOCOL = 2;\n', + ); + writeFileSync( + join( + fixture.repoRoot, + 'services/platform/backend/db/migrations/0163_automation_legacy_protocol.sql', + ), + 'SELECT 1;\n', + ); + fixture.git('add', '.'); + fixture.git('commit', '-qm', 'new protocol target'); + fixture.revision = fixture.git('rev-parse', 'HEAD'); + fixture.options.bundleDirectory = join(fixture.directory, 'protocol-two'); + await prepare(); + docker.calls = []; + await expect( + applyRuntime(fixture.options, { + ...docker.dependencies(), + exec: async (command, args, options) => { + if ( + args[0] === 'ps' && + args.some( + (arg) => + arg === 'label=com.docker.compose.project=tale-blue' || + arg === 'label=com.docker.compose.project=tale-green', + ) + ) + return ok(''); + return docker.execute(command, args, options); + }, + }), + ).rejects.toThrow('verified b493'); + expect( + docker.calls.some( + (call) => call.args[0] === 'compose' && call.args.includes('up'), + ), + ).toBe(false); + expect(docker.calls.some((call) => call.args[0] === 'stop')).toBe(false); +}); + test('managed source protocol requires its migration and rechecks the immutable image before mutation', async () => { const fixture = runtimeFixture(); fixtures.push(fixture); diff --git a/tools/cli/src/lib/deployment/automation-protocol.ts b/tools/cli/src/lib/deployment/automation-protocol.ts index 875b166c74..f7b1892047 100644 --- a/tools/cli/src/lib/deployment/automation-protocol.ts +++ b/tools/cli/src/lib/deployment/automation-protocol.ts @@ -34,7 +34,7 @@ export function requireAutomationProtocol( ); } -const databaseIdentitySchema = z.object({ +export const databaseIdentitySchema = z.object({ Id: z.string().regex(/^[a-f0-9]{64}$/), Image: z.string().regex(/^sha256:[a-f0-9]{64}$/), RestartCount: z.number().int().nonnegative(), @@ -125,7 +125,16 @@ const backendIdentitySchema = z.object({ Id: z.string().regex(/^[a-f0-9]{64}$/), Image: z.string().regex(/^sha256:[a-f0-9]{64}$/), RestartCount: z.number().int().nonnegative(), - State: z.object({ Running: z.boolean(), StartedAt: z.string() }), + State: z.object({ + Running: z.boolean(), + StartedAt: z.string(), + Pid: z.number().int().nonnegative().optional(), + Status: z.string().optional(), + Dead: z.boolean().optional(), + }), + HostConfig: z + .object({ RestartPolicy: z.object({ Name: z.string() }) }) + .optional(), Config: z.object({ Labels: z.record(z.string(), z.string()), Env: z.array(z.string()).max(2048), @@ -138,7 +147,7 @@ const backendIdentitySchema = z.object({ export async function bundledBackendIdentity( projects: readonly string[], dependencies: RuntimeDependencies, -): Promise<{ identity: string; protocol: AutomationWriterProtocol }> { +) { const ids: string[] = []; requireRuntime( projects.length > 0 && @@ -286,12 +295,37 @@ export async function bundledBackendIdentity( .map((image) => ({ id: image.Id, protocol: imageWriterProtocol(image.Config.Labels), + revision: + image.Config.Labels?.['org.opencontainers.image.revision'] ?? null, })) .sort((a, b) => a.id.localeCompare(b.id)); - const protocol = capabilities.some((image) => image.protocol === 2) ? 2 : 1; + const protocol: AutomationWriterProtocol = capabilities.some( + (image) => image.protocol === 2, + ) + ? 2 + : 1; // Compare only the owned identities and connection, never unrelated secrets. return { protocol, + writers: values + .map((v) => ({ + id: v.Id, + image: v.Image, + revision: + capabilities.find((image) => image.id === v.Image)?.revision ?? null, + protocol: + capabilities.find((image) => image.id === v.Image)?.protocol ?? null, + restarts: v.RestartCount, + running: v.State.Running, + pid: v.State.Pid ?? null, + status: v.State.Status ?? null, + dead: v.State.Dead ?? null, + startedAt: v.State.StartedAt, + restartPolicy: v.HostConfig?.RestartPolicy.Name ?? null, + project: v.Config.Labels['com.docker.compose.project'], + service: v.Config.Labels['com.docker.compose.service'], + })) + .sort((a, b) => a.id.localeCompare(b.id)), identity: stableJson({ capabilities, containers: values @@ -300,6 +334,7 @@ export async function bundledBackendIdentity( Image: v.Image, RestartCount: v.RestartCount, State: v.State, + RestartPolicy: v.HostConfig?.RestartPolicy.Name ?? null, Config: { Labels: v.Config.Labels, Env: v.Config.Env.filter((e) => e.startsWith('DATABASE_URL=')), diff --git a/tools/cli/src/lib/deployment/automation-session.test.ts b/tools/cli/src/lib/deployment/automation-session.test.ts new file mode 100644 index 0000000000..42a7d4eb0e --- /dev/null +++ b/tools/cli/src/lib/deployment/automation-session.test.ts @@ -0,0 +1,92 @@ +import { afterEach, describe, expect, test } from 'bun:test'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { boundedOutput } from '../docker/bounded-output'; +import { runtimeProcessEnvironment } from './runtime-command'; + +const directories: string[] = []; +afterEach(() => { + for (const directory of directories.splice(0)) + rmSync(directory, { recursive: true, force: true }); +}); + +// A child process owns PATH; no test changes the parent runner's Docker command. +// The fake Docker is a real process with real OS pipes, never a promise mock. +async function transport(fake: string, script: string) { + const directory = mkdtempSync(join(tmpdir(), 'tale-cutover-pipe-test-')); + directories.push(directory); + writeFileSync(join(directory, 'docker'), `#!${process.execPath}\n${fake}\n`, { + mode: 0o700, + }); + // Other action suites mock docker/exec globally. Own the actual child here + // while retaining the shared deadline, byte cap and process-group cleanup. + const child = Bun.spawn( + [ + process.execPath, + '-e', + `import { automationSession } from ${JSON.stringify(new URL('./automation-session.ts', import.meta.url).href)};\n${script}`, + ], + { + stdin: 'pipe', + stdout: 'pipe', + stderr: 'pipe', + detached: process.platform !== 'win32', + env: { + ...runtimeProcessEnvironment(), + PATH: `${directory}:${process.env.PATH ?? ''}`, + }, + }, + ); + return boundedOutput(child, { timeout: 12, maxOutputBytes: 16_384 }); +} + +describe.skipIf(process.platform === 'win32')( + 'bounded automation lock transport', + () => { + test('close deadline covers stdin backpressure as well as process exit', async () => { + const result = await transport( + 'await Bun.sleep(60_000);', + ` +const session = await automationSession('${'a'.repeat(64)}'); +const query = session.query(' '.repeat(4_000_000)).catch(() => 'refused'); +const started = performance.now(); +await session.close(); +console.log(JSON.stringify({ elapsed: performance.now() - started, query: await query, healthy: session.healthy() })); +`, + ); + expect(result.success).toBe(true); + const observed = JSON.parse(result.stdout); + expect(observed.query).toBe('refused'); + expect(observed.healthy).toBe(false); + expect(observed.elapsed).toBeLessThan(8_000); + }, 15_000); + + test('oversized output and private subprocess errors revoke the session without rendering payloads', async () => { + for (const fake of [ + "process.stdout.write('x'.repeat(1_048_577)); await Bun.sleep(60_000);", + "console.error('SYNTHETIC_PRIVATE_DATABASE_VALUE'); process.exit(1);", + ]) { + const result = await transport( + fake, + ` +const session = await automationSession('${'a'.repeat(64)}'); +let refused = false; +try { await session.query('SELECT 1;'); } catch (error) { refused = !String(error).includes('SYNTHETIC_PRIVATE_DATABASE_VALUE'); } +await session.close(); +console.log(JSON.stringify({ refused, healthy: session.healthy() })); +`, + ); + expect(result.success).toBe(true); + expect(JSON.parse(result.stdout)).toEqual({ + refused: true, + healthy: false, + }); + expect(result.stdout + result.stderr).not.toContain( + 'SYNTHETIC_PRIVATE_DATABASE_VALUE', + ); + } + }, 15_000); + }, +); diff --git a/tools/cli/src/lib/deployment/automation-session.ts b/tools/cli/src/lib/deployment/automation-session.ts new file mode 100644 index 0000000000..0112b44d51 --- /dev/null +++ b/tools/cli/src/lib/deployment/automation-session.ts @@ -0,0 +1,139 @@ +import { randomUUID } from 'node:crypto'; + +import { preconditionError } from '../../utils/fail'; +import { migrationSessionCommand } from './acceptance-migrations'; +import { runtimeProcessEnvironment } from './runtime-command'; +import { requireRuntime, type RuntimeSqlSession } from './runtime-model'; + +const sessionFailure = () => + preconditionError( + 'The automation cutover lock session was lost or timed out. No new runtime may start; retry the same managed deployment to reconcile its stopped writers.', + ); + +/** Private bounded psql session. It never exposes Docker/SQL error payloads. + * PostgreSQL's idle timeout also retires the transaction after a CLI crash. */ +export async function automationSession( + containerId: string, +): Promise { + requireRuntime( + /^[a-f0-9]{64}$/.test(containerId), + 'Invalid cutover database identity.', + ); + const proc = Bun.spawn( + [ + 'docker', + 'exec', + '-i', + containerId, + 'sh', + '-c', + migrationSessionCommand('db'), + ], + { + stdin: 'pipe', + stdout: 'pipe', + stderr: 'pipe', + env: runtimeProcessEnvironment(), + }, + ); + let alive = true; + let closing = false; + let bytes = 0; + let pending: + | { + token: string; + lines: string[]; + resolve: (value: string) => void; + reject: (error: Error) => void; + } + | undefined; + const fail = () => { + alive = false; + pending?.reject(sessionFailure()); + pending = undefined; + proc.kill(); + }; + const deadline = setTimeout(fail, 90_000); + const consume = async ( + stream: ReadableStream, + output: boolean, + ) => { + const decoder = new TextDecoder(); + let buffered = ''; + try { + for await (const chunk of stream) { + bytes += chunk.byteLength; + if (bytes > 1_048_576) { + fail(); + return; + } + if (!output) continue; + buffered += decoder.decode(chunk, { stream: true }); + let newline: number; + while ((newline = buffered.indexOf('\n')) !== -1) { + const line = buffered.slice(0, newline).replace(/\r$/, ''); + buffered = buffered.slice(newline + 1); + if (!pending) { + if (!closing) fail(); + continue; + } + if (line === pending.token) { + const result = pending; + pending = undefined; + result.resolve(result.lines.join('\n')); + } else pending.lines.push(line); + } + } + if (!closing) fail(); + } catch { + fail(); + } + }; + const readers = [consume(proc.stdout, true), consume(proc.stderr, false)]; + void proc.exited.then(() => { + if (!closing) fail(); + return undefined; + }); + return { + healthy: () => alive && !closing && proc.exitCode === null, + async query(sql) { + if (!alive || closing || pending || proc.exitCode !== null) + throw sessionFailure(); + const token = `TALE_${randomUUID().replaceAll('-', '')}`; + const timer = setTimeout(fail, 10_000); + try { + return await new Promise((resolve, reject) => { + pending = { token, lines: [], resolve, reject }; + try { + proc.stdin.write(`${sql}\n\\echo ${token}\n`); + void Promise.resolve(proc.stdin.flush()).catch(fail); + } catch { + fail(); + } + }); + } finally { + clearTimeout(timer); + } + }, + async close() { + clearTimeout(deadline); + closing = true; + alive = false; + pending?.reject(sessionFailure()); + pending = undefined; + const timer = setTimeout(() => proc.kill(), 5_000); + try { + try { + proc.stdin.write('ROLLBACK;\n\\q\n'); + await proc.stdin.end(); + } catch { + /* The lost connection itself rolls back; no startup follows it. */ + } + await proc.exited; + await Promise.all(readers); + } finally { + clearTimeout(timer); + } + }, + }; +} diff --git a/tools/cli/src/lib/deployment/inputs.test.ts b/tools/cli/src/lib/deployment/inputs.test.ts index 6d22a77910..2f77c7a342 100644 --- a/tools/cli/src/lib/deployment/inputs.test.ts +++ b/tools/cli/src/lib/deployment/inputs.test.ts @@ -510,7 +510,9 @@ test('failed private source checkout scrubs errors and removes its ephemeral key throw new Error('must not reach source consumer'); }, ), - ).rejects.toThrow('read-only checkout key'); + ).rejects.toThrow( + 'configuration deployment source during fetch (exit 1; failure hint: unknown)', + ); expect(keySeen).toBe(true); expect(() => readFileSync(keyFile)).toThrow(); }); diff --git a/tools/cli/src/lib/deployment/runtime-apply.ts b/tools/cli/src/lib/deployment/runtime-apply.ts index 14158aac4c..1527a19f7c 100644 --- a/tools/cli/src/lib/deployment/runtime-apply.ts +++ b/tools/cli/src/lib/deployment/runtime-apply.ts @@ -8,6 +8,7 @@ import { z } from 'zod'; import { externalDepError } from '../../utils/fail'; import { BACKUP_VOLUME, GATEWAY_VOLUME } from '../backup/constants'; import { validateAdditionalSiteUrls } from '../config/ensure-env'; +import { cutoverLegacyAutomation } from './automation-cutover'; import { AUTOMATION_PROTOCOL_MIGRATION } from './automation-model'; import { bundledBackendIdentity, @@ -1113,6 +1114,24 @@ export async function applyRuntime( operation: 'compose-validation', }); await checkInstalledProtocol(); + if (bundle.automationWriterProtocol === 2 && databases.length === 1) + await cutoverLegacyAutomation( + { + databaseId: databases[0].Id, + project: options.composeProject, + stateDirectory: options.stateDirectory, + targetRevision: bundle.revision, + targetBackendImages: bundle.images + .filter((image) => + image.services.some( + (service) => + service === 'backend-api' || service === 'backend-worker', + ), + ) + .map((image) => image.reference), + }, + dependencies, + ); await runtimeCommand( [ ...composeArgs, diff --git a/tools/cli/src/lib/deployment/runtime-command.ts b/tools/cli/src/lib/deployment/runtime-command.ts index 8f38362517..98c89f3925 100644 --- a/tools/cli/src/lib/deployment/runtime-command.ts +++ b/tools/cli/src/lib/deployment/runtime-command.ts @@ -48,6 +48,7 @@ export async function runtimeCommand( options: { cwd?: string; timeout?: number; + maxOutputBytes?: number; allowFailure?: boolean; operation?: 'compose-validation' | 'compose-startup'; /** @@ -72,6 +73,9 @@ export async function runtimeCommand( timeout: options.timeout ?? 60, silent: true, env: runtimeProcessEnvironment(), + ...(options.maxOutputBytes === undefined + ? {} + : { maxOutputBytes: options.maxOutputBytes }), }); } catch { throw externalDepError( diff --git a/tools/cli/src/lib/deployment/runtime-model.ts b/tools/cli/src/lib/deployment/runtime-model.ts index b4970882f0..2156293ff5 100644 --- a/tools/cli/src/lib/deployment/runtime-model.ts +++ b/tools/cli/src/lib/deployment/runtime-model.ts @@ -93,6 +93,13 @@ export interface RuntimeDependencies { sleep?: (milliseconds: number) => Promise; /** Isolated tests must not create the production host workspace. */ ensureSandboxWorkspace?: () => void; + /** Persistent, private psql transport; substituted only by isolated tests. */ + automationSession?: (containerId: string) => Promise; +} +export interface RuntimeSqlSession { + query: (sql: string) => Promise; + healthy: () => boolean; + close: () => Promise; } export interface PrepareRuntimeOptions { repoRoot: string; diff --git a/tools/cli/src/lib/deployment/sources.test.ts b/tools/cli/src/lib/deployment/sources.test.ts index 7c72f6d095..d9ebfe669b 100644 --- a/tools/cli/src/lib/deployment/sources.test.ts +++ b/tools/cli/src/lib/deployment/sources.test.ts @@ -10,6 +10,8 @@ import { import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; +import { operationalFailure } from '../../commands/operational-failure'; +import { CliError, ExitCode } from '../../utils/fail'; import { TALE_REPOSITORY, withDeploymentSources } from './sources'; const roots: string[] = []; @@ -88,6 +90,8 @@ for (const variant of ['LF', 'missing LF', 'CRLF', 'CRLF missing LF']) { run: async (command, args, options) => { expect(command).toBe('git'); expect(options?.silent).toBe(true); + expect(options?.timeout).toBe(300); + expect(options?.maxOutputBytes).toBe(1_048_576); expect(options?.env).not.toHaveProperty('TALE_SOURCE_SSH_KEY'); expect(JSON.stringify(options?.env)).not.toContain(sourceKey); if (args.includes('fetch')) { @@ -153,3 +157,110 @@ test('public runtime source acquisition does not stage or use a client key', asy ); expect(existsSync(root)).toBe(false); }); + +async function sourceFailure({ + stage = 'fetch', + request = runtime, + stderr = '', + exitCode = 128, + thrown, +}: { + stage?: string; + request?: typeof runtime; + stderr?: string; + exitCode?: number; + thrown?: Error; +}) { + let root = ''; + let failures = 0; + try { + await withDeploymentSources( + [request], + { + run: async (_command, args) => { + root = dirname(args[1]!); + if (!args.includes(stage)) return success(revision); + failures++; + if (thrown) throw thrown; + return { success: false, stdout: '', stderr, exitCode }; + }, + }, + async () => { + throw new Error('failed acquisition must not reach its consumer'); + }, + ); + throw new Error('source acquisition must fail'); + } catch (error) { + expect(error).toBeInstanceOf(CliError); + if (!(error instanceof CliError)) throw error; + expect(error.info.code).toBe(ExitCode.ExternalDep); + expect(error.info.cause).toBeUndefined(); + expect(failures).toBe(1); + expect(existsSync(root)).toBe(false); + expect( + operationalFailure(error, { schema: 'invalid input', summary: 'failed' }), + ).toBe(error); + return error; + } +} + +test('source acquisition distinguishes disk and DNS failures without exposing stderr', async () => { + const disk = await sourceFailure({ + stderr: 'fatal: No space left on device /private/checkout secret-marker', + }); + const dns = await sourceFailure({ + stderr: 'fatal: Could not resolve host: private.example secret-marker', + }); + expect(disk.message).toBe( + 'Git could not acquire the pinned runtime deployment source during fetch (exit 128; failure hint: no-space).', + ); + expect(dns.message).toBe( + 'Git could not acquire the pinned runtime deployment source during fetch (exit 128; failure hint: name-resolution).', + ); + for (const error of [disk, dns]) { + expect(JSON.stringify(error.info)).not.toContain('secret-marker'); + expect(JSON.stringify(error.info)).not.toContain('private'); + } +}); + +for (const request of [runtime, client]) { + for (const stage of ['init', 'remote', 'fetch', 'checkout', 'rev-parse']) { + test(`source acquisition identifies ${request === runtime ? 'runtime' : 'configuration'} ${stage} failures`, async () => { + const error = await sourceFailure({ + request, + stage, + stderr: + 'unknown secret-marker https://private.example/repo /private/key', + }); + expect(error.message).toContain( + `pinned ${request === runtime ? 'runtime' : 'configuration'} deployment source during ${stage} (exit 128; failure hint: unknown)`, + ); + const rendered = JSON.stringify(error.info); + for (const privateValue of [ + 'secret-marker', + 'private', + request.repository, + ]) + expect(rendered).not.toContain(privateValue); + }); + } +} + +for (const exitCode of [Number.NaN, Number.POSITIVE_INFINITY, -1, 0, 256]) { + test(`source acquisition refuses invalid exit status ${exitCode}`, async () => { + const error = await sourceFailure({ exitCode }); + expect(error.message).toContain('(exit unknown; failure hint: unknown)'); + }); +} + +for (const [message, hint] of [ + ['Command exceeded its time limit.', 'timeout'], + ['Command output exceeded its byte limit.', 'output-limit'], + ['unexpected private-source-key-marker /private/key', 'unknown'], +]) { + test(`source acquisition classifies thrown ${hint} failures safely`, async () => { + const error = await sourceFailure({ thrown: new Error(message) }); + expect(error.message).toContain(`(exit unknown; failure hint: ${hint})`); + expect(JSON.stringify(error.info)).not.toContain(message); + }); +} diff --git a/tools/cli/src/lib/deployment/sources.ts b/tools/cli/src/lib/deployment/sources.ts index 363d944b61..a33329ee5d 100644 --- a/tools/cli/src/lib/deployment/sources.ts +++ b/tools/cli/src/lib/deployment/sources.ts @@ -14,9 +14,47 @@ export interface SourceRequest { revision: string; } type SourceMap = Record; +type SourceKind = 'runtime' | 'configuration'; +type SourceStage = 'init' | 'remote' | 'fetch' | 'checkout' | 'rev-parse'; const sourceKey = ({ repository, revision }: SourceRequest) => `${repository}@${revision}`; +// Output is diagnostic input only: emit authored hints, never Git's text, +// repository URLs, temporary paths or a possibly credential-bearing cause. +function stderrHint(stderr: string) { + const text = stderr.toLowerCase(); + if (text.includes('no space left on device')) return 'no-space'; + if (text.includes('could not resolve host')) return 'name-resolution'; + return 'unknown'; +} + +function thrownHint(error: unknown) { + if (error instanceof Error) { + if (error.message === 'Command exceeded its time limit.') return 'timeout'; + if (error.message === 'Command output exceeded its byte limit.') + return 'output-limit'; + } + return 'unknown'; +} + +function acquisitionError( + kind: SourceKind, + stage: SourceStage, + hint: ReturnType | ReturnType, + exitCode?: number, +) { + const exit = + exitCode !== undefined && + Number.isSafeInteger(exitCode) && + exitCode > 0 && + exitCode <= 255 + ? exitCode + : 'unknown'; + return externalDepError( + `Git could not acquire the pinned ${kind} deployment source during ${stage} (exit ${exit}; failure hint: ${hint}).`, + ); +} + /** The metadata endpoint is authenticated by HTTPS. Do not learn an SSH key * from the SSH connection it is meant to authenticate (ssh-keyscan alone). */ type MetadataFetch = (url: string, init: RequestInit) => Promise; @@ -117,7 +155,13 @@ export async function withDeploymentSources( GIT_NO_REPLACE_OBJECTS: '1', GIT_TERMINAL_PROMPT: '0', }; - const execute = async (directory: string, args: string[], ssh?: string) => { + const execute = async ( + directory: string, + kind: SourceKind, + stage: SourceStage, + args: string[], + ssh?: string, + ) => { let result; try { result = await run( @@ -139,17 +183,19 @@ export async function withDeploymentSources( ...(ssh ? { GIT_SSH_COMMAND: ssh } : {}), }, timeout: 300, + maxOutputBytes: 1_048_576, silent: true, }, ); - } catch { - throw externalDepError( - 'Git could not acquire the pinned deployment source.', - ); + } catch (error) { + throw acquisitionError(kind, stage, thrownHint(error)); } if (!result.success) - throw externalDepError( - 'Git could not acquire the pinned deployment source. Check the repository, full commit SHA and read-only checkout key.', + throw acquisitionError( + kind, + stage, + stderrHint(result.stderr), + result.exitCode, ); return result.stdout.trim(); }; @@ -157,6 +203,8 @@ export async function withDeploymentSources( let index = 0; for (const request of requests) { const revision = gitSha.parse(request.revision); + const kind = + request.repository === TALE_REPOSITORY ? 'runtime' : 'configuration'; const key = sourceKey(request); if (sources[key]) continue; const match = @@ -177,7 +225,7 @@ export async function withDeploymentSources( : join(root, `repository-${index++}`); if (!supplied) { await mkdir(directory, { mode: 0o700 }); - await execute(directory, ['init', '--template=']); + await execute(directory, kind, 'init', ['init', '--template=']); let remote = request.repository; let sourceSsh: string | undefined; // The runtime is always public. A client key is used only for a @@ -223,17 +271,31 @@ export async function withDeploymentSources( remote = `git@github.com:${match[1]}/${match[2]}.git`; sourceSsh = ssh; } - await execute(directory, ['remote', 'add', 'origin', remote]); + await execute(directory, kind, 'remote', [ + 'remote', + 'add', + 'origin', + remote, + ]); // Tags are required to resolve an older release image back to this // exact commit; none of them is accepted as the requested source pin. await execute( directory, + kind, + 'fetch', ['fetch', '--depth=1', '--tags', 'origin', revision], sourceSsh, ); - await execute(directory, ['checkout', '--detach', revision]); + await execute(directory, kind, 'checkout', [ + 'checkout', + '--detach', + revision, + ]); } - if ((await execute(directory, ['rev-parse', 'HEAD'])) !== revision) + if ( + (await execute(directory, kind, 'rev-parse', ['rev-parse', 'HEAD'])) !== + revision + ) throw preconditionError( 'Deployment checkout differs from the requested full commit SHA.', ); diff --git a/tools/cli/src/lib/deployment/tag-automation-protocol.ts b/tools/cli/src/lib/deployment/tag-automation-protocol.ts index 1cb63d32dc..cb17cbf6f4 100644 --- a/tools/cli/src/lib/deployment/tag-automation-protocol.ts +++ b/tools/cli/src/lib/deployment/tag-automation-protocol.ts @@ -1,6 +1,7 @@ import { z } from 'zod'; import { imageRef, type ServiceConfig } from '../compose/types'; +import { getProjectId } from '../project/project-context'; import type { AutomationWriterProtocol } from './automation-model'; import { bundledBackendIdentity, @@ -135,6 +136,28 @@ export async function admitTagAutomationImage( const protocol = imageWriterProtocol(image.Config.Labels); requireAutomationProtocol(installed, protocol); if (protocol === 1) return undefined; + if (installed === 1) { + // A tag/color deployment does not own the managed cutover recovery journal. + // Empty-host installs are safe; an existing DB must use managed apply. + const databases = await protocolRead( + [ + 'ps', + '-a', + '--no-trunc', + '--filter', + 'label=com.docker.compose.service=db', + '--filter', + `label=com.docker.compose.project=${getProjectId()}`, + '--format', + '{{.ID}}', + ], + dependencies, + ); + requireRuntime( + databases.trim() === '', + 'An existing protocol-1 database must upgrade through managed deployment apply and its automation cutover barrier before using tag deployments.', + ); + } const repository = `${config.registry}/tale-platform`; const digests = [ ...new Set( diff --git a/tools/cli/src/lib/docker/prune-superseded-images.test.ts b/tools/cli/src/lib/docker/prune-superseded-images.test.ts deleted file mode 100644 index 8753680d29..0000000000 --- a/tools/cli/src/lib/docker/prune-superseded-images.test.ts +++ /dev/null @@ -1,200 +0,0 @@ -import { describe, expect, mock, test } from 'bun:test'; - -import { pruneSupersededImages } from './prune-superseded-images'; - -const REGISTRY = 'ghcr.io/tale-project/tale'; - -// Fresh fakes per test, injected directly — `mock.module` is process-global in -// Bun and leaks across files. -function fakeDeps( - images: string[], - { - listOk = true, - refuse = {}, - }: { listOk?: boolean; refuse?: Record } = {}, -) { - const docker = mock((...args: string[]) => { - if (args[0] === 'image' && args[1] === 'ls') { - return Promise.resolve({ - success: listOk, - exitCode: listOk ? 0 : 1, - stdout: listOk ? `${images.join('\n')}\n` : '', - stderr: listOk ? '' : 'Cannot connect to the Docker daemon', - }); - } - const reference = args[2] ?? ''; - const stderr = refuse[reference]; - return Promise.resolve({ - success: stderr === undefined, - exitCode: stderr === undefined ? 0 : 1, - stdout: '', - stderr: stderr ?? '', - }); - }); - return { docker, logger: { info: mock(), warn: mock(), debug: mock() } }; -} - -const removedBy = (docker: ReturnType['docker']) => - docker.mock.calls - .filter((call) => call[0] === 'image' && call[1] === 'rm') - .map((call) => call[2]); - -describe('pruneSupersededImages', () => { - test('removes versions older than the live and rollback versions', async () => { - const deps = fakeDeps([ - `${REGISTRY}/tale-sandbox-runtime:0.5.78`, - `${REGISTRY}/tale-sandbox-runtime:0.5.77`, - `${REGISTRY}/tale-sandbox-runtime:0.5.76`, - `${REGISTRY}/tale-platform:0.5.78`, - `${REGISTRY}/tale-platform:0.5.77`, - `${REGISTRY}/tale-platform:0.5.70`, - `${REGISTRY}/tale-db:0.4.9`, - ]); - - const result = await pruneSupersededImages( - REGISTRY, - ['0.5.78', '0.5.77'], - deps, - ); - - expect(removedBy(deps.docker)).toEqual([ - `${REGISTRY}/tale-sandbox-runtime:0.5.76`, - `${REGISTRY}/tale-platform:0.5.70`, - `${REGISTRY}/tale-db:0.4.9`, - ]); - expect(result).toEqual({ - removed: removedBy(deps.docker), - inUse: [], - failed: [], - }); - }); - - test('keeps an image loaded ahead for a later version', async () => { - const deps = fakeDeps([ - `${REGISTRY}/tale-platform:0.5.79`, - `${REGISTRY}/tale-platform:0.5.78`, - `${REGISTRY}/tale-platform:0.5.76`, - ]); - - await pruneSupersededImages(REGISTRY, ['0.5.78', '0.5.77'], deps); - - expect(removedBy(deps.docker)).toEqual([ - `${REGISTRY}/tale-platform:0.5.76`, - ]); - }); - - test('keeps the rollback target after a downgrade', async () => { - // Deploying 0.5.76 over 0.5.78 records 0.5.78 as the rollback target. - const deps = fakeDeps([ - `${REGISTRY}/tale-platform:0.5.78`, - `${REGISTRY}/tale-platform:0.5.76`, - `${REGISTRY}/tale-platform:0.5.75`, - ]); - - await pruneSupersededImages(REGISTRY, ['0.5.76', '0.5.78'], deps); - - expect(removedBy(deps.docker)).toEqual([ - `${REGISTRY}/tale-platform:0.5.75`, - ]); - }); - - test('keeps the newest earlier version when no distinct rollback target is recorded', async () => { - const deps = fakeDeps([ - `${REGISTRY}/tale-platform:0.5.78`, - `${REGISTRY}/tale-platform:0.5.77`, - `${REGISTRY}/tale-sandbox-runtime:0.5.77`, - `${REGISTRY}/tale-platform:0.5.76`, - ]); - - // A redeploy of the live version records it as its own rollback target. - await pruneSupersededImages(REGISTRY, ['0.5.78', '0.5.78'], deps); - - expect(removedBy(deps.docker)).toEqual([ - `${REGISTRY}/tale-platform:0.5.76`, - ]); - }); - - test('touches only release tags of this registry’s tale repositories', async () => { - const deps = fakeDeps([ - `${REGISTRY}/tale-sandbox-runtime:latest`, - `${REGISTRY}/tale-platform:pr-4512`, - `${REGISTRY}/tale-platform:`, - 'tale-sandbox-runtime:latest', - 'tale-sandbox-runtime:0.5.1', - 'ghcr.io/someone-else/tale/tale-platform:0.1.0', - `${REGISTRY}/other-service:0.1.0`, - 'postgres:16.4', - `${REGISTRY}/tale-platform:0.5.70`, - ]); - - await pruneSupersededImages(REGISTRY, ['0.5.78', '0.5.77'], deps); - - expect(removedBy(deps.docker)).toEqual([ - `${REGISTRY}/tale-platform:0.5.70`, - ]); - }); - - test('never forces: an image a container uses is reported and kept', async () => { - const inUse = `${REGISTRY}/tale-sandbox-runtime:0.5.70`; - const broken = `${REGISTRY}/tale-platform:0.5.70`; - const deps = fakeDeps([inUse, broken, `${REGISTRY}/tale-db:0.5.70`], { - refuse: { - [inUse]: - 'Error response from daemon: conflict: unable to remove repository reference "…" (must force) - container 1f2e is using its referenced image 9a8b', - [broken]: 'Error response from daemon: unexpected I/O error', - }, - }); - - const result = await pruneSupersededImages( - REGISTRY, - ['0.5.78', '0.5.77'], - deps, - ); - - expect( - deps.docker.mock.calls.some((call) => call.includes('--force')), - ).toBe(false); - expect(result).toEqual({ - removed: [`${REGISTRY}/tale-db:0.5.70`], - inUse: [inUse], - failed: [broken], - }); - expect(deps.logger.warn).toHaveBeenCalledTimes(1); - }); - - test('a dry run lists what it would remove and removes nothing', async () => { - const deps = fakeDeps([ - `${REGISTRY}/tale-platform:0.5.78`, - `${REGISTRY}/tale-platform:0.5.70`, - ]); - - const result = await pruneSupersededImages(REGISTRY, ['0.5.78', '0.5.77'], { - ...deps, - dryRun: true, - }); - - expect(result.removed).toEqual([`${REGISTRY}/tale-platform:0.5.70`]); - expect(removedBy(deps.docker)).toEqual([]); - }); - - test('does nothing without a known version to keep', async () => { - const deps = fakeDeps([`${REGISTRY}/tale-platform:0.5.70`]); - - await pruneSupersededImages(REGISTRY, [null, 'latest'], deps); - - expect(deps.docker).not.toHaveBeenCalled(); - }); - - test('an unreachable daemon is a warning, not a failure', async () => { - const deps = fakeDeps([], { listOk: false }); - - const result = await pruneSupersededImages( - REGISTRY, - ['0.5.78', '0.5.77'], - deps, - ); - - expect(result).toEqual({ removed: [], inUse: [], failed: [] }); - expect(deps.logger.warn).toHaveBeenCalledTimes(1); - }); -}); diff --git a/tools/cli/src/lib/docker/prune-superseded-images.ts b/tools/cli/src/lib/docker/prune-superseded-images.ts deleted file mode 100644 index c36cd106ff..0000000000 --- a/tools/cli/src/lib/docker/prune-superseded-images.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { compareVersions, extractVersion } from '../../utils/compare-versions'; -import * as defaultLogger from '../../utils/logger'; -import { docker as defaultDocker } from './docker'; - -interface PruneSupersededImagesDeps { - docker: typeof defaultDocker; - logger: Pick; -} - -export interface PruneSupersededImagesResult { - /** References removed (or, in a dry run, that would be). */ - removed: string[]; - /** References a container still uses; a later deploy removes them. */ - inUse: string[]; - /** References whose removal failed for another reason. */ - failed: string[]; -} - -/** `docker image rm` refuses a reference a container (running or not) uses. */ -const IN_USE = - /being used by|is using its referenced image|conflict: unable to remove/i; - -/** - * Remove the images of versions older than every version `keep` names. - * - * `tale deploy` pulls each image of the new version by its version tag, so the - * versions it replaced keep their own tags: they are not dangling, and no - * prune removed them. Every release left its predecessor's images on the host, - * the sandbox runtime alone about 6 GB unpacked. - * - * Touches only `/tale-*` repositories and only release tags strictly - * older than the oldest kept version, so the version now live, the rollback - * target and an image loaded ahead for a later version all stay. Removal never - * forces: Docker refuses an image a container still uses — a stop-gated - * service left running on an older version, or a sandbox session that started - * before this deploy — and a later deploy removes it once it is free. - * - * Best-effort: a failure is reported and never fails the deploy. - */ -export async function pruneSupersededImages( - registry: string, - keep: readonly (string | null | undefined)[], - { - dryRun = false, - docker = defaultDocker, - logger = defaultLogger, - }: Partial & { dryRun?: boolean } = {}, -): Promise { - const result: PruneSupersededImagesResult = { - removed: [], - inUse: [], - failed: [], - }; - const kept = keep.filter( - (version): version is string => - typeof version === 'string' && extractVersion(version) !== null, - ); - if (kept.length === 0) return result; - const oldestKept = kept.reduce((oldest, version) => - compareVersions(version, oldest) < 0 ? version : oldest, - ); - - const listing = await docker( - 'image', - 'ls', - '--format', - '{{.Repository}}:{{.Tag}}', - ); - if (!listing.success) { - logger.warn( - `Could not list images to remove earlier versions: ${listing.stderr.trim()}`, - ); - return result; - } - - const prefix = `${registry.replace(/\/+$/, '')}/tale-`; - const tagOf = (reference: string) => - reference.slice(reference.lastIndexOf(':') + 1).replace(/^v/, ''); - const older = [ - ...new Set( - listing.stdout - .split('\n') - .map((line) => line.trim()) - .filter((reference) => reference.startsWith(prefix)), - ), - ].filter((reference) => { - const tag = tagOf(reference); - // A release tag: the whole tag is a version, so `latest`, branch and pull - // request tags never match. - if (extractVersion(tag) !== tag) return false; - return compareVersions(tag, oldestKept) < 0; - }); - // Without a distinct rollback target (a first deploy, or a redeploy of the - // live version, which records itself), the newest earlier version stays as - // the fallback a rollback would want. - const distinctKept = new Set( - kept.map((version) => version.replace(/^v/, '')), - ); - const fallback = - distinctKept.size > 1 - ? undefined - : older - .map(tagOf) - .reduce( - (newest, tag) => - newest === undefined || compareVersions(tag, newest) > 0 - ? tag - : newest, - undefined, - ); - const superseded = older.filter((reference) => tagOf(reference) !== fallback); - - for (const reference of superseded) { - if (dryRun) { - result.removed.push(reference); - continue; - } - // One at a time: a deploy host is serving traffic while this runs. - const removal = await docker('image', 'rm', reference); - if (removal.success) result.removed.push(reference); - else if (IN_USE.test(removal.stderr)) result.inUse.push(reference); - else { - result.failed.push(reference); - logger.debug(`Could not remove ${reference}: ${removal.stderr.trim()}`); - } - } - - if (result.removed.length > 0) { - logger.info( - `${dryRun ? 'Would remove' : 'Removed'} ${result.removed.length} image(s) of versions before ${oldestKept}.`, - ); - } - if (result.inUse.length > 0) { - logger.info( - `Kept ${result.inUse.length} earlier image(s) still in use; a later deploy removes them.`, - ); - } - if (result.failed.length > 0) { - logger.warn( - `Could not remove ${result.failed.length} earlier image(s): ${result.failed.join(', ')}`, - ); - } - return result; -} diff --git a/tools/cli/tests/fixtures/exec-bounded.ts b/tools/cli/tests/fixtures/exec-bounded.ts index 7fbca01c76..c97d6e1599 100644 --- a/tools/cli/tests/fixtures/exec-bounded.ts +++ b/tools/cli/tests/fixtures/exec-bounded.ts @@ -77,7 +77,9 @@ if (mode === 'descendant') { try { const result = await exec(process.execPath, ['-e', scripts[mode]!], { silent: true, - timeout: 0.25, + // Only the timeout probe judges a short deadline. The other probes + // need room for the nested runtime to start on a busy CI worker. + timeout: mode === 'timeout' ? 0.25 : 5, maxOutputBytes: 3000, ...(mode === 'stdin' ? { stdin: 'literal $value\n' } : {}), });