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.

refactor(models): one door for delete cascades on NOT NULL child FKs

Juan Denis7fd90a6c8726
diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py
index 1da3b759..01bfcd3e 100644
--- a/backend/app/models/__init__.py
+++ b/backend/app/models/__init__.py
@@ -1,3 +1,6 @@
+# Registers the mapper hook that auto-cascades deletes onto NOT NULL child
+# FKs (the alternative is an IntegrityError on every parent hard-delete).
+from app.models import _delete_cascade_policy # noqa: F401
from app.models.user import User
from app.models.application import Application
from app.models.domain import Domain
diff --git a/backend/app/models/_delete_cascade_policy.py b/backend/app/models/_delete_cascade_policy.py
new file mode 100644
index 00000000..2b4c70f2
--- /dev/null
+++ b/backend/app/models/_delete_cascade_policy.py
@@ -0,0 +1,59 @@
+"""One door for delete semantics on NOT NULL child FKs.
+
+SQLAlchemy's default when a parent row is deleted is to NULL the child's FK —
+dynamic relationships included. For a child whose FK is NOT NULL that default
+is not a policy, it is a crash: the UPDATE violates the constraint and the
+delete dies with IntegrityError (this is how Recycle Bin purge broke in the
+field, then user/server/workspace deletes in the audit that followed).
+
+Rather than every model remembering to write cascade='all, delete-orphan' on
+every such relationship — and every reviewer remembering to check — this module
+applies it automatically at mapper-configuration time: any one-to-many whose
+child FK is NOT NULL gets the delete cascade, because with a NOT NULL FK the
+children *cannot* outlive the parent; the only question is whether the delete
+works or crashes.
+
+A relationship where the parent delete should be REFUSED instead (the children
+are too valuable to cascade) opts out here, and the code path that deletes the
+parent must guard explicitly. `test_application_soft_delete.py` pins both
+halves: the sweep proves the door leaves no offenders beyond this registry, and
+a test per entry proves its guard exists.
+
+Plugin/extension models are covered too: registering a new model triggers a
+fresh configure_mappers() run, which fires this hook again (it is idempotent).
+"""
+from sqlalchemy import event
+from sqlalchemy.orm import Mapper
+
+# 'Parent.relationship' -> why cascading would be wrong. Every entry needs a
+# guard on the parent's delete path; an entry without one just moves the crash.
+DELIBERATELY_UNCASCADED = {
+ 'User.applications':
+ 'apps own containers/volumes that must go through app delete + '
+ 'Recycle Bin purge; delete_user refuses (409) while the user owns any',
+ 'CloudProvider.servers':
+ 'no code path deletes a CloudProvider row today; silently dropping '
+ 'the inventory of provisioned (billing!) VMs must stay a deliberate, '
+ 'guarded decision if one is ever added',
+}
+
+
+def _needs_delete_cascade(rel):
+ if rel.direction.name != 'ONETOMANY' or rel.viewonly:
+ return False
+ fk_cols = [c for c in rel.remote_side if c.foreign_keys]
+ if not fk_cols or all(c.nullable for c in fk_cols):
+ return False
+ return 'delete' not in rel.cascade
+
+
[email protected]_for(Mapper, 'after_configured')
+def apply_delete_cascades():
+ from app import db
+ for mapper in db.Model.registry.mappers:
+ for rel in mapper.relationships:
+ if not _needs_delete_cascade(rel):
+ continue
+ if f'{mapper.class_.__name__}.{rel.key}' in DELIBERATELY_UNCASCADED:
+ continue
+ rel.cascade = 'all, delete-orphan'
diff --git a/backend/app/models/agent_plugin.py b/backend/app/models/agent_plugin.py
index 364d4782..162407f7 100644
--- a/backend/app/models/agent_plugin.py
+++ b/backend/app/models/agent_plugin.py
@@ -40,10 +40,7 @@ class AgentPlugin(JsonColumnMixin, TimestampMixin, db.Model):
# Relationships
- # cascade: install rows have a NOT NULL plugin_id — deleting the plugin must
- # delete them, or the default FK null-out IntegrityErrors.
- installations = db.relationship('AgentPluginInstall', backref='plugin',
- lazy='dynamic', cascade='all, delete-orphan')
+ installations = db.relationship('AgentPluginInstall', backref='plugin', lazy='dynamic')
@property
def manifest(self):
@@ -130,9 +127,7 @@ class AgentPluginInstall(JsonColumnMixin, db.Model):
health_status = db.Column(db.String(32), default='unknown') # healthy, degraded, unhealthy, unknown
metrics_json = db.Column(db.Text)
- # cascade: server_id is NOT NULL — removing a server must take its installs.
- server = db.relationship('Server', backref=db.backref(
- 'plugin_installs', lazy='dynamic', cascade='all, delete-orphan'))
+ server = db.relationship('Server', backref=db.backref('plugin_installs', lazy='dynamic'))
@property
def config(self):
diff --git a/backend/app/models/container_scale_policy.py b/backend/app/models/container_scale_policy.py
index a52186c9..407b7684 100644
--- a/backend/app/models/container_scale_policy.py
+++ b/backend/app/models/container_scale_policy.py
@@ -23,10 +23,7 @@ class ContainerScalePolicy(db.Model):
last_scaled_at = db.Column(db.DateTime)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
- # cascade: application_id is NOT NULL, so a real delete of the app (Recycle
- # Bin purge) must take this row with it — the default null-out IntegrityErrors.
- application = db.relationship('Application', backref=db.backref(
- 'scale_policy', uselist=False, cascade='all, delete-orphan'))
+ application = db.relationship('Application', backref=db.backref('scale_policy', uselist=False))
def to_dict(self):
return {
diff --git a/backend/app/models/container_sleep_policy.py b/backend/app/models/container_sleep_policy.py
index df8c6676..c9518a34 100644
--- a/backend/app/models/container_sleep_policy.py
+++ b/backend/app/models/container_sleep_policy.py
@@ -17,10 +17,7 @@ class ContainerSleepPolicy(db.Model):
asleep = db.Column(db.Boolean, default=False, nullable=False)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
- # cascade: application_id is NOT NULL, so a real delete of the app (Recycle
- # Bin purge) must take this row with it — the default null-out IntegrityErrors.
- application = db.relationship('Application', backref=db.backref(
- 'sleep_policy', uselist=False, cascade='all, delete-orphan'))
+ application = db.relationship('Application', backref=db.backref('sleep_policy', uselist=False))
def to_dict(self):
return {
diff --git a/backend/app/models/deployment.py b/backend/app/models/deployment.py
index 643cab3a..b0f55349 100644
--- a/backend/app/models/deployment.py
+++ b/backend/app/models/deployment.py
@@ -59,10 +59,7 @@ class Deployment(JsonColumnMixin, db.Model):
extra_data = db.Column(db.Text, default='{}')
# Relationships
- # cascade: app_id is NOT NULL, so a real delete of the app (Recycle Bin
- # purge) must take the history with it — the default null-out IntegrityErrors.
- app = db.relationship('Application', backref=db.backref(
- 'deployments', lazy='dynamic', cascade='all, delete-orphan'))
+ app = db.relationship('Application', backref=db.backref('deployments', lazy='dynamic'))
deployer = db.relationship('User', backref=db.backref('user_deployments', lazy='dynamic'))
def get_metadata(self):
@@ -194,10 +191,7 @@ class DeploymentDiff(JsonColumnMixin, db.Model):
created_at = db.Column(db.DateTime, default=datetime.utcnow)
- # cascade: deployment_id is NOT NULL — retention pruning (and app purge)
- # deletes Deployment rows, which must take their diff along.
- deployment = db.relationship('Deployment', foreign_keys=[deployment_id],
- backref=db.backref('diff', cascade='all, delete-orphan'))
+ deployment = db.relationship('Deployment', foreign_keys=[deployment_id], backref='diff')
def to_dict(self):
return {
diff --git a/backend/app/models/deployment_snapshot.py b/backend/app/models/deployment_snapshot.py
index 0ad092f1..4424daf2 100644
--- a/backend/app/models/deployment_snapshot.py
+++ b/backend/app/models/deployment_snapshot.py
@@ -58,13 +58,8 @@ class DeploymentSnapshot(JsonColumnMixin, db.Model):
# deployment.py (another agent owns those). The Application gains a
# ``config_snapshots`` collection; the Deployment gains ``config_snapshots``
# too via a distinct backref.
- # cascade: application_id is NOT NULL, so a real delete of the app (Recycle
- # Bin purge) must take the snapshots too — the default null-out IntegrityErrors.
- # (deployment_id below is nullable, so the Deployment side needs no cascade.)
application = db.relationship(
- 'Application',
- backref=db.backref('config_snapshots', lazy='dynamic',
- cascade='all, delete-orphan')
+ 'Application', backref=db.backref('config_snapshots', lazy='dynamic')
)
deployment = db.relationship(
'Deployment', backref=db.backref('config_snapshots', lazy='dynamic')
diff --git a/backend/app/models/environment_activity.py b/backend/app/models/environment_activity.py
index a65d11e8..beee2e47 100644
--- a/backend/app/models/environment_activity.py
+++ b/backend/app/models/environment_activity.py
@@ -33,9 +33,7 @@ class EnvironmentActivity(JsonColumnMixin, db.Model):
created_at = db.Column(db.DateTime, default=datetime.utcnow)
# Relationships
- # cascade: site_id is NOT NULL — a site's activity log dies with the site.
- site = db.relationship('WordPressSite', backref=db.backref(
- 'activities', lazy='dynamic', cascade='all, delete-orphan'))
+ site = db.relationship('WordPressSite', backref=db.backref('activities', lazy='dynamic'))
user = db.relationship('User', backref=db.backref('environment_activities', lazy='dynamic'))
def to_dict(self):
diff --git a/backend/app/models/image_scan.py b/backend/app/models/image_scan.py
index 5ab36f43..944dc97f 100644
--- a/backend/app/models/image_scan.py
+++ b/backend/app/models/image_scan.py
@@ -20,10 +20,7 @@ class ImageVulnerabilityScan(JsonColumnMixin, db.Model):
started_at = db.Column(db.DateTime, default=datetime.utcnow)
completed_at = db.Column(db.DateTime, nullable=True)
- # cascade: application_id is NOT NULL — purge must delete, not null out.
- application = db.relationship('Application', backref=db.backref(
- 'image_scans', lazy='dynamic', cascade='all, delete-orphan',
- order_by='ImageVulnerabilityScan.started_at.desc()'))
+ application = db.relationship('Application', backref=db.backref('image_scans', lazy='dynamic', order_by='ImageVulnerabilityScan.started_at.desc()'))
def set_counts(self, counts):
self.severity_counts = json.dumps(counts)
@@ -75,10 +72,7 @@ class SbomArtifact(JsonColumnMixin, db.Model):
sbom_json = db.Column(db.Text) # SPDX 2.3 JSON
created_at = db.Column(db.DateTime, default=datetime.utcnow)
- # cascade: application_id is NOT NULL — purge must delete, not null out.
- application = db.relationship('Application', backref=db.backref(
- 'sboms', lazy='dynamic', cascade='all, delete-orphan',
- order_by='SbomArtifact.created_at.desc()'))
+ application = db.relationship('Application', backref=db.backref('sboms', lazy='dynamic', order_by='SbomArtifact.created_at.desc()'))
def to_dict(self, include_sbom=False):
return {
diff --git a/backend/app/models/image_update.py b/backend/app/models/image_update.py
index b63bf871..b8626f3a 100644
--- a/backend/app/models/image_update.py
+++ b/backend/app/models/image_update.py
@@ -18,8 +18,7 @@ class ImageUpdateCheck(SerializableMixin, db.Model):
error_message = db.Column(db.Text)
checked_at = db.Column(db.DateTime, default=datetime.utcnow)
- # cascade: application_id is NOT NULL — purge must delete, not null out.
application = db.relationship('Application', backref=db.backref(
- 'image_update_checks', lazy='dynamic', cascade='all, delete-orphan',
+ 'image_update_checks', lazy='dynamic',
order_by='ImageUpdateCheck.checked_at.desc()'))
diff --git a/backend/app/models/metric_alert.py b/backend/app/models/metric_alert.py
index 192a7483..5b94383f 100644
--- a/backend/app/models/metric_alert.py
+++ b/backend/app/models/metric_alert.py
@@ -55,9 +55,7 @@ class MetricAlert(db.Model):
created_at = db.Column(db.DateTime, default=datetime.utcnow)
resolved_at = db.Column(db.DateTime)
- # cascade: server_id is NOT NULL — alerts die with their server.
- server = db.relationship('Server', backref=db.backref(
- 'metric_alerts', cascade='all, delete-orphan'))
+ server = db.relationship('Server', backref='metric_alerts')
def to_dict(self):
return {
diff --git a/backend/app/models/notification_preferences.py b/backend/app/models/notification_preferences.py
index ae025430..3913923a 100644
--- a/backend/app/models/notification_preferences.py
+++ b/backend/app/models/notification_preferences.py
@@ -63,9 +63,7 @@ class NotificationPreferences(TimestampMixin, JsonColumnMixin, db.Model):
# Relationship
- # cascade: user_id is NOT NULL — preferences die with the account.
- user = db.relationship('User', backref=db.backref(
- 'notification_preferences', uselist=False, cascade='all, delete-orphan'))
+ user = db.relationship('User', backref=db.backref('notification_preferences', uselist=False))
def get_channels(self):
"""Get the list of enabled channels."""
diff --git a/backend/app/models/oauth_identity.py b/backend/app/models/oauth_identity.py
index df307424..f4bc5124 100644
--- a/backend/app/models/oauth_identity.py
+++ b/backend/app/models/oauth_identity.py
@@ -21,9 +21,7 @@ class OAuthIdentity(TimestampMixin, db.Model):
token_expires_at = db.Column(db.DateTime, nullable=True)
last_login_at = db.Column(db.DateTime, nullable=True)
- # cascade: user_id is NOT NULL — linked identities die with the account.
- user = db.relationship('User', backref=db.backref(
- 'oauth_identities', lazy='dynamic', cascade='all, delete-orphan'))
+ user = db.relationship('User', backref=db.backref('oauth_identities', lazy='dynamic'))
def to_dict(self):
return {
diff --git a/backend/app/models/passkey.py b/backend/app/models/passkey.py
index 511eb386..f25c2283 100644
--- a/backend/app/models/passkey.py
+++ b/backend/app/models/passkey.py
@@ -29,9 +29,7 @@ class PasskeyCredential(JsonColumnMixin, db.Model):
created_at = db.Column(db.DateTime, default=datetime.utcnow)
last_used_at = db.Column(db.DateTime, nullable=True)
- # cascade: user_id is NOT NULL — passkeys die with the account.
- user = db.relationship('User', backref=db.backref(
- 'passkeys', lazy='dynamic', cascade='all, delete-orphan'))
+ user = db.relationship('User', backref=db.backref('passkeys', lazy='dynamic'))
def get_transports(self):
return self._json_read('transports', [])
diff --git a/backend/app/models/promotion_job.py b/backend/app/models/promotion_job.py
index 3b5b35ea..84f4e8d9 100644
--- a/backend/app/models/promotion_job.py
+++ b/backend/app/models/promotion_job.py
@@ -40,14 +40,10 @@ class PromotionJob(JsonColumnMixin, db.Model):
created_at = db.Column(db.DateTime, default=datetime.utcnow)
# Relationships
- # cascade: both site FKs are NOT NULL — a promotion record cannot outlive
- # either endpoint, so deleting a site takes its job history along.
source_site = db.relationship('WordPressSite', foreign_keys=[source_site_id],
- backref=db.backref('promotions_as_source', lazy='dynamic',
- cascade='all, delete-orphan'))
+ backref=db.backref('promotions_as_source', lazy='dynamic'))
target_site = db.relationship('WordPressSite', foreign_keys=[target_site_id],
- backref=db.backref('promotions_as_target', lazy='dynamic',
- cascade='all, delete-orphan'))
+ backref=db.backref('promotions_as_target', lazy='dynamic'))
user = db.relationship('User', backref=db.backref('promotion_jobs', lazy='dynamic'))
pre_promotion_snapshot = db.relationship('DatabaseSnapshot', foreign_keys=[pre_promotion_snapshot_id])
diff --git a/backend/app/models/sanitization_profile.py b/backend/app/models/sanitization_profile.py
index d477632c..f9915078 100644
--- a/backend/app/models/sanitization_profile.py
+++ b/backend/app/models/sanitization_profile.py
@@ -43,9 +43,7 @@ class SanitizationProfile(JsonColumnMixin, db.Model):
updated_at = db.Column(db.DateTime, onupdate=datetime.utcnow)
# Relationships
- # cascade: user_id is NOT NULL — personal profiles die with the account.
- user = db.relationship('User', backref=db.backref(
- 'sanitization_profiles', lazy='dynamic', cascade='all, delete-orphan'))
+ user = db.relationship('User', backref=db.backref('sanitization_profiles', lazy='dynamic'))
def get_config(self):
"""Parse and return the config dict."""
diff --git a/backend/app/models/server_template.py b/backend/app/models/server_template.py
index 46910ac1..a3031c20 100644
--- a/backend/app/models/server_template.py
+++ b/backend/app/models/server_template.py
@@ -35,9 +35,7 @@ class ServerTemplate(JsonColumnMixin, TimestampMixin, db.Model):
created_by = db.Column(db.Integer, db.ForeignKey('users.id'))
- # cascade: template_id is NOT NULL — assignments die with the template.
- assignments = db.relationship('ServerTemplateAssignment', backref='template',
- lazy='dynamic', cascade='all, delete-orphan')
+ assignments = db.relationship('ServerTemplateAssignment', backref='template', lazy='dynamic')
def _get_json(self, field):
return self._json_read(field, [])
@@ -174,9 +172,7 @@ class ServerTemplateAssignment(JsonColumnMixin, db.Model):
applied_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
- # cascade: server_id is NOT NULL — assignments die with the server too.
- server = db.relationship('Server', backref=db.backref(
- 'template_assignments', lazy='dynamic', cascade='all, delete-orphan'))
+ server = db.relationship('Server', backref=db.backref('template_assignments', lazy='dynamic'))
__table_args__ = (
db.UniqueConstraint('template_id', 'server_id', name='uq_template_server'),
diff --git a/backend/app/models/source_connection.py b/backend/app/models/source_connection.py
index 3a3fd4e6..f28237ea 100644
--- a/backend/app/models/source_connection.py
+++ b/backend/app/models/source_connection.py
@@ -28,9 +28,7 @@ class SourceConnection(SerializableMixin, db.Model):
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
last_used_at = db.Column(db.DateTime, nullable=True)
- # cascade: user_id is NOT NULL — a user's git credentials die with the account.
- user = db.relationship('User', backref=db.backref(
- 'source_connections', lazy='dynamic', cascade='all, delete-orphan'))
+ user = db.relationship('User', backref=db.backref('source_connections', lazy='dynamic'))
__table_args__ = (
db.UniqueConstraint('user_id', 'provider', name='uq_source_connection_user_provider'),
diff --git a/backend/app/models/webhook.py b/backend/app/models/webhook.py
index 39bcbceb..0121ca2b 100644
--- a/backend/app/models/webhook.py
+++ b/backend/app/models/webhook.py
@@ -172,10 +172,7 @@ class GitDeployment(db.Model):
created_at = db.Column(db.DateTime, default=datetime.utcnow)
# Relationships
- # cascade: app_id is NOT NULL — purge must delete, not null out. (GitWebhook
- # above keeps a plain backref: its app_id is nullable.)
- app = db.relationship('Application', backref=db.backref(
- 'git_deployments', lazy='dynamic', cascade='all, delete-orphan'))
+ app = db.relationship('Application', backref=db.backref('git_deployments', lazy='dynamic'))
webhook = db.relationship('GitWebhook', backref=db.backref('deployments', lazy='dynamic'))
def to_dict(self):
diff --git a/backend/app/models/wordpress_site.py b/backend/app/models/wordpress_site.py
index 15356538..64400f58 100644
--- a/backend/app/models/wordpress_site.py
+++ b/backend/app/models/wordpress_site.py
@@ -100,10 +100,7 @@ class WordPressSite(JsonColumnMixin, TimestampMixin, db.Model):
# Timestamps
# Relationships
- # cascade: application_id is NOT NULL, so a real delete of the app (Recycle
- # Bin purge) must take this row with it — the default null-out IntegrityErrors.
- application = db.relationship('Application', backref=db.backref(
- 'wp_site', uselist=False, cascade='all, delete-orphan'))
+ application = db.relationship('Application', backref=db.backref('wp_site', uselist=False))
environments = db.relationship(
'WordPressSite',
backref=db.backref('production_site', remote_side=[id]),
@@ -113,21 +110,17 @@ class WordPressSite(JsonColumnMixin, TimestampMixin, db.Model):
vulnerabilities = db.relationship('WordPressVulnerability', backref='site', lazy='dynamic', cascade='all, delete-orphan')
update_runs = db.relationship('WordPressUpdateRun', backref='site', lazy='dynamic', cascade='all, delete-orphan')
reports = db.relationship('WordPressReport', backref='site', lazy='dynamic', cascade='all, delete-orphan')
- # cascade on both: the site FKs are NOT NULL, so a sync job cannot outlive
- # either endpoint — deleting a site takes its job history along.
sync_jobs_as_source = db.relationship(
'SyncJob',
foreign_keys='SyncJob.source_site_id',
backref='source_site',
- lazy='dynamic',
- cascade='all, delete-orphan'
+ lazy='dynamic'
)
sync_jobs_as_target = db.relationship(
'SyncJob',
foreign_keys='SyncJob.target_site_id',
backref='target_site',
- lazy='dynamic',
- cascade='all, delete-orphan'
+ lazy='dynamic'
)
def to_dict(self, include_environments=False, include_snapshots=False):
diff --git a/backend/app/models/workflow.py b/backend/app/models/workflow.py
index e8997222..4a300d74 100644
--- a/backend/app/models/workflow.py
+++ b/backend/app/models/workflow.py
@@ -29,9 +29,7 @@ class Workflow(JsonColumnMixin, TimestampMixin, db.Model):
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
# Relationships
- # cascade: user_id is NOT NULL — a user's workflows die with the account.
- user = db.relationship('User', backref=db.backref(
- 'workflows', lazy='dynamic', cascade='all, delete-orphan'))
+ user = db.relationship('User', backref=db.backref('workflows', lazy='dynamic'))
executions = db.relationship('WorkflowExecution', backref='workflow', lazy='dynamic', cascade='all, delete-orphan')
def to_dict(self):
diff --git a/backend/app/models/workspace.py b/backend/app/models/workspace.py
index fa4eafe5..4dd5c24b 100644
--- a/backend/app/models/workspace.py
+++ b/backend/app/models/workspace.py
@@ -36,12 +36,8 @@ class Workspace(JsonColumnMixin, TimestampMixin, db.Model):
created_by = db.Column(db.Integer, db.ForeignKey('users.id'))
- # cascade: both child FKs are NOT NULL — memberships and keys die with the
- # workspace, or the default FK null-out IntegrityErrors on delete.
- members = db.relationship('WorkspaceMember', backref='workspace',
- lazy='dynamic', cascade='all, delete-orphan')
- api_keys = db.relationship('WorkspaceApiKey', backref='workspace',
- lazy='dynamic', cascade='all, delete-orphan')
+ members = db.relationship('WorkspaceMember', backref='workspace', lazy='dynamic')
+ api_keys = db.relationship('WorkspaceApiKey', backref='workspace', lazy='dynamic')
@property
def settings(self):
@@ -89,9 +85,7 @@ class WorkspaceMember(db.Model):
joined_at = db.Column(db.DateTime, default=datetime.utcnow)
- # cascade: user_id is NOT NULL — memberships die with the account too.
- user = db.relationship('User', backref=db.backref(
- 'workspace_memberships', lazy='dynamic', cascade='all, delete-orphan'))
+ user = db.relationship('User', backref=db.backref('workspace_memberships', lazy='dynamic'))
__table_args__ = (
db.UniqueConstraint('workspace_id', 'user_id', name='uq_workspace_user'),
diff --git a/backend/tests/test_application_soft_delete.py b/backend/tests/test_application_soft_delete.py
index c828d2a0..3fa05668 100644
--- a/backend/tests/test_application_soft_delete.py
+++ b/backend/tests/test_application_soft_delete.py
@@ -190,39 +190,25 @@ def test_purge_takes_the_one_to_one_policy_rows_with_it(app, dead_app, monkeypat
assert Deployment.query.filter_by(app_id=dead_app.id).first() is None
-# Relationships DELIBERATELY left without a delete cascade. Each entry must be
-# backed by something that keeps the parent delete from ever reaching the FK
-# null-out — a guard, or the absence of any delete path:
-# User.applications — delete_user REFUSES (409) while the user owns apps;
-# apps go through app delete + Recycle Bin purge so
-# containers/volumes are cleaned, never a cascade.
-# CloudProvider.servers — no code path deletes a CloudProvider row today;
-# silently dropping the inventory of provisioned
-# (billing!) VMs must stay a deliberate decision.
-DELIBERATELY_UNCASCADED = {
- 'User.applications',
- 'CloudProvider.servers',
-}
-
-
def test_every_not_null_child_relationship_cascades_deletes(app):
"""The invariant behind the purge crash, pinned for EVERY model: a
one-to-many whose child FK is NOT NULL must carry a delete cascade, because
SQLAlchemy's default on parent delete — dynamic relationships included — is
to NULL the child FK, which the NOT NULL constraint turns into an
IntegrityError the moment anything hard-deletes the parent (Recycle Bin
- purge, retention pruning, admin deletes). Exceptions are enumerated and
- justified in DELIBERATELY_UNCASCADED above."""
- from sqlalchemy import inspect as sa_inspect
+ purge, retention pruning, admin deletes).
+
+ The cascade is applied by _delete_cascade_policy's mapper hook, so this is
+ a test that THE DOOR WORKS, not a checklist for model authors. Exceptions
+ live (with their justification) in DELIBERATELY_UNCASCADED there."""
+ from sqlalchemy.orm import configure_mappers
+
+ from app.models._delete_cascade_policy import DELIBERATELY_UNCASCADED
with app.app_context():
+ configure_mappers()
offenders = set()
- seen = set()
for mapper in db.Model.registry.mappers:
- cls = mapper.class_
- if cls in seen:
- continue
- seen.add(cls)
for rel in mapper.relationships:
if rel.direction.name != 'ONETOMANY' or rel.viewonly:
continue
@@ -230,13 +216,13 @@ def test_every_not_null_child_relationship_cascades_deletes(app):
if not fk_cols or all(c.nullable for c in fk_cols):
continue
if 'delete' not in rel.cascade:
- offenders.add(f'{cls.__name__}.{rel.key}')
- unexpected = offenders - DELIBERATELY_UNCASCADED
+ offenders.add(f'{mapper.class_.__name__}.{rel.key}')
+ unexpected = offenders - set(DELIBERATELY_UNCASCADED)
assert not unexpected, (
- 'NOT NULL child relationships without a delete cascade (a parent '
- f'hard-delete would IntegrityError): {sorted(unexpected)}')
- # The allowlist may only shrink: an entry that stops matching is stale.
- stale = DELIBERATELY_UNCASCADED - offenders
+ 'NOT NULL child relationships the cascade policy did not reach '
+ f'(a parent hard-delete would IntegrityError): {sorted(unexpected)}')
+ # The registry may only shrink: an entry that stops matching is stale.
+ stale = set(DELIBERATELY_UNCASCADED) - offenders
assert not stale, f'stale DELIBERATELY_UNCASCADED entries: {sorted(stale)}'