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.

fix(scale): roll back on any set_policy commit failure

Juan Denis5d2b3dd5caa9
diff --git a/backend/app/services/container_scale_service.py b/backend/app/services/container_scale_service.py
index 6eeb5adc..07e31c37 100644
--- a/backend/app/services/container_scale_service.py
+++ b/backend/app/services/container_scale_service.py
@@ -34,9 +34,10 @@ class ContainerScaleService:
try:
cls._apply_policy_fields(policy, fields)
db.session.commit()
- except ValueError:
+ except Exception:
# Validation raises after fields were already assigned to the ORM
- # row; roll back here so callers never inherit a dirty session.
+ # row, and commit itself can raise; roll back either way so callers
+ # never inherit a dirty session.
db.session.rollback()
raise
return policy
diff --git a/backend/tests/test_container_scale.py b/backend/tests/test_container_scale.py
index c667765c..d7b2dc43 100644
--- a/backend/tests/test_container_scale.py
+++ b/backend/tests/test_container_scale.py
@@ -52,6 +52,28 @@ class TestScalePolicy:
else:
raise AssertionError('overlapping CPU thresholds were accepted')
+ def test_a_failed_commit_never_leaves_a_dirty_session(self, app, monkeypatch):
+ from sqlalchemy.exc import OperationalError
+
+ a = _seed_app()
+ ContainerScaleService.set_policy(a.id, service_name='web')
+
+ def failing_commit():
+ raise OperationalError('UPDATE container_scale_policies', {},
+ RuntimeError('db went away'))
+
+ monkeypatch.setattr(db.session, 'commit', failing_commit)
+ try:
+ ContainerScaleService.set_policy(a.id, min_replicas=4)
+ except OperationalError:
+ pass
+ else:
+ raise AssertionError('commit failure was swallowed')
+ monkeypatch.undo()
+
+ p = ContainerScalePolicy.query.filter_by(application_id=a.id).first()
+ assert p.min_replicas == 1, 'failed commit left the assigned value in the session'
+
class TestEvaluate:
def test_scales_up_on_high_cpu(self, app, monkeypatch):