Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(apps): policy-driven replica scaling for local Compose apps

Juan Denisbb675f0d9a71
diff --git a/backend/app/api/apps.py b/backend/app/api/apps.py
index 6f663647..ddc9008f 100644
--- a/backend/app/api/apps.py
+++ b/backend/app/api/apps.py
@@ -1885,7 +1885,11 @@ def update_scale_policy(app_id):
if not _can_edit_app(user, app):
return jsonify({'error': 'Access denied'}), 403
data = request.get_json() or {}
- policy = ContainerScaleService.set_policy(app_id, **data)
+ try:
+ policy = ContainerScaleService.set_policy(app_id, **data)
+ except ValueError as exc:
+ db.session.rollback()
+ return jsonify({'error': str(exc)}), 400
return jsonify(policy.to_dict())
diff --git a/backend/app/services/container_scale_service.py b/backend/app/services/container_scale_service.py
index 0560f455..b07861b2 100644
--- a/backend/app/services/container_scale_service.py
+++ b/backend/app/services/container_scale_service.py
@@ -31,16 +31,33 @@ class ContainerScaleService:
@classmethod
def set_policy(cls, application_id, **fields):
policy = cls.get_or_create_policy(application_id)
+
if fields.get('enabled') is not None:
- policy.enabled = bool(fields['enabled'])
+ enabled = fields['enabled']
+ if not isinstance(enabled, bool):
+ raise ValueError('enabled must be a boolean')
+ policy.enabled = enabled
if fields.get('service_name') is not None:
- policy.service_name = (fields['service_name'] or '').strip() or None
+ service_name = fields['service_name']
+ if service_name is not None and not isinstance(service_name, str):
+ raise ValueError('service_name must be a string')
+ policy.service_name = (service_name or '').strip() or None
for key in ('min_replicas', 'max_replicas', 'cpu_high_percent',
'cpu_low_percent', 'cooldown_seconds'):
if fields.get(key) is not None:
- setattr(policy, key, max(0, int(fields[key])))
+ try:
+ value = int(fields[key])
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f'{key} must be an integer') from exc
+ setattr(policy, key, max(0, value))
policy.min_replicas = max(1, policy.min_replicas)
policy.max_replicas = max(policy.min_replicas, policy.max_replicas)
+ policy.cpu_high_percent = min(100, policy.cpu_high_percent)
+ policy.cpu_low_percent = min(100, policy.cpu_low_percent)
+ if policy.cpu_low_percent >= policy.cpu_high_percent:
+ raise ValueError('cpu_low_percent must be less than cpu_high_percent')
+ if policy.enabled and not policy.service_name:
+ raise ValueError('service_name is required when auto-scale is enabled')
db.session.commit()
return policy
@@ -92,7 +109,10 @@ class ContainerScaleService:
if not app:
return {'success': False, 'error': 'Application not found'}
policy = cls.get_or_create_policy(application_id)
- replicas = max(1, int(replicas))
+ try:
+ replicas = max(1, int(replicas))
+ except (TypeError, ValueError):
+ return {'success': False, 'error': 'replicas must be an integer'}
result = cls._apply_scale(app, policy, replicas)
if not result.get('success'):
return result
@@ -109,21 +129,32 @@ class ContainerScaleService:
policy = cls.get_or_create_policy(application_id)
if not policy.enabled:
return {'success': True, 'action': 'disabled', 'replicas': policy.current_replicas}
+ if not policy.service_name:
+ return {
+ 'success': False,
+ 'error': 'service_name is required when auto-scale is enabled',
+ 'replicas': policy.current_replicas,
+ }
now = datetime.utcnow()
if policy.last_scaled_at and (now - policy.last_scaled_at) < timedelta(seconds=policy.cooldown_seconds):
return {'success': True, 'action': 'cooldown', 'replicas': policy.current_replicas}
- cpu = cls._service_cpu(app, policy)
- if cpu is None:
- return {'success': True, 'action': 'unknown', 'replicas': policy.current_replicas}
-
current = policy.current_replicas
target = current
- if cpu > policy.cpu_high_percent and current < policy.max_replicas:
- target = current + 1
- elif cpu < policy.cpu_low_percent and current > policy.min_replicas:
- target = current - 1
+ cpu = None
+ if current < policy.min_replicas:
+ target = policy.min_replicas
+ elif current > policy.max_replicas:
+ target = policy.max_replicas
+ else:
+ cpu = cls._service_cpu(app, policy)
+ if cpu is None:
+ return {'success': True, 'action': 'unknown', 'replicas': current}
+ if cpu > policy.cpu_high_percent and current < policy.max_replicas:
+ target = current + 1
+ elif cpu < policy.cpu_low_percent and current > policy.min_replicas:
+ target = current - 1
if target == current:
return {'success': True, 'action': 'hold', 'replicas': current, 'cpu': cpu}
@@ -135,8 +166,11 @@ class ContainerScaleService:
policy.last_scaled_at = now
db.session.commit()
action = 'scaled_up' if target > current else 'scaled_down'
- logger.info('Auto-scale %s: %s -> %s replicas (cpu=%.1f)', app.name, current, target, cpu)
- return {'success': True, 'action': action, 'replicas': target, 'cpu': cpu}
+ logger.info('Auto-scale %s: %s -> %s replicas (cpu=%s)', app.name, current, target, cpu)
+ response = {'success': True, 'action': action, 'replicas': target}
+ if cpu is not None:
+ response['cpu'] = cpu
+ return response
@classmethod
def sweep(cls):
diff --git a/backend/migrations/versions/093_container_scale_policies.py b/backend/migrations/versions/093_container_scale_policies.py
new file mode 100644
index 00000000..f1dfcd78
--- /dev/null
+++ b/backend/migrations/versions/093_container_scale_policies.py
@@ -0,0 +1,56 @@
+"""Add per-application container scaling policies.
+
+Revision ID: 093_container_scale_policies
+Revises: 092_restore_point_ledgers
+Create Date: 2026-08-27
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = '093_container_scale_policies'
+down_revision = '092_restore_point_ledgers'
+branch_labels = None
+depends_on = None
+
+
+def _has_table(name):
+ return name in sa.inspect(op.get_bind()).get_table_names()
+
+
+def upgrade():
+ if _has_table('container_scale_policies'):
+ return
+
+ op.create_table(
+ 'container_scale_policies',
+ sa.Column('id', sa.Integer(), nullable=False),
+ sa.Column('application_id', sa.Integer(), nullable=False),
+ sa.Column('enabled', sa.Boolean(), nullable=False,
+ server_default=sa.text('0')),
+ sa.Column('service_name', sa.String(length=100), nullable=True),
+ sa.Column('min_replicas', sa.Integer(), nullable=False,
+ server_default='1'),
+ sa.Column('max_replicas', sa.Integer(), nullable=False,
+ server_default='3'),
+ sa.Column('cpu_high_percent', sa.Integer(), nullable=False,
+ server_default='75'),
+ sa.Column('cpu_low_percent', sa.Integer(), nullable=False,
+ server_default='25'),
+ sa.Column('cooldown_seconds', sa.Integer(), nullable=False,
+ server_default='300'),
+ sa.Column('current_replicas', sa.Integer(), nullable=False,
+ server_default='1'),
+ sa.Column('last_scaled_at', sa.DateTime(), nullable=True),
+ sa.Column('updated_at', sa.DateTime(), nullable=True),
+ sa.ForeignKeyConstraint(['application_id'], ['applications.id']),
+ sa.PrimaryKeyConstraint('id'),
+ )
+ op.create_index(
+ 'ix_container_scale_policies_application_id',
+ 'container_scale_policies', ['application_id'], unique=True)
+
+
+def downgrade():
+ if _has_table('container_scale_policies'):
+ op.drop_table('container_scale_policies')
diff --git a/backend/tests/test_container_scale.py b/backend/tests/test_container_scale.py
index 0f037850..c667765c 100644
--- a/backend/tests/test_container_scale.py
+++ b/backend/tests/test_container_scale.py
@@ -1,5 +1,4 @@
-"""Tests for container horizontal auto-scaling (decision logic)."""
-import uuid
+"""Tests for container horizontal auto-scaling (decision logic and API flow)."""
from datetime import datetime
from app import db
@@ -33,6 +32,26 @@ class TestScalePolicy:
p = ContainerScaleService.set_policy(a.id, min_replicas=5, max_replicas=2)
assert p.max_replicas == 5
+ def test_rejects_an_enabled_policy_without_a_service(self, app):
+ a = _seed_app()
+ try:
+ ContainerScaleService.set_policy(a.id, enabled=True)
+ except ValueError as exc:
+ assert str(exc) == 'service_name is required when auto-scale is enabled'
+ else:
+ raise AssertionError('enabled policy without a service was accepted')
+
+ def test_rejects_overlapping_cpu_thresholds(self, app):
+ a = _seed_app()
+ try:
+ ContainerScaleService.set_policy(
+ a.id, service_name='web', cpu_low_percent=80,
+ cpu_high_percent=70)
+ except ValueError as exc:
+ assert str(exc) == 'cpu_low_percent must be less than cpu_high_percent'
+ else:
+ raise AssertionError('overlapping CPU thresholds were accepted')
+
class TestEvaluate:
def test_scales_up_on_high_cpu(self, app, monkeypatch):
@@ -83,6 +102,26 @@ class TestEvaluate:
monkeypatch.setattr(ContainerScaleService, '_service_cpu', lambda app_, policy: None)
assert ContainerScaleService.evaluate(a.id)['action'] == 'unknown'
+ def test_enforces_a_raised_minimum_without_waiting_for_high_cpu(self, app, monkeypatch):
+ a = _seed_app()
+ ContainerScaleService.set_policy(
+ a.id, enabled=True, service_name='web', min_replicas=2,
+ max_replicas=3, cooldown_seconds=0)
+ applied = []
+ monkeypatch.setattr(
+ ContainerScaleService, '_service_cpu',
+ lambda app_, policy: (_ for _ in ()).throw(
+ AssertionError('CPU should not gate the replica floor')))
+ monkeypatch.setattr(
+ ContainerScaleService, '_apply_scale',
+ lambda app_, policy, n: applied.append(n) or {'success': True})
+
+ result = ContainerScaleService.evaluate(a.id)
+
+ assert result['action'] == 'scaled_up'
+ assert result['replicas'] == 2
+ assert applied == [2]
+
class TestScaleApi:
def test_manual_scale_endpoint(self, client, auth_headers, app, monkeypatch):
@@ -96,3 +135,82 @@ class TestScaleApi:
def test_scale_sweep_requires_admin(self, client, app):
assert client.post('/api/v1/apps/scale-sweep').status_code == 401
+
+ def test_rejects_non_numeric_manual_replica_count(self, client, auth_headers, app):
+ from app.models import User
+ admin = User.query.filter_by(username='testadmin').first()
+ a = _seed_app(user_id=admin.id)
+ ContainerScaleService.set_policy(a.id, service_name='web')
+
+ response = client.post(
+ f'/api/v1/apps/{a.id}/scale', json={'replicas': 'many'},
+ headers=auth_headers)
+
+ assert response.status_code == 400
+ assert response.get_json() == {'error': 'replicas must be an integer'}
+
+ def test_rejects_invalid_policy_without_persisting_it(
+ self, client, auth_headers, app):
+ from app.models import User
+ admin = User.query.filter_by(username='testadmin').first()
+ a = _seed_app(user_id=admin.id)
+
+ response = client.put(
+ f'/api/v1/apps/{a.id}/scale-policy',
+ json={'enabled': True, 'service_name': ''},
+ headers=auth_headers)
+
+ assert response.status_code == 400
+ assert response.get_json() == {
+ 'error': 'service_name is required when auto-scale is enabled'}
+ persisted = client.get(
+ f'/api/v1/apps/{a.id}/scale-policy', headers=auth_headers)
+ assert persisted.get_json()['enabled'] is False
+
+ def test_policy_to_evaluation_to_manual_scale_workflow(
+ self, client, auth_headers, app, monkeypatch):
+ from app.models import User
+ admin = User.query.filter_by(username='testadmin').first()
+ a = _seed_app(user_id=admin.id)
+ applied = []
+ monkeypatch.setattr(ContainerScaleService, '_service_cpu', lambda app_, policy: 92.0)
+ monkeypatch.setattr(
+ ContainerScaleService, '_apply_scale',
+ lambda app_, policy, n: applied.append(n) or {'success': True})
+
+ initial = client.get(
+ f'/api/v1/apps/{a.id}/scale-policy', headers=auth_headers)
+ assert initial.status_code == 200
+ assert initial.get_json()['current_replicas'] == 1
+
+ configured = client.put(
+ f'/api/v1/apps/{a.id}/scale-policy',
+ json={
+ 'enabled': True,
+ 'service_name': 'web',
+ 'min_replicas': 1,
+ 'max_replicas': 4,
+ 'cpu_low_percent': 20,
+ 'cpu_high_percent': 75,
+ 'cooldown_seconds': 0,
+ },
+ headers=auth_headers)
+ assert configured.status_code == 200
+ assert configured.get_json()['enabled'] is True
+
+ evaluated = client.post(
+ f'/api/v1/apps/{a.id}/scale/evaluate', headers=auth_headers)
+ assert evaluated.status_code == 200
+ assert evaluated.get_json()['action'] == 'scaled_up'
+ assert evaluated.get_json()['replicas'] == 2
+
+ manual = client.post(
+ f'/api/v1/apps/{a.id}/scale', json={'replicas': 3},
+ headers=auth_headers)
+ assert manual.status_code == 200
+ assert manual.get_json()['replicas'] == 3
+
+ persisted = client.get(
+ f'/api/v1/apps/{a.id}/scale-policy', headers=auth_headers)
+ assert persisted.get_json()['current_replicas'] == 3
+ assert applied == [2, 3]
diff --git a/docs/NEW_FEATURES.md b/docs/NEW_FEATURES.md
index f837150d..08cff773 100644
--- a/docs/NEW_FEATURES.md
+++ b/docs/NEW_FEATURES.md
@@ -1,10 +1,9 @@
# New Features — Endpoint & Page Reference
-Reference for the features added on `dev` — the 12 UI/Docker/WAF feature commits
-(`cd16d9a … 70883d5`) plus the SSL/TLS hardening follow-up (`02afdec … a09bf0f`,
-see §6). All endpoints are under `/api/v1`. "admin" = requires `user.is_admin`;
-"edit" = `_can_edit_app` (owner or admin); "auth" = any valid JWT. Tables
-auto-create on startup via `db.create_all()`.
+Reference for the current UI, Docker, WAF, and TLS surfaces on `dev`. All endpoints
+are under `/api/v1`. "admin" requires an admin user; "edit" uses `_can_edit_app`
+(owner, admin, or an editor grant); "auth" accepts any valid JWT. Migration
+`093_container_scale_policies` versions the scaling-policy table.
---
@@ -57,12 +56,24 @@ no-activity-baseline policy is never slept blind.
| Method | Path | Auth | Notes |
|---|---|---|---|
| GET | `/apps/<id>/scale-policy` | auth | |
-| PUT | `/apps/<id>/scale-policy` | edit | Body `{enabled?, service_name?, min_replicas?, max_replicas?, cpu_high_percent?, cpu_low_percent?, cooldown_seconds?}`. |
-| POST | `/apps/<id>/scale` | edit | Body `{replicas}` — manual scale (`docker compose --scale`). |
+| PUT | `/apps/<id>/scale-policy` | edit | Body `{enabled?, service_name?, min_replicas?, max_replicas?, cpu_high_percent?, cpu_low_percent?, cooldown_seconds?}`. Enabling requires a service name; low CPU must remain below high CPU. |
+| POST | `/apps/<id>/scale` | edit | Body `{replicas}`; manual scale through `docker compose --scale`, with a minimum of one replica. |
| POST | `/apps/<id>/scale/evaluate` | edit | One auto decision (returns `action`: scaled_up/down/hold/cooldown/disabled/unknown). |
| POST | `/apps/scale-sweep` | admin | Evaluate every enabled policy. **Cron-drivable.** |
-Requires a scale-capable compose service (no fixed host port / `container_name`). Local apps only.
+Requires a scale-capable Compose service with no fixed host port or `container_name`.
+Local apps only. The configured minimum acts as a floor on the next evaluation,
+even when CPU metrics are unavailable. The feature does not configure a load
+balancer, shared storage, health checks, or failover, so it must not be presented
+as end-to-end high availability. `current_replicas` records the last successful
+ServerKit scale command; it does not reconcile changes made through Docker outside
+ServerKit.
+
+Verification lives in `frontend/src/components/apps/__tests__/autoScalePolicy.test.mjs`,
+`frontend/src/services/api/__tests__/containerOps.test.mjs`, and
+`backend/tests/test_container_scale.py`. The backend workflow test covers policy
+read/write, evaluation, manual scale, and persistence. Docker execution and traffic
+continuity still require the real-host checklist in `docs/HORIZONTAL_SCALING_SPEC.md`.
### GPU monitoring — `services/gpu_service.py` (no model)
| Method | Path | Auth | Notes |
diff --git a/frontend/src/components/apps/ContainerOpsPanel.jsx b/frontend/src/components/apps/ContainerOpsPanel.jsx
index d4db4ce3..acb45eb1 100644
--- a/frontend/src/components/apps/ContainerOpsPanel.jsx
+++ b/frontend/src/components/apps/ContainerOpsPanel.jsx
@@ -11,6 +11,13 @@ import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { useTranslation } from 'react-i18next';
+import {
+ DEFAULT_SCALE_POLICY,
+ normalizeScalePolicy,
+ replicaTarget,
+ resolvedReplicaCount,
+ scalePolicyPayload,
+} from './autoScalePolicy';
// Short SHA helper for image digests (handles "sha256:abcdef..." or bare hashes)
function shortDigest(digest) {
@@ -378,21 +385,10 @@ const AutoSleepSection = ({ app, onChanged }) => {
// ============================================================
// Auto-scale section
// ============================================================
-const DEFAULT_SCALE = {
- enabled: false,
- service_name: '',
- min_replicas: 1,
- max_replicas: 3,
- cpu_high_percent: 80,
- cpu_low_percent: 20,
- cooldown_seconds: 300,
- current_replicas: 1,
-};
-
const AutoScaleSection = ({ app, onChanged }) => {
const { t } = useTranslation();
const toast = useToast();
- const [form, setForm] = useState(DEFAULT_SCALE);
+ const [form, setForm] = useState(DEFAULT_SCALE_POLICY);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [scaling, setScaling] = useState(false);
@@ -402,7 +398,7 @@ const AutoScaleSection = ({ app, onChanged }) => {
setLoading(true);
try {
const data = await api.getScalePolicy(app.id);
- const merged = { ...DEFAULT_SCALE, ...(data || {}) };
+ const merged = normalizeScalePolicy(data);
setForm(merged);
setManualReplicas(merged.current_replicas ?? merged.min_replicas ?? 1);
} catch (err) {
@@ -421,15 +417,7 @@ const AutoScaleSection = ({ app, onChanged }) => {
async function handleSave() {
setSaving(true);
try {
- const payload = {
- enabled: form.enabled,
- service_name: form.service_name,
- min_replicas: parseInt(form.min_replicas, 10) || 1,
- max_replicas: parseInt(form.max_replicas, 10) || 1,
- cpu_high_percent: parseInt(form.cpu_high_percent, 10) || 0,
- cpu_low_percent: parseInt(form.cpu_low_percent, 10) || 0,
- cooldown_seconds: parseInt(form.cooldown_seconds, 10) || 0,
- };
+ const payload = scalePolicyPayload(form);
const data = await api.updateScalePolicy(app.id, payload);
setForm((prev) => ({ ...prev, ...(data || payload) }));
toast.success(t('app.containerOpsPanel.autoScalePolicySaved', 'Auto-scale policy saved.'));
@@ -442,11 +430,12 @@ const AutoScaleSection = ({ app, onChanged }) => {
}
async function handleManualScale() {
- const replicas = Math.max(0, parseInt(manualReplicas, 10) || 0);
+ const replicas = replicaTarget(manualReplicas);
setScaling(true);
try {
- await api.scaleApp(app.id, replicas);
- toast.success(t('app.containerOpsPanel.scaledToReplica', 'Scaled to {{replicas}} replica{{value}}.', { replicas: replicas, value: replicas === 1 ? '' : 's' }));
+ const result = await api.scaleApp(app.id, replicas);
+ const appliedReplicas = resolvedReplicaCount(result, replicas);
+ toast.success(t('app.containerOpsPanel.scaledToReplica', 'Scaled to {{replicas}} replica{{value}}.', { replicas: appliedReplicas, value: appliedReplicas === 1 ? '' : 's' }));
await load();
onChanged?.();
} catch (err) {
@@ -517,7 +506,7 @@ const AutoScaleSection = ({ app, onChanged }) => {
<Input
id={`scale-min-${app.id}`}
type="number"
- min={0}
+ min={1}
value={form.min_replicas}
onChange={(e) => setField('min_replicas', e.target.value)}
disabled={loading}
@@ -572,7 +561,7 @@ const AutoScaleSection = ({ app, onChanged }) => {
<Input
id={`scale-manual-${app.id}`}
type="number"
- min={0}
+ min={1}
value={manualReplicas}
onChange={(e) => setManualReplicas(e.target.value)}
disabled={scaling}
diff --git a/frontend/src/components/apps/__tests__/autoScalePolicy.test.mjs b/frontend/src/components/apps/__tests__/autoScalePolicy.test.mjs
new file mode 100644
index 00000000..61d2ab66
--- /dev/null
+++ b/frontend/src/components/apps/__tests__/autoScalePolicy.test.mjs
@@ -0,0 +1,46 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import {
+ DEFAULT_SCALE_POLICY,
+ normalizeScalePolicy,
+ replicaTarget,
+ resolvedReplicaCount,
+ scalePolicyPayload,
+} from '../autoScalePolicy.js';
+
+test('normalizes a missing policy to the UI defaults', () => {
+ assert.deepEqual(normalizeScalePolicy(null), DEFAULT_SCALE_POLICY);
+ assert.deepEqual(normalizeScalePolicy({ enabled: true, service_name: 'web' }), {
+ ...DEFAULT_SCALE_POLICY,
+ enabled: true,
+ service_name: 'web',
+ });
+});
+
+test('serializes the policy using the same bounds as the API', () => {
+ assert.deepEqual(scalePolicyPayload({
+ enabled: true,
+ service_name: ' web ',
+ min_replicas: '0',
+ max_replicas: '-2',
+ cpu_high_percent: '120',
+ cpu_low_percent: '-4',
+ cooldown_seconds: '-30',
+ }), {
+ enabled: true,
+ service_name: 'web',
+ min_replicas: 1,
+ max_replicas: 1,
+ cpu_high_percent: 100,
+ cpu_low_percent: 0,
+ cooldown_seconds: 0,
+ });
+});
+
+test('manual scale never asks for zero replicas and reports the API result', () => {
+ assert.equal(replicaTarget('0'), 1);
+ assert.equal(replicaTarget('4'), 4);
+ assert.equal(resolvedReplicaCount({ replicas: 2 }, 5), 2);
+ assert.equal(resolvedReplicaCount(null, 5), 5);
+});
diff --git a/frontend/src/components/apps/autoScalePolicy.js b/frontend/src/components/apps/autoScalePolicy.js
new file mode 100644
index 00000000..6d80da0a
--- /dev/null
+++ b/frontend/src/components/apps/autoScalePolicy.js
@@ -0,0 +1,46 @@
+export const DEFAULT_SCALE_POLICY = Object.freeze({
+ enabled: false,
+ service_name: '',
+ min_replicas: 1,
+ max_replicas: 3,
+ cpu_high_percent: 75,
+ cpu_low_percent: 25,
+ cooldown_seconds: 300,
+ current_replicas: 1,
+});
+
+function integerOr(value, fallback) {
+ const parsed = Number.parseInt(value, 10);
+ return Number.isFinite(parsed) ? parsed : fallback;
+}
+
+function percentage(value, fallback) {
+ return Math.min(100, Math.max(0, integerOr(value, fallback)));
+}
+
+export function normalizeScalePolicy(data) {
+ return { ...DEFAULT_SCALE_POLICY, ...(data || {}) };
+}
+
+export function scalePolicyPayload(form) {
+ const minReplicas = Math.max(1, integerOr(form.min_replicas, 1));
+ const maxReplicas = Math.max(minReplicas, integerOr(form.max_replicas, minReplicas));
+
+ return {
+ enabled: !!form.enabled,
+ service_name: String(form.service_name || '').trim(),
+ min_replicas: minReplicas,
+ max_replicas: maxReplicas,
+ cpu_high_percent: percentage(form.cpu_high_percent, 75),
+ cpu_low_percent: percentage(form.cpu_low_percent, 25),
+ cooldown_seconds: Math.max(0, integerOr(form.cooldown_seconds, 0)),
+ };
+}
+
+export function replicaTarget(value) {
+ return Math.max(1, integerOr(value, 1));
+}
+
+export function resolvedReplicaCount(result, requested) {
+ return replicaTarget(result?.replicas ?? requested);
+}
diff --git a/frontend/src/services/api/__tests__/containerOps.test.mjs b/frontend/src/services/api/__tests__/containerOps.test.mjs
new file mode 100644
index 00000000..c3695d51
--- /dev/null
+++ b/frontend/src/services/api/__tests__/containerOps.test.mjs
@@ -0,0 +1,40 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import {
+ evaluateScale,
+ getScalePolicy,
+ scaleApp,
+ updateScalePolicy,
+} from '../containerOps.js';
+
+function recorder(response = { ok: true }) {
+ const calls = [];
+ return {
+ calls,
+ context: {
+ request(path, options) {
+ calls.push({ path, options });
+ return Promise.resolve(response);
+ },
+ },
+ };
+}
+
+test('scale-policy frontend methods preserve the backend route contract', async () => {
+ const { calls, context } = recorder({ replicas: 3 });
+ const policy = { enabled: true, service_name: 'web', min_replicas: 2 };
+
+ await getScalePolicy.call(context, 42);
+ await updateScalePolicy.call(context, 42, policy);
+ const result = await scaleApp.call(context, 42, 3);
+ await evaluateScale.call(context, 42);
+
+ assert.deepEqual(calls, [
+ { path: '/apps/42/scale-policy', options: undefined },
+ { path: '/apps/42/scale-policy', options: { method: 'PUT', body: policy } },
+ { path: '/apps/42/scale', options: { method: 'POST', body: { replicas: 3 } } },
+ { path: '/apps/42/scale/evaluate', options: { method: 'POST' } },
+ ]);
+ assert.deepEqual(result, { replicas: 3 });
+});