diff --git a/.claude/rules/06-api-patterns.md b/.claude/rules/06-api-patterns.md index 83a02b76bc..c660c08f4a 100644 --- a/.claude/rules/06-api-patterns.md +++ b/.claude/rules/06-api-patterns.md @@ -41,6 +41,10 @@ app.use('*', async (c, next) => { Throw `AppError` (from `@simple-agent-manager/worker-core`, re-exported by `middleware/error.ts`) in route handlers — the global `app.onError()` handler catches them. +Expected domain rejections from services also need the `AppError` contract. Preserve +exception names used by recovery callers, and test the real route with the production +`handleAppError` handler plus an unrelated-error control when changing classification. + ## Hono Middleware Scoping (CRITICAL) **NEVER use wildcard `use('/*', ...)` middleware on subrouters that share a base path with other subrouters using different auth models.** Hono's `app.route('/', subRouter)` merges routes — wildcard middleware from one subrouter leaks to ALL sibling subrouters mounted at the same path. diff --git a/.claude/skills/api-reference/SKILL.md b/.claude/skills/api-reference/SKILL.md index 20b17ba79d..783bdeeb5f 100644 --- a/.claude/skills/api-reference/SKILL.md +++ b/.claude/skills/api-reference/SKILL.md @@ -33,7 +33,7 @@ The old `POST /api/sam/chat` inference path is closed: enabled clients receive ` ## Node Management -- `POST /api/nodes` — Create node +- `POST /api/nodes` — Create node (`201`). At the caller's per-person managed workspace-node limit in the selected pool, returns `409 CAPACITY_POOL_NODE_LIMIT` with guidance to delete an idle node or ask the pool owner to raise the limit in Infrastructure; no node is created or provisioning scheduled (`services/nodes.ts:createNodeRecord`, `routes/nodes.ts`). - `GET /api/nodes` — List user's nodes - `GET /api/nodes/:id` — Get node details - `POST /api/nodes/:id/stop` — Stop node diff --git a/apps/api/src/services/nodes.ts b/apps/api/src/services/nodes.ts index 7a9994c5cb..31f55780f8 100644 --- a/apps/api/src/services/nodes.ts +++ b/apps/api/src/services/nodes.ts @@ -3,6 +3,7 @@ import { type CapacityPlacementSnapshot, type CredentialSource, } from '@simple-agent-manager/shared'; +import { AppError } from '@simple-agent-manager/worker-core'; import { drizzle } from 'drizzle-orm/d1'; import * as schema from '../db/schema'; @@ -74,9 +75,14 @@ export interface ProvisionedNode { updatedAt: string; } -export class CapacityPoolNodeLimitExceededError extends Error { +export class CapacityPoolNodeLimitExceededError extends AppError { constructor() { - super('Capacity pool node limit reached'); + super( + 409, + 'CAPACITY_POOL_NODE_LIMIT', + 'Your compute pool has reached its node limit. Delete an idle node or ask the pool owner to raise the limit in Infrastructure.' + ); + // TaskRunner uses this name to release its provisioning lease and wait for capacity. this.name = 'CapacityPoolNodeLimitExceededError'; } } diff --git a/apps/api/tests/unit/durable-objects/task-runner-capacity-exhaustion.test.ts b/apps/api/tests/unit/durable-objects/task-runner-capacity-exhaustion.test.ts index 0dd3b95c84..f238bd0a44 100644 --- a/apps/api/tests/unit/durable-objects/task-runner-capacity-exhaustion.test.ts +++ b/apps/api/tests/unit/durable-objects/task-runner-capacity-exhaustion.test.ts @@ -21,16 +21,21 @@ import type { TaskRunnerContext, TaskRunnerState, } from '../../../src/durable-objects/task-runner/types'; +import { CapacityPoolNodeLimitExceededError } from '../../../src/services/nodes'; // Mock the dynamically-imported service modules. node-steps imports these via // `await import(...)` inside handleNodeProvisioning, so the mocks apply to the // dynamic import too. const createNodeRecord = vi.fn(); const provisionNode = vi.fn(); -vi.mock('../../../src/services/nodes', () => ({ - createNodeRecord: (...args: unknown[]) => createNodeRecord(...args), - provisionNode: (...args: unknown[]) => provisionNode(...args), -})); +vi.mock('../../../src/services/nodes', async (importOriginal) => { + const original = await importOriginal(); + return { + CapacityPoolNodeLimitExceededError: original.CapacityPoolNodeLimitExceededError, + createNodeRecord: (...args: unknown[]) => createNodeRecord(...args), + provisionNode: (...args: unknown[]) => provisionNode(...args), + }; +}); const getRuntimeLimits = vi.fn(() => ({ nodeHeartbeatStaleSeconds: 180 })); vi.mock('../../../src/services/limits', () => ({ @@ -362,9 +367,7 @@ describe('TaskRunner capacity exhaustion', () => { }); it('does not call the provider when the atomic pool insert loses a cross-domain race', async () => { - const poolLimitError = new Error('Capacity pool node limit reached'); - poolLimitError.name = 'CapacityPoolNodeLimitExceededError'; - createNodeRecord.mockRejectedValueOnce(poolLimitError); + createNodeRecord.mockRejectedValueOnce(new CapacityPoolNodeLimitExceededError()); const { DATABASE } = createDbMock({ firstResolver: (sql) => sql.includes('capacity_pool_id = ?') && sql.includes('COUNT(*) AS count') @@ -383,6 +386,51 @@ describe('TaskRunner capacity exhaustion', () => { expect(provisionNode).not.toHaveBeenCalled(); }); + it('releases the provisioning lease and waits after the named pool-limit error', async () => { + createNodeRecord.mockRejectedValueOnce(new CapacityPoolNodeLimitExceededError()); + resolveCredentialSource.mockResolvedValue({ + credentialSource: 'user', + providerName: 'vultr', + }); + const { DATABASE, runCalls } = createDbMock({ + firstResolver: (sql) => { + if (sql.includes('capacity_pool_id = ?') && sql.includes('COUNT(*) AS count')) { + return { count: 2 }; + } + if (sql.includes('FROM vm_provisioning_leases')) { + return { + owner_task_id: 'task-1', + fencing_token: 1, + expires_at: new Date(Date.now() + 60_000).toISOString(), + }; + } + return FALLTHROUGH; + }, + }); + const rc = createContext(DATABASE, { VM_ADMISSION_CONTROL_MODE: 'enforce' }); + const state = createState({ capacityPoolSelection: capacityPoolSelection() }); + + await handleNodeProvisioning(state, rc); + + expect(createNodeRecord).toHaveBeenCalledOnce(); + expect(provisionNode).not.toHaveBeenCalled(); + expect(rc.advanceToStep).not.toHaveBeenCalled(); + expect(runCalls).toContainEqual({ + sql: expect.stringContaining('DELETE FROM vm_provisioning_leases'), + args: [expect.any(String), 'task-1', 1], + }); + expect(state.admissionScopeKey).toBeNull(); + expect(state.admissionLeaseToken).toBeNull(); + expect(rc.updateD1ExecutionStep).toHaveBeenCalledWith('task-1', 'waiting_for_node_capacity'); + expect(rc.ctx.storage.setAlarm).toHaveBeenCalledWith(expect.any(Number)); + expect( + runCalls.some( + (call) => + call.sql.includes("SET state = 'waiting'") && call.args[0] === 'capacity_pool_node_limit' + ) + ).toBe(true); + }); + it('does not provision through legacy fallback when the selected pool has no candidates', async () => { const { DATABASE } = createDbMock({}); const rc = createContext(DATABASE); diff --git a/apps/api/tests/unit/routes/nodes-pool-node-limit.test.ts b/apps/api/tests/unit/routes/nodes-pool-node-limit.test.ts new file mode 100644 index 0000000000..0b7235b36a --- /dev/null +++ b/apps/api/tests/unit/routes/nodes-pool-node-limit.test.ts @@ -0,0 +1,178 @@ +import type { CapacityPlacementSnapshot } from '@simple-agent-manager/shared'; +import Database from 'better-sqlite3'; +import { Hono } from 'hono'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import * as schema from '../../../src/db/schema'; +import type { Env } from '../../../src/env'; +import { handleAppError } from '../../../src/middleware/app-error-handler'; +import { AppError } from '../../../src/middleware/error'; +import { nodesRoutes } from '../../../src/routes/nodes'; +import { resolveCanonicalVmAllocationPlan } from '../../../src/services/canonical-vm-allocation'; +import { scheduleDirectProvisioning } from '../../../src/services/direct-provisioning'; +import { CapacityPoolNodeLimitExceededError, createNodeRecord } from '../../../src/services/nodes'; +import { recordNodeRoutingMetric } from '../../../src/services/telemetry'; +import { applySqliteMigration, createSchemaTables, createSqliteD1 } from '../../helpers/sqlite-d1'; + +vi.mock('../../../src/middleware/auth', () => ({ + getUserId: () => 'user-1', + requireAuth: () => async (_c: unknown, next: () => Promise) => next(), + requireApproved: () => async (_c: unknown, next: () => Promise) => next(), +})); + +// Placement selection is upstream of the insert under test. Keep the real node +// service, ORM, shipped SQLite trigger and production error handler composed. +vi.mock('../../../src/services/canonical-vm-allocation', () => ({ + resolveCanonicalVmAllocationPlan: vi.fn(), +})); +vi.mock('../../../src/services/direct-provisioning', () => ({ + scheduleDirectProvisioning: vi.fn().mockResolvedValue(undefined), +})); +vi.mock('../../../src/services/telemetry', () => ({ recordNodeRoutingMetric: vi.fn() })); + +const snapshot: CapacityPlacementSnapshot = { + capacityPoolId: 'pool-1', + capacityPoolScope: 'user', + capacityPoolRevision: 1, + capacitySourceId: 'source-1', + capacityPoolCandidateId: 'candidate-1', + placementCredentialSource: 'user', + placementCredentialReference: 'credentials:credential-1', + placementCredentialVersion: 1, + capacityPoolProjectId: null, + workloadRole: 'workspace', +}; + +describe('POST /api/nodes pool node limit — real insert and production error handler', () => { + let sqlite: Database.Database; + let env: Env; + let app: Hono<{ Bindings: Env }>; + + beforeEach(() => { + vi.clearAllMocks(); + sqlite = new Database(':memory:'); + createSchemaTables(sqlite, [schema.nodes, schema.capacityPools]); + // Reapply the shipped migration, including its default and atomic trigger. + sqlite.exec('ALTER TABLE capacity_pools DROP COLUMN max_nodes'); + applySqliteMigration( + sqlite, + new URL('../../../src/db/migrations/0167_capacity_pool_max_nodes.sql', import.meta.url) + ); + sqlite.exec("INSERT INTO capacity_pools (id, max_nodes) VALUES ('pool-1', 1)"); + env = { DATABASE: createSqliteD1(sqlite), MAX_NODES_PER_USER: '10' } as Env; + vi.mocked(resolveCanonicalVmAllocationPlan).mockResolvedValue({ + vmSize: 'small', + vmLocation: 'fsn1', + effectiveProvider: 'hetzner', + credentialAttributionUserId: 'user-1', + credentialAttributionProjectId: null, + credentialAttributionSource: 'user', + quotaCredentialSource: 'user', + capacityPlacementSnapshot: snapshot, + } as Awaited>); + app = new Hono<{ Bindings: Env }>(); + app.onError(handleAppError); + app.route('/api/nodes', nodesRoutes); + }); + + afterEach(() => sqlite.close()); + + function postNode(): Promise { + return app.request( + '/api/nodes', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ name: 'new-node' }), + }, + env + ); + } + + async function fillPool(): Promise { + await createNodeRecord(env, { + userId: 'user-1', + name: 'existing-node', + vmSize: 'small', + vmLocation: 'fsn1', + heartbeatStaleAfterSeconds: 180, + capacityPlacementSnapshot: snapshot, + }); + } + + function nodeCount(): number { + return (sqlite.prepare('SELECT COUNT(*) AS count FROM nodes').get() as { count: number }).count; + } + + it('returns actionable 409 JSON at max_nodes without scheduling provisioning or inserting a node', async () => { + await fillPool(); + + const response = await postNode(); + + expect(response.status).toBe(409); + expect(response.headers.get('Content-Type')).toContain('application/json'); + expect(await response.json()).toEqual({ + error: 'CAPACITY_POOL_NODE_LIMIT', + message: + 'Your compute pool has reached its node limit. Delete an idle node or ask the pool owner to raise the limit in Infrastructure.', + }); + expect(resolveCanonicalVmAllocationPlan).toHaveBeenCalledOnce(); + expect(nodeCount()).toBe(1); + expect(scheduleDirectProvisioning).not.toHaveBeenCalled(); + expect(recordNodeRoutingMetric).not.toHaveBeenCalled(); + }); + + it('converts the real trigger error through the ORM cause chain to the named AppError', async () => { + await fillPool(); + const error = await createNodeRecord(env, { + userId: 'user-1', + name: 'rejected', + vmSize: 'small', + vmLocation: 'fsn1', + heartbeatStaleAfterSeconds: 180, + capacityPlacementSnapshot: snapshot, + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(CapacityPoolNodeLimitExceededError); + expect(error).toBeInstanceOf(AppError); + expect(error).toMatchObject({ + name: 'CapacityPoolNodeLimitExceededError', + statusCode: 409, + error: 'CAPACITY_POOL_NODE_LIMIT', + }); + expect(nodeCount()).toBe(1); + }); + + it('creates and schedules a node below max_nodes, then rejects the next request', async () => { + const response = await postNode(); + expect(response.status).toBe(201); + const created = (await response.json()) as { id: string; status: string }; + expect(created.status).toBe('creating'); + expect(nodeCount()).toBe(1); + expect(scheduleDirectProvisioning).toHaveBeenCalledExactlyOnceWith(env, { + nodeId: created.id, + userId: 'user-1', + }); + + expect((await postNode()).status).toBe(409); + expect(nodeCount()).toBe(1); + expect(scheduleDirectProvisioning).toHaveBeenCalledOnce(); + }); + + it('keeps unrelated insert failures as redacted 500 errors without provisioning', async () => { + sqlite.exec(`CREATE TRIGGER unrelated_insert_failure BEFORE INSERT ON nodes + BEGIN SELECT RAISE(ABORT, 'unrelated_database_failure'); END`); + + const response = await postNode(); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ + error: 'INTERNAL_ERROR', + message: 'Internal server error', + requestId: expect.any(String), + }); + expect(nodeCount()).toBe(0); + expect(scheduleDirectProvisioning).not.toHaveBeenCalled(); + expect(recordNodeRoutingMetric).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/www/src/content/docs/docs/reference/api.md b/apps/www/src/content/docs/docs/reference/api.md index 97b5ec0057..fcbe58f474 100644 --- a/apps/www/src/content/docs/docs/reference/api.md +++ b/apps/www/src/content/docs/docs/reference/api.md @@ -681,6 +681,16 @@ Comment threads and replies accept an optional `mentions: [{ "userId": "..." }]` ## Nodes +### `POST /api/nodes` + +Create a node for the authenticated user. Returns `201` when creation is scheduled. +If the caller has reached the selected compute pool's per-person limit for managed +workspace nodes, returns `409` with +`error: "CAPACITY_POOL_NODE_LIMIT"`. Delete an idle node or ask the pool owner to +raise the limit in Infrastructure, then retry. A rejected request does not create +a node or schedule provisioning (`apps/api/src/services/nodes.ts:createNodeRecord`, +`apps/api/src/routes/nodes.ts`, `apps/api/src/middleware/app-error-handler.ts:handleAppError`). + ### `GET /api/nodes` List all nodes for the authenticated user. diff --git a/tasks/archive/2026-11-17-pool-node-limit-http-conflict.md b/tasks/archive/2026-11-17-pool-node-limit-http-conflict.md new file mode 100644 index 0000000000..73a74316cf --- /dev/null +++ b/tasks/archive/2026-11-17-pool-node-limit-http-conflict.md @@ -0,0 +1,129 @@ +# Pool node limit returns an actionable HTTP conflict + +## Problem and scope + +External reporter leonceaklin observed HTTP 500 when creating a node at a compute pool's +`max_nodes` on self-hosted Infomaniak. Fix #2844 with a **draft PR only** against main. +Do not mark ready, merge, deploy to production, or create GitHub issues. Keep unrelated +credential and ACP fixes in the reporter's fork out of scope. + +## Research and preflight + +- Base: `e5c5aa4f77e6adf389a24b25b9470a69c24acbff`. +- Classification: cross-component-change, business-logic-change, public-surface-change, + docs-sync-change. No external service contract or new configuration changes. +- `0167_capacity_pool_max_nodes.sql` atomically raises `capacity_pool_node_limit` at + insertion. Keep this final enforcement and its counting semantics unchanged. +- `services/nodes.ts:createNodeRecord` walks wrapped DB errors and throws + `CapacityPoolNodeLimitExceededError`, currently a plain Error. +- `routes/nodes.ts:POST /api/nodes` awaits that insert before routing telemetry and + `scheduleDirectProvisioning`. `middleware/app-error-handler.ts:handleAppError` maps + AppError to its public JSON/status, otherwise redacts to 500 INTERNAL_ERROR. +- Use the shared worker-core AppError (already re-exported by middleware/error), with + 409 / CAPACITY_POOL_NODE_LIMIT. Guidance must work for pool members without edit rights. +- `task-runner/node-provisioning-step.ts` matches the exception's **name**, releases its + admission lease and delegates to `waitOrThrowForCapacityPoolNodeLimit`. Preserve this. +- Other createNodeRecord callers include workspace creation, Instant placement, + deployment placement and provisioning infrastructure. They inherit structured AppError + behavior without new per-route handling or changes to allocation enforcement. +- Existing route tests often supply their own error handler, leaving the production + composition untested. Add a real-route/real-handler regression and use shipped trigger + SQL with the existing SQLite-backed D1 adapter. Related lesson: rule 72's unreachable + classifier and rule 62's real-trigger requirement. +- Principles II/IV/X/XI/XIII: discriminating tests first, actionable error, minimal + subclass change, no new tunables, fail before provider work. +- SAM supplies the isolated output branch/workspace. Keep task documentation here on + the feature branch so this draft-only task never pushes main or triggers production. + +## Implementation checklist + +- [x] Add POST /api/nodes tests using production handleAppError, real createNodeRecord, + Drizzle and shipped 0167 trigger; assert 409/code/message, unchanged row count and no + scheduling/provider work, successful under-limit control, unrelated failures remain 500. +- [x] Pin real service DB-trigger conversion and exception identity; test nested DB cause. +- [x] Exercise actual exception class in task-runner capacity waiting and fail policies; + assert lease release, waiting alarm/state, and no provider call. +- [x] Run new regression tests on pre-fix code and record expected failure. +- [x] Extend the exception from shared AppError; preserve its name and DB classification. +- [x] Update API reference documentation and regression guidance. +- [x] Run relevant lint/typecheck/test/build and full CI while PR stays draft. +- [x] Complete specialist, test, documentation, constitution and implementation-completion reviews. +- [x] Verify on staging, clean up fixtures and release lease; no production deployment. +- [x] Publish draft PR with Closes #2844, reporter/fork credit, validation and review evidence; + file nonblocking human-review inbox item and complete SAM task with PR URL. + +## Acceptance criteria + +1. A node insert rejected at the pool limit responds HTTP 409, JSON code + CAPACITY_POOL_NODE_LIMIT and safe actionable guidance through the production handler. +2. Rejection writes no node and schedules no provisioning. Pool enforcement stays intact. +3. Unrelated failures remain redacted 500 INTERNAL_ERROR; under-limit creation still succeeds. +4. Task-runner lease release and existing waiting/fail policies work with the actual class. +5. Delivery remains draft against main, with attribution and a nonblocking review inbox item. + +## References + +- https://github.com/raphaeltm/simple-agent-manager/issues/2844 +- https://github.com/zebra-pig/simple-agent-manager/pull/9 (evidence only; unrelated fixes excluded) +- SAM idea `01M7MBNVA0XMH3YCZJPAD20J2M`; task `01M7MBPJ6H0GDWE95E6K67C656`. + +## Post-mortem + +The user-visible failure was a 500 for an expected configured capacity rejection. The +domain exception did not implement the API error contract, so the global handler treated +it as an internal failure. Existing quota and trigger tests did not compose the route, +service conversion and production handler. Regression coverage at that boundary prevents +recurrence; relevant regression guidance is updated with this fix. + +## Validation evidence + +- Baseline root lint/typecheck passed. +- TDD: 3 expected pre-fix failures and 37 passing controls across 2 files; after fix, + 40 tests pass. Each independent Cloudflare and test reviewer reran all 40 successfully. +- Cloudflare, constitution and test specialist reviews PASS. Doc review refinements + addressed: per-person scope described accurately, code paths cited, historical specs left alone. +- Instruction context-budget check passed. Root lint/typecheck/build passed; root API test + timeouts passed on a single-worker rerun (121/121 including the regressions). +- Safe main merged at `14beb3ae7`; the bug source and tests are unchanged. Post-main + regression rerun passed 40/40; API lint/typecheck and secret-handling guard passed. +- Full CI passed on that head: https://github.com/raphaeltm/simple-agent-manager/actions/runs/44125339898. +- Draft PR https://github.com/raphaeltm/simple-agent-manager/pull/2850 remains open against main. + Live staging, fixture cleanup and lease release are verified. Nonblocking owner-review inbox item: `ask:01M7NNRMXRBG3GZ7K3AAE3KMNJ`. + +## Live staging evidence + +- Normal staging2 workflow: https://github.com/raphaeltm/simple-agent-manager/actions/runs/44171771911. + Cloudflare API version `fa34afe8-34b2-4cc0-85f4-4bb5f4fbb17c` is tagged with tested + commit `14beb3ae7e2ae9f5e4be80e2bf63b6828d694b32` at 100%; the shipped + `trg_nodes_capacity_pool_max_nodes` trigger is present in D1. +- Authenticated Playwright opened the app and verified pool/node reads. Temporarily set + only the test user's owned pool from maxNodes 3 to 1. One GCP e2-medium fixture returned + HTTP 201 and reached running; the next distinct-name POST returned HTTP 409, + CAPACITY_POOL_NODE_LIMIT and the exact actionable guidance. +- Read-only D1 assertions found exactly one fixture row and no rejected-attempt row. + Owner DELETE returned HTTP 200 after strict provider termination; a final D1 check + confirms the fixture row is absent. No provider or enforcement code changed. +- Restored personal maxNodes 3; installation maxNodes 2 and the preexisting sleeping + NULL-pool node remain unchanged. Signed out and verified session revocation; private + authentication files removed. The complete deployment workflow, including smoke tests, succeeded. +- Lease release https://github.com/raphaeltm/simple-agent-manager/actions/runs/44176820626 + succeeded; a fresh queue read confirmed no lease holder and the next task’s turn. + Sent that task the early-release notice. No production deployment occurred. + +## Task Completion Validation Report + +Task: this file. Branch: `sam/fix-verified-github-bug-67c656`. Date: 2026-11-17. +Verdict: **PASS**. No uncovered research findings or acceptance criteria; no findings remain. + +| Check | Status | Evidence | +| ----------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| A: Research → Checklist | PASS | Error contract, name compatibility, production handler/trigger composition and docs all have completed items. | +| B: Checklist → Diff | PASS | Minimal service subclass, two regression files, two API references and regression rule are in the seven-file PR diff; CI/review/staging evidence is recorded above. | +| C: Criteria → Tests | PASS | Criteria 1–3: real POST/ORM/trigger/handler tests and live 201→409/no-row verification. Criterion 4: actual-class TaskRunner wait/fail/lease tests. Criterion 5: draft/open/main PR, attribution/closing text and nonblocking inbox verified. | +| D: UI → Backend | N/A | No UI inputs changed. | +| E: Multi-Resource | N/A | No provider/resource selection changed. | +| F: Vertical Slice | PASS | Route-to-real-SQLite-trigger-to-production-handler regression, unrelated-error control, plus deployed Worker/D1 and one real provider fixture. | + +Full CI and staging tested `14beb3ae7e2ae9f5e4be80e2bf63b6828d694b32`. +The final follow-up commit only records this evidence; production code and tests are unchanged. +This task file remains active until the owner confirms completion; no archive, readiness or merge is authorized.