From 36302e7a9dc61a708769e2dccc187c6ce20a22ba Mon Sep 17 00:00:00 2001 From: Emil Pobinger <33319340+candlelightner@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:30:21 +0200 Subject: [PATCH 1/4] Prevent stale main builds from regressing shared image tags Serialize current-head promotion for both images while retaining immutable commit manifests and existing release tags. Cover reverse completion and publication boundaries. Co-authored-by: Codex --- .github/workflows/docker-build.yml | 57 +++++++++++++- docs/image-publication.md | 30 ++++++++ scripts/promote-main-image.sh | 23 ++++++ tests/api/docker-build-filter.spec.ts | 9 ++- tests/helpers/test_main_image_promotion.py | 90 ++++++++++++++++++++++ 5 files changed, 204 insertions(+), 5 deletions(-) create mode 100644 docs/image-publication.md create mode 100644 scripts/promote-main-image.sh create mode 100644 tests/helpers/test_main_image_promotion.py diff --git a/.github/workflows/docker-build.yml b/.github/workflows/docker-build.yml index a1bfa37d..291a0675 100644 --- a/.github/workflows/docker-build.yml +++ b/.github/workflows/docker-build.yml @@ -39,9 +39,11 @@ jobs: - 'scripts/incus-canary.mjs' - '.dockerignore' - '.github/workflows/docker-build.yml' + - 'scripts/promote-main-image.sh' worker: - 'worker/**' - '.github/workflows/docker-build.yml' + - 'scripts/promote-main-image.sh' validation: - 'orchestrator/**' - 'worker/**' @@ -52,6 +54,7 @@ jobs: - 'scripts/agentor-incus-network-service.py' - 'scripts/setup-incus-host.sh' - 'scripts/profile-ci-workflow.py' + - 'scripts/promote-main-image.sh' - '.dockerignore' - 'tests/**' - 'docker-compose.tests.yml' @@ -366,11 +369,11 @@ jobs: with: images: ${{ env.REGISTRY }}/${{ github.repository_owner }}/agentor-orchestrator tags: | - type=ref,event=branch + type=ref,event=branch,enable=${{ github.ref != 'refs/heads/main' }} type=semver,pattern={{version}} type=semver,pattern={{major}}.{{minor}} type=sha - type=raw,value=latest,enable={{is_default_branch}} + type=sha,format=long - run: | cd /tmp/digests @@ -468,11 +471,11 @@ jobs: with: images: ${{ env.REGISTRY }}/${{ github.repository_owner }}/agentor-worker tags: | - type=ref,event=branch + type=ref,event=branch,enable=${{ github.ref != 'refs/heads/main' }} type=semver,pattern={{version}} type=semver,pattern={{major}}.{{minor}} type=sha - type=raw,value=latest,enable={{is_default_branch}} + type=sha,format=long - run: | cd /tmp/digests @@ -480,3 +483,49 @@ jobs: TAGS=$(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") SOURCES=$(for f in *; do echo "$IMAGE@$(cat $f)"; done) docker buildx imagetools create $TAGS $SOURCES + + promote-main: + name: Promote main (${{ matrix.image }}) + needs: [merge-orchestrator, merge-worker] + if: >- + always() && github.ref == 'refs/heads/main' && + github.event_name != 'pull_request' && + (needs.merge-orchestrator.result == 'success' || needs.merge-worker.result == 'success') + strategy: + fail-fast: false + matrix: + include: + - image: agentor-orchestrator + merge-result: ${{ needs.merge-orchestrator.result }} + - image: agentor-worker + merge-result: ${{ needs.merge-worker.result }} + # Keep the freshness check and both shared tags under the same per-image lock. + concurrency: + group: main-image-promotion-${{ github.repository }}-${{ matrix.image }} + cancel-in-progress: false + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + steps: + - uses: actions/checkout@v4 + if: matrix.merge-result == 'success' + with: + persist-credentials: false + + - uses: docker/setup-buildx-action@v3 + if: matrix.merge-result == 'success' + + - uses: docker/login-action@v3 + if: matrix.merge-result == 'success' + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Promote only the current main revision + if: matrix.merge-result == 'success' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + IMAGE: ${{ env.REGISTRY }}/${{ github.repository_owner }}/${{ matrix.image }} + run: bash scripts/promote-main-image.sh diff --git a/docs/image-publication.md b/docs/image-publication.md new file mode 100644 index 00000000..bb5c6ce1 --- /dev/null +++ b/docs/image-publication.md @@ -0,0 +1,30 @@ +# Image publication + +Orchestrator and worker builds publish multi-platform manifests only after the +CI test gate. Pull requests build without registry login or publication. Release +tags retain their existing version and major/minor tags. + +Each successful merge publishes `sha-` before shared-tag +promotion. The existing short SHA tags remain available for compatibility; +use the full SHA reference for commit-specific deployments. + +Main promotion uses a separate job with a per-image concurrency group and +`cancel-in-progress: false`. The lock covers the main HEAD check and the single +manifest command that updates `main` and `latest`. An older run finishing after +a newer run cannot move either shared tag back to its older revision. Pending +promotion jobs may be replaced by GitHub concurrency scheduling, but immutable +SHA publication has already completed outside that lock. + +A run whose commit is no longer main HEAD skips shared tags and reports that +its SHA references remain available. This also applies when a newer commit only +changes unrelated files: shared tags stay on the previously promoted image until +a current-head image build succeeds (a manual main run builds both images). +If the HEAD lookup fails, promotion fails closed with a bounded reason; it does +not affect the already published SHA references. Registry failures may partially +update shared tags; rerun the current main workflow to recover. + +Run the registry-free reverse-completion regression with: + +```sh +python3 -m unittest discover -s tests/helpers -p test_main_image_promotion.py +``` diff --git a/scripts/promote-main-image.sh b/scripts/promote-main-image.sh new file mode 100644 index 00000000..f1fa500b --- /dev/null +++ b/scripts/promote-main-image.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# Caller must hold the workflow's per-image promotion concurrency lock. +set -euo pipefail +phase='checking the current main revision' +trap 'printf "[image-promotion] Failed while %s; shared-tag promotion stopped, published SHA references retained.\n" "$phase" >&2' ERR +: "${GITHUB_REPOSITORY:?}" "${GITHUB_SHA:?}" "${GITHUB_REF:?}" "${IMAGE:?}" +if [[ "$GITHUB_REF" != refs/heads/main || ! "$GITHUB_SHA" =~ ^[0-9a-f]{40}$ ]]; then + echo '[image-promotion] Invalid main revision context; promotion stopped, published SHA references retained.' >&2 + exit 1 +fi +head_sha=$(gh api "repos/$GITHUB_REPOSITORY/git/ref/heads/main" --jq '.object.sha') +if [[ ! "$head_sha" =~ ^[0-9a-f]{40}$ ]]; then + echo '[image-promotion] Invalid main head response; promotion stopped, published SHA references retained.' >&2 + exit 1 +fi +# A newer revision may have passed its build while this run was waiting. +if [[ "$head_sha" != "$GITHUB_SHA" ]]; then + echo '[image-promotion] Run is no longer main HEAD; main/latest promotion skipped, published SHA references retained.' + exit 0 +fi +phase='promoting main/latest from the full commit reference' +docker buildx imagetools create --tag "$IMAGE:main" --tag "$IMAGE:latest" "$IMAGE:sha-$GITHUB_SHA" +echo '[image-promotion] Current main revision promoted to main/latest; published SHA references retained.' diff --git a/tests/api/docker-build-filter.spec.ts b/tests/api/docker-build-filter.spec.ts index 22355cff..add2f0d6 100644 --- a/tests/api/docker-build-filter.spec.ts +++ b/tests/api/docker-build-filter.spec.ts @@ -2,6 +2,7 @@ import { test, expect } from '@playwright/test'; import { readFile } from 'node:fs/promises'; import { matchesGlob } from 'node:path'; import { createRequire } from 'node:module'; +import { execFileSync } from 'node:child_process'; const { parse } = createRequire(new URL('../../orchestrator/package.json', import.meta.url))('yaml'); async function filters(): Promise> { @@ -27,7 +28,9 @@ test('dependency detection stays narrow and preserves independent worker builds' const config = await filters(); for (const path of ['docs/testing.md', 'scripts/unrelated-helper.sh']) for (const scope of ['orchestrator', 'validation']) expect(config[scope]!.some(pattern => matchesGlob(path, pattern))).toBe(false); - expect(config.worker).toEqual(['worker/**', '.github/workflows/docker-build.yml']); + expect(config.worker).toEqual(['worker/**', '.github/workflows/docker-build.yml', 'scripts/promote-main-image.sh']); + for (const scope of ['orchestrator', 'worker', 'validation']) + expect(config[scope]!.includes('scripts/promote-main-image.sh')).toBe(true); for (const path of ['scripts/incus-admin-network-policy.py', 'scripts/setup-incus-host.sh', 'scripts/profile-ci-workflow.py']) { expect(config.validation!.some(pattern => matchesGlob(path, pattern))).toBe(true); expect(config.orchestrator!.some(pattern => matchesGlob(path, pattern))).toBe(false); @@ -52,3 +55,7 @@ test('regression runner uses current source and publication still requires valid expect(workflow.jobs[`build-${image}`].if).toContain("needs.test_gate.result == 'success'"); } }); + +test('main promotion rejects stale runs for both images and retains publication boundaries', () => { + execFileSync('python3', [new URL('../helpers/test_main_image_promotion.py', import.meta.url).pathname], { timeout: 30_000 }); +}); diff --git a/tests/helpers/test_main_image_promotion.py b/tests/helpers/test_main_image_promotion.py new file mode 100644 index 00000000..a2c99f60 --- /dev/null +++ b/tests/helpers/test_main_image_promotion.py @@ -0,0 +1,90 @@ +"""Exercise shared-tag promotion without registry credentials or publication.""" +import json +import os +import re +from pathlib import Path +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] +SCRIPT = ROOT / 'scripts/promote-main-image.sh' +OLD = '1' * 40 +NEW = '2' * 40 + + +class MainImagePromotionTests(unittest.TestCase): + def test_reverse_completion_retains_both_sha_images(self): + for image in ('agentor-orchestrator', 'agentor-worker'): + with self.subTest(image=image), tempfile.TemporaryDirectory() as directory: + temp = Path(directory) + (temp / 'gh').write_text('#!/bin/sh\nprintf "%s\\n" "$MAIN_HEAD"\n') + (temp / 'docker').write_text('''#!/usr/bin/env python3 +import json, os, sys +from pathlib import Path +path = Path(os.environ['REGISTRY_STATE']) +state = json.loads(path.read_text()) +args = sys.argv[1:] +assert args[:3] == ['buildx', 'imagetools', 'create'], args +source = args[-1] +assert source in state, source +for index, value in enumerate(args): + if value == '--tag': + state[args[index + 1]] = state[source] +path.write_text(json.dumps(state)) +''') + for name in ('gh', 'docker'): + (temp / name).chmod(0o755) + image_ref = f'ghcr.io/example/{image}' + state_file = temp / 'registry.json' + immutable = {f'{image_ref}:sha-{sha}': f'manifest-{sha}' for sha in (OLD, NEW)} + state_file.write_text(json.dumps(immutable)) + env = dict(os.environ, PATH=f'{temp}:{os.environ["PATH"]}', + GITHUB_REPOSITORY='example/project', GITHUB_REF='refs/heads/main', + IMAGE=image_ref, MAIN_HEAD=NEW, REGISTRY_STATE=str(state_file)) + for sha, outcome in ((NEW, 'promoted to main/latest'), (OLD, 'promotion skipped')): + result = subprocess.run(['bash', str(SCRIPT)], env=dict(env, GITHUB_SHA=sha), + text=True, capture_output=True) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn(outcome, result.stdout) + self.assertIn('SHA references retained', result.stdout) + state = json.loads(state_file.read_text()) + for tag in ('main', 'latest'): + self.assertEqual(state[f'{image_ref}:{tag}'], f'manifest-{NEW}') + self.assertEqual({key: state[key] for key in immutable}, immutable) + + def test_unreadable_main_stops_before_publication(self): + with tempfile.TemporaryDirectory() as directory: + temp = Path(directory) + (temp / 'gh').write_text('#!/bin/sh\nexit 1\n') + (temp / 'gh').chmod(0o755) + result = subprocess.run(['bash', str(SCRIPT)], text=True, capture_output=True, + env=dict(os.environ, PATH=f'{temp}:{os.environ["PATH"]}', + GITHUB_REPOSITORY='example/project', + GITHUB_REF='refs/heads/main', GITHUB_SHA=NEW, + IMAGE='ghcr.io/example/agentor-worker')) + self.assertNotEqual(result.returncode, 0) + self.assertIn('promotion stopped', result.stderr) + + def test_workflow_keeps_immutable_merge_outside_promotion_lock(self): + workflow = (ROOT / '.github/workflows/docker-build.yml').read_text() + for component in ('orchestrator', 'worker'): + # Read the whole job, excluding subsequent top-level job declarations. + merge = re.split(r'\n [a-z][a-z-]*:\n', workflow.split(f' merge-{component}:\n', 1)[1])[0] + self.assertNotIn('concurrency:', merge) + self.assertIn('type=sha,format=long', merge) + self.assertIn('type=semver,pattern={{version}}', merge) + self.assertIn('type=semver,pattern={{major}}.{{minor}}', merge) + self.assertIn("type=ref,event=branch,enable=${{ github.ref != 'refs/heads/main' }}", merge) + self.assertNotIn('value=latest', merge) + promotion = workflow.split(' promote-main:\n', 1)[1] + self.assertIn('group: main-image-promotion-${{ github.repository }}-${{ matrix.image }}', promotion) + self.assertIn('cancel-in-progress: false', promotion) + self.assertIn("github.ref == 'refs/heads/main'", promotion) + self.assertIn("github.event_name != 'pull_request'", promotion) + self.assertIn('bash scripts/promote-main-image.sh', promotion) + self.assertIn('needs.test_gate.result == \'success\'', workflow) + + +if __name__ == '__main__': + unittest.main() From 3bfb6e3b38ef15cb05da478ad088da10e48dc2d3 Mon Sep 17 00:00:00 2001 From: Emil Pobinger <33319340+candlelightner@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:30:26 +0200 Subject: [PATCH 2/4] Handle unavailable worker panes without error floods or stale polling Keep stopped and unknown compute distinct, discard probes from older lifecycle generations, and suspend or back off pane discovery using verified shared inventory. Co-authored-by: Codex --- docs/pane-lifecycle.md | 17 ++ orchestrator/app/composables/useTmuxTabs.ts | 62 ++++--- .../api/containers/[id]/panes/index.get.ts | 4 +- orchestrator/server/utils/container.ts | 38 +++- tests/api/pane-lifecycle.spec.ts | 162 ++++++++++++++++++ tests/playwright.modules.config.ts | 1 + 6 files changed, 245 insertions(+), 39 deletions(-) create mode 100644 docs/pane-lifecycle.md create mode 100644 tests/api/pane-lifecycle.spec.ts diff --git a/docs/pane-lifecycle.md b/docs/pane-lifecycle.md new file mode 100644 index 00000000..07ec63ed --- /dev/null +++ b/docs/pane-lifecycle.md @@ -0,0 +1,17 @@ +# Pane discovery during worker lifecycle changes + +`GET /api/containers/:id/panes` requires the same authenticated ownership checks +as before. It executes guest commands only for confirmed running compute without +an unsettled lifecycle operation. + +A confirmed stopped worker returns HTTP 409. Unknown/unresponsive or changing +compute returns HTTP 503. Both include `data.code: WORKER_PANES_UNAVAILABLE` and +the observed `data.status`; desired stopped intent alone is not proof of a stop. +Missing workers return 404. An expected lifecycle rejection never changes stopped +state into unknown, and delayed probes cannot overwrite newer lifecycle state. + +The GUI uses the shared worker inventory to suspend discovery when compute is +not confirmed running. Failed discovery backs off from six seconds to at most +48 seconds, without overlapping periodic requests. A verified transition back +to running resumes discovery immediately. Closing a pane cancels its polling, +including after a late response. diff --git a/orchestrator/app/composables/useTmuxTabs.ts b/orchestrator/app/composables/useTmuxTabs.ts index ddd746fc..8cab3415 100644 --- a/orchestrator/app/composables/useTmuxTabs.ts +++ b/orchestrator/app/composables/useTmuxTabs.ts @@ -1,8 +1,10 @@ -import type { TmuxWindow } from '~/types'; +import type { ContainerInfo, TmuxWindow } from '~/types'; const POLL_INTERVAL = 3000; export function useTmuxTabs(containerId: Ref) { + const { data: workers } = useNuxtData('workers'); + const available = computed(() => workers.value?.some(worker => worker.id === containerId.value && worker.status === 'running') ?? false); const { getTmuxActiveWindow, setTmuxActiveWindow } = useUiState(); const windows = ref([]); const activeWindowIndex = ref(null); @@ -11,14 +13,18 @@ export function useTmuxTabs(containerId: Ref) { let pollTimer: ReturnType | null = null; let fetchGeneration = 0; + let destroyed = false; + let pollGeneration = 0; + let failures = 0; async function fetchWindows() { + if (destroyed || !available.value) return false; const currentGeneration = ++fetchGeneration; try { - const data = await $fetch(`/api/containers/${containerId.value}/panes`); + const data = await $fetch(`/api/containers/${containerId.value}/panes`, { retry: 0 }); // Discard stale response if containerId changed during fetch - if (currentGeneration !== fetchGeneration) return; + if (destroyed || !available.value || currentGeneration !== fetchGeneration) return false; windows.value = data; @@ -29,42 +35,34 @@ export function useTmuxTabs(containerId: Ref) { // Auto-select first window when nothing is active if (activeWindowIndex.value == null && data.length > 0) { - activeWindowIndex.value = data[0]!.index; + const saved = getTmuxActiveWindow(containerId.value); + activeWindowIndex.value = data.some(window => window.index === saved) ? saved! : data[0]!.index; } // Persist for reopen if (activeWindowIndex.value != null) { setTmuxActiveWindow(containerId.value, activeWindowIndex.value); } + return true; } catch { - // Container may be stopped or removed - } - } - - async function init() { - await fetchWindows(); - - // Restore last active window if it still exists - const saved = getTmuxActiveWindow(containerId.value); - if (saved != null && windows.value.some((w) => w.index === saved)) { - activeWindowIndex.value = saved; - } else if (windows.value.length > 0 && activeWindowIndex.value == null) { - activeWindowIndex.value = windows.value[0]!.index; + return false; } - - startPolling(); } - function startPolling() { - stopPolling(); - pollTimer = setInterval(() => fetchWindows(), POLL_INTERVAL); + async function poll() { + const generation = pollGeneration; + const succeeded = await fetchWindows(); + if (destroyed || !available.value || generation !== pollGeneration) return; + failures = succeeded ? 0 : Math.min(failures + 1, 4); + // Expected unavailable responses back off; inventory must still confirm running. + pollTimer = setTimeout(poll, POLL_INTERVAL * 2 ** failures); } function stopPolling() { - if (pollTimer) { - clearInterval(pollTimer); - pollTimer = null; - } + pollGeneration++; + fetchGeneration++; + if (pollTimer) clearTimeout(pollTimer); + pollTimer = null; } async function createWindow(name?: string, lockPassword?: string): Promise { @@ -124,19 +122,17 @@ export function useTmuxTabs(containerId: Ref) { } function destroy() { + destroyed = true; stopPolling(); } - // Re-init when containerId changes - watch(containerId, () => { + watch([containerId, available], () => { stopPolling(); windows.value = []; activeWindowIndex.value = null; - init(); - }); - - // Start on creation - init(); + failures = 0; + if (!destroyed && available.value) void poll(); + }, { immediate: true }); return { windows, diff --git a/orchestrator/server/api/containers/[id]/panes/index.get.ts b/orchestrator/server/api/containers/[id]/panes/index.get.ts index 05cdeafd..ec9ec057 100644 --- a/orchestrator/server/api/containers/[id]/panes/index.get.ts +++ b/orchestrator/server/api/containers/[id]/panes/index.get.ts @@ -2,10 +2,12 @@ defineRouteMeta({ openAPI: { tags: ['Tmux'], summary: 'List tmux windows', - description: 'Returns all tmux windows in the container session.', + description: 'Returns tmux windows only for confirmed running compute. A stopped worker returns 409; unknown, unresponsive, or changing compute returns 503 with WORKER_PANES_UNAVAILABLE. Refresh inventory before retrying.', operationId: 'listTmuxWindows', parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' }, description: 'Container ID' }], responses: { + 409: { description: 'Confirmed stopped worker; panes unavailable' }, + 503: { description: 'Runtime unconfirmed, unresponsive, or changing; panes unavailable' }, 200: { description: 'Array of tmux windows', content: { 'application/json': { schema: { type: 'array', items: { $ref: '#/components/schemas/TmuxWindow' } } } }, diff --git a/orchestrator/server/utils/container.ts b/orchestrator/server/utils/container.ts index f485049b..b21a80f0 100644 --- a/orchestrator/server/utils/container.ts +++ b/orchestrator/server/utils/container.ts @@ -1,3 +1,4 @@ +import { createError } from 'h3'; import { recoveryState, validateRecoveryMaxRetries, UNKNOWN_STATE_WARNING } from "../../shared/worker-recovery"; import { workerStartupFailure } from "./worker-startup-error"; import { MANAGED_KILO_PARENT } from './managed-volume-kilo-parent'; @@ -7788,13 +7789,40 @@ for p in sys.argv[1:]: async listTmuxWindows(id: string): Promise { const info = this.containers.get(id); - if (!info) throw new Error("Container not found"); + if (!info) throw createError({ statusCode: 404, statusMessage: "Worker not found" }); + const unavailable = () => createError({ + statusCode: info.status === 'stopped' ? 409 : 503, + statusMessage: 'Worker panes are unavailable; refresh worker status before retrying', + data: { code: 'WORKER_PANES_UNAVAILABLE', status: info.status }, + }); + if (info.status !== 'running' || isWorkerLifecycleMutationPending(id)) { + useLogger().debug('[panes] Discovery skipped: compute is not confirmed running or lifecycle is pending; no guest command issued.'); + throw unavailable(); + } + // Admission errors are not failed runtime probes and must not erase stopped state. + let commands: DockerService | IncusWorkerCommands; + try { commands = this.workerCommands(id); } + catch { + useLogger().debug('[panes] Command admission refused; panes withheld, runtime state retained.'); + throw unavailable(); + } + const handle = info.containerId, generation = workerLifecycleGeneration(id); + let windows: TmuxWindow[]; try { - return await this.workerCommands(id).execListTmuxWindows(info.containerId); + windows = await commands.execListTmuxWindows(handle); } catch (error) { - this.markRuntimeUnknown(info, "Docker terminal inspection", error); - throw error; - } + if (this.containers.get(id) === info && info.containerId === handle && info.status === 'running' && + workerLifecycleGeneration(id) === generation && !isWorkerLifecycleMutationPending(id)) + this.reportRuntimeFailure(id, "Worker terminal inspection", error, handle); + useLogger().debug('[panes] Runtime inspection failed; panes withheld pending verified runtime status.'); + throw unavailable(); + } + if (this.containers.get(id) !== info || info.containerId !== handle || info.status !== 'running' || + workerLifecycleGeneration(id) !== generation || isWorkerLifecycleMutationPending(id)) { + useLogger().debug('[panes] Runtime changed during discovery; stale panes discarded, newer runtime state retained.'); + throw unavailable(); + } + return windows; } async createTmuxWindow(id: string, name?: string): Promise { diff --git a/tests/api/pane-lifecycle.spec.ts b/tests/api/pane-lifecycle.spec.ts new file mode 100644 index 00000000..e86bcfb2 --- /dev/null +++ b/tests/api/pane-lifecycle.spec.ts @@ -0,0 +1,162 @@ +import { test, expect } from '@playwright/test'; +import { createRequire } from 'node:module'; +import { readFileSync } from 'node:fs'; +import { randomUUID } from 'node:crypto'; +import { ContainerManager } from '../../orchestrator/server/utils/container'; +import { withWorkerLifecycleMutation } from '../../orchestrator/server/utils/worker-lifecycle-coordinator'; + +const require = createRequire(new URL('../../orchestrator/package.json', import.meta.url)); +const ts = require('typescript'), vue = require('vue'); +const panes = [{ index: 0, name: 'main', active: true }]; +(globalThis as any).useLogger ??= () => ({ info() {}, warn() {}, error() {}, debug() {} }); + +function deferred() { + let resolve!: (value: T) => void, reject!: (error: Error) => void; + const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); + return { promise, resolve, reject }; +} +function managerFixture(status: string, probe = async () => panes) { + const manager = new ContainerManager({} as any, {} as any); + const info = { id: randomUUID(), userId: 'fixture-owner', containerId: 'fixture-incarnation', runtimeKind: 'incus-vm', status } as any; + let calls = 0; + manager.registerExternal(info); + manager.workerCommands = (() => ({ execListTmuxWindows: async () => { calls++; return probe(); } })) as any; + return { manager, info, calls: () => calls }; +} +for (const [status, statusCode] of [['stopped', 409], ['unknown', 503]] as const) { + test(`panes reject ${status} without guest execution or rewriting inventory`, async () => { + const f = managerFixture(status); + await expect(f.manager.listTmuxWindows(f.info.id)).rejects.toMatchObject({ statusCode, + data: { code: 'WORKER_PANES_UNAVAILABLE', status } }); + expect(f.info.status).toBe(status); + expect(f.calls()).toBe(0); + }); +} +test('running panes succeed; a current failed runtime probe becomes unknown with 503', async () => { + const healthy = managerFixture('running'); + await expect(healthy.manager.listTmuxWindows(healthy.info.id)).resolves.toEqual(panes); + expect(healthy.calls()).toBe(1); + const failed = managerFixture('running', async () => { throw Error('fixture guest unavailable'); }); + await expect(failed.manager.listTmuxWindows(failed.info.id)).rejects.toMatchObject({ statusCode: 503 }); + expect(failed.info.status).toBe('unknown'); + expect(failed.info.runtimeDiagnostic.operation).toBe('Worker terminal inspection'); +}); +test('a delayed pane probe failure cannot erase a completed stop', async () => { + const probe = deferred(), f = managerFixture('running', () => probe.promise); + const rejected = expect(f.manager.listTmuxWindows(f.info.id)).rejects.toMatchObject({ statusCode: 409 }); + await withWorkerLifecycleMutation(f.info.id, async () => { f.info.status = 'stopped'; }); + probe.reject(Error('old probe failed after stop')); + await rejected; + expect(f.info.status).toBe('stopped'); + expect(f.info.runtimeDiagnostic).toBeUndefined(); +}); +for (const outcome of ['success', 'failure']) test(`stop/start invalidates delayed pane ${outcome} without overwriting running state`, async () => { + const probe = deferred(), f = managerFixture('running', () => probe.promise); + const rejected = expect(f.manager.listTmuxWindows(f.info.id)).rejects.toMatchObject({ statusCode: 503 }); + await withWorkerLifecycleMutation(f.info.id, async () => { f.info.status = 'stopped'; }); + await withWorkerLifecycleMutation(f.info.id, async () => { f.info.status = 'running'; }); + if (outcome === 'success') probe.resolve(panes); + else probe.reject(Error('probe belongs to old lifecycle')); + await rejected; + expect(f.info.status).toBe('running'); + expect(f.info.runtimeDiagnostic).toBeUndefined(); +}); + +function tabsFixture(initialStatus: string, fetch: () => Promise) { + const workers = vue.ref([{ id: 'fixture-worker', status: initialStatus }]); + const timers = new Map Promise, delay: number }>(); + let sequence = 0, requests = 0; + const source = readFileSync(new URL('../../orchestrator/app/composables/useTmuxTabs.ts', import.meta.url), 'utf8'); + const compiled = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, + target: ts.ScriptTarget.ES2022 } }).outputText; + const exports: any = {}; + new Function('exports', 'ref', 'computed', 'watch', 'useNuxtData', 'useUiState', '$fetch', 'setTimeout', 'clearTimeout', compiled)( + exports, vue.ref, vue.computed, vue.watch, () => ({ data: workers }), + () => ({ getTmuxActiveWindow: () => null, setTmuxActiveWindow() {} }), + () => { requests++; return fetch(); }, + (callback: () => Promise, delay: number) => { const id = ++sequence; timers.set(id, { callback, delay }); return id; }, + (id: number) => timers.delete(id)); + const scope = vue.effectScope(); + const tabs = scope.run(() => exports.useTmuxTabs(vue.ref('fixture-worker'))); + const flush = async () => { + await vue.nextTick(); + for (let turn = 0; turn < 8; turn++) await Promise.resolve(); + await vue.nextTick(); + }; + return { tabs, workers, timers, flush, requests: () => requests, + async status(status: string) { workers.value[0].status = status; await flush(); }, + async tick() { + expect(timers.size).toBe(1); + const [id, timer] = [...timers.entries()][0]; + timers.delete(id); + await timer.callback(); + await flush(); + return timer.delay; + }, + dispose() { tabs.destroy(); scope.stop(); }, + }; +} + +test('pane polling follows shared running inventory and discards late stopped responses', async () => { + const pending = deferred(); + let next = () => pending.promise; + const f = tabsFixture('unknown', () => next()); + try { + await f.flush(); + expect(f.requests()).toBe(0); + expect(f.timers.size).toBe(0); + expect(f.workers.value[0].status).toBe('unknown'); + await f.status('running'); + expect(f.requests()).toBe(1); + expect(f.timers.size).toBe(0); + await f.status('stopped'); + pending.resolve(panes); + await f.flush(); + expect(f.tabs.windows.value).toEqual([]); + expect(f.timers.size).toBe(0); + expect(f.workers.value[0].status).toBe('stopped'); + await f.status('unknown'); + expect(f.requests()).toBe(1); + expect(f.workers.value[0].status).toBe('unknown'); + next = async () => panes; + await f.status('running'); + expect(f.requests()).toBe(2); + expect(f.tabs.windows.value).toEqual(panes); + expect(f.tabs.activeWindowIndex.value).toBe(0); + expect([...f.timers.values()].map(timer => timer.delay)).toEqual([3000]); + await f.status('stopped'); + expect(f.timers.size).toBe(0); + expect(f.tabs.windows.value).toEqual([]); + } finally { f.dispose(); } +}); + +test('pane polling waits for each response and backs off to a bounded interval, then recovers', async () => { + const pending = deferred(); + let response: () => Promise = () => pending.promise; + let active = 0, maximumActive = 0; + const f = tabsFixture('running', async () => { + maximumActive = Math.max(maximumActive, ++active); + try { return await response(); } finally { active--; } + }); + try { + await f.flush(); + expect(f.requests()).toBe(1); + expect(active).toBe(1); + expect(f.timers.size).toBe(0); + pending.reject(Error('expected unavailable')); + await f.flush(); + response = async () => { throw Error('expected unavailable'); }; + const delays = []; + for (let index = 0; index < 6; index++) delays.push(await f.tick()); + expect(delays).toEqual([6000, 12000, 24000, 48000, 48000, 48000]); + expect(maximumActive).toBe(1); + expect(active).toBe(0); + expect(f.workers.value[0].status).toBe('running'); + response = async () => panes; + await f.tick(); + expect([...f.timers.values()].map(timer => timer.delay)).toEqual([3000]); + expect(f.tabs.windows.value).toEqual(panes); + f.tabs.destroy(); + expect(f.timers.size).toBe(0); + } finally { f.dispose(); } +}); diff --git a/tests/playwright.modules.config.ts b/tests/playwright.modules.config.ts index 9646c3d7..4b00735a 100644 --- a/tests/playwright.modules.config.ts +++ b/tests/playwright.modules.config.ts @@ -141,6 +141,7 @@ export default defineConfig({ "api/admin-emergency-initialization.spec.ts", "api/incus-client.spec.ts", "api/incus-vcpu.spec.ts", + "api/pane-lifecycle.spec.ts", "api/vcpu-count.spec.ts", "api/incus-image-import.spec.ts", "api/incus-image-import-live.spec.ts", From f762cdebfc4ab8f25f1a1c75f16a9cbe3e0e85ea Mon Sep 17 00:00:00 2001 From: Emil Pobinger <33319340+candlelightner@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:30:42 +0200 Subject: [PATCH 3/4] Delegate vCPU management through bounded group ceilings and MCP tools Expose stopped-VM CPU inspection, resizing and observational reconciliation for ordinary and administrative workspaces. Enforce inherited per-worker ceilings across allocation and membership paths; group admins may configure descendants within parent authority, with no cumulative CPU pool. Co-authored-by: Codex --- docs/vm-vcpu-changes.md | 49 +++++- orchestrator/app/components/VcpuEditor.vue | 2 +- .../app/components/WorkerGroupsModal.vue | 29 ++++ .../app/composables/useWorkerGroups.ts | 4 +- .../server/api/worker-groups/[id].patch.ts | 3 +- .../server/api/worker-groups/index.post.ts | 3 +- .../server/utils/admin-workspace-store.ts | 13 +- orchestrator/server/utils/container.ts | 22 ++- .../utils/group-admin-workspace-store.ts | 20 ++- .../utils/incus-admin-workspace-runtime.ts | 16 +- orchestrator/server/utils/incus-client.ts | 4 +- .../server/utils/incus-worker-runtime.ts | 7 +- .../server/utils/management-cpu-domain.ts | 130 +++++++++++++++ .../server/utils/management-mcp-store.ts | 54 ++++++- .../server/utils/management-worker-domain.ts | 33 +++- .../server/utils/worker-group-manager.ts | 50 +++++- .../server/utils/worker-group-response.ts | 3 + .../server/utils/worker-group-store.ts | 9 ++ .../server/utils/worker-vcpu-policy.ts | 105 ++++++++++++ tests/api/incus-vcpu.spec.ts | 56 ++++++- tests/api/management-cpu-domain.spec.ts | 149 ++++++++++++++++++ tests/api/worker-vcpu-policy.spec.ts | 67 ++++++++ tests/playwright.modules.config.ts | 2 + 23 files changed, 795 insertions(+), 35 deletions(-) create mode 100644 orchestrator/server/utils/management-cpu-domain.ts create mode 100644 orchestrator/server/utils/worker-vcpu-policy.ts create mode 100644 tests/api/management-cpu-domain.spec.ts create mode 100644 tests/api/worker-vcpu-policy.spec.ts diff --git a/docs/vm-vcpu-changes.md b/docs/vm-vcpu-changes.md index f7f25707..5033c01b 100644 --- a/docs/vm-vcpu-changes.md +++ b/docs/vm-vcpu-changes.md @@ -2,7 +2,7 @@ The **Virtual CPU cores** editor is available in ordinary VM settings and in platform/group administrative VM management. It shows the assigned count from -the owned VM definition and the maximum reported by the Incus backend. +the owned VM definition and the maximum allowed by the Incus backend and inherited group policy. 1. Stop the VM, then select **Refresh vCPU count**. 2. Enter a positive integer within the backend maximum and select **Save vCPU @@ -35,3 +35,50 @@ Administrative VM changes also require an installed host policy that advertises CPU-count update support. Older policy installations reject the update before changing compute. Follow the bounded policy update procedure in [administrative networking](incus-admin-private-networks.md). + +## Group ceilings and delegation + +Groups have an optional **Maximum vCPUs per worker** setting. It limits each VM +independently; there is no cumulative group CPU pool. The effective ceiling is +the lowest configured value in the group's ancestry, including the group itself. +A blank setting inherits. A new explicit child ceiling cannot exceed its effective +parent ceiling. The effective maximum shown by the CPU editor also respects the +backend's CPU capacity. + +Global administrators can configure root and child ceilings. Group administrators +can configure only descendant groups, within the effective parent ceiling; they +cannot raise or clear the ceiling of their own administrative group. No delegated +resize is allowed until an inherited ceiling has been configured. Ordinary owner +REST access remains subject to applicable group ceilings. Platform administrative +VMs remain restricted to global administration. + +Ceilings apply to ordinary and group administrative VM allocation, including new +VM definitions and replacement/import paths. Existing VM allocations remain +visible and are not automatically shrunk or stopped after a ceiling is lowered. +Their next new allocation must fit. Reading or reconciling an already submitted +CPU operation does not submit another allocation and remains available. + +Moving a capped worker to an uncapped or more permissive group is rejected; +a global administrator must first adjust the source ceiling. Group administrators +cannot reparent groups to escape an inherited ceiling. The server enforces these +checks for GUI, REST and management MCP callers. + +vCPU counts describe guest CPUs, not reserved host CPU time. A per-worker ceiling +does not prevent aggregate host CPU contention when many workers run together. + +## Management MCP + +Use `workers.cpu.get`, `workers.cpu.set`, and `workers.cpu.reconcile` for ordinary +workers (`workerId`). Use `admin-workspace.cpu.get/set/reconcile` for the calling +administrative workspace, and `groups.admin-workspace.cpu.get/set/reconcile` +with `groupId` for a group administrative workspace. Group identities can target +only their bound group and live descendants. Global identities can administer +all applicable targets. + +Set requests take a positive integer `vcpuCount` and, when required, `lockPassword`. +Stop the VM explicitly first, inspect its CPU settings, set the count, start it, +and inspect again. A caller timeout does not cancel the backend operation. +Inspect pending state and use the explicit reconciliation tool; it can observe +only the recorded operation and cannot create a new resize. Group ceilings can +be configured through `groups.create` and `groups.update` using `maxVcpuCount` +(a positive integer or null to inherit), subject to the delegation rules above. diff --git a/orchestrator/app/components/VcpuEditor.vue b/orchestrator/app/components/VcpuEditor.vue index 58f6e244..920b43bf 100644 --- a/orchestrator/app/components/VcpuEditor.vue +++ b/orchestrator/app/components/VcpuEditor.vue @@ -38,7 +38,7 @@ onMounted(() => { void request(); });

Stop the VM before changing its vCPU count. Save, then start it normally; storage is retained.