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.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
fix(models): close all 26 dangling-on-delete FKs + orphan sweep migration
Juan Denisf34969eaac6b
diff --git a/backend/app/api/workspaces.py b/backend/app/api/workspaces.pyindex ea6a54f3..86050f71 100644--- a/backend/app/api/workspaces.py+++ b/backend/app/api/workspaces.py@@ -115,7 +115,10 @@ def delete_workspace(workspace_id):user = get_current_user()if not user.is_admin:return jsonify({'error': 'Admin access required'}), 403- result = WorkspaceService.delete_workspace(workspace_id)+ try:+ result = WorkspaceService.delete_workspace(workspace_id)+ except ValueError as exc:+ return jsonify({'error': str(exc)}), 409if not result:return jsonify({'error': 'Workspace not found'}), 404return jsonify({'message': 'Workspace deleted'})diff --git a/backend/app/models/_delete_cascade_policy.py b/backend/app/models/_delete_cascade_policy.pyindex 2b4c70f2..0b7d4689 100644--- a/backend/app/models/_delete_cascade_policy.py+++ b/backend/app/models/_delete_cascade_policy.py@@ -35,6 +35,9 @@ DELIBERATELY_UNCASCADED = {'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',+ 'Workspace.projects':+ 'projects contain environments and app groupings; delete_workspace '+ 'refuses (409) while any remain rather than silently destroying them',}diff --git a/backend/app/models/ai.py b/backend/app/models/ai.pyindex ca1f7fc0..fd24fca9 100644--- a/backend/app/models/ai.py+++ b/backend/app/models/ai.py@@ -50,6 +50,10 @@ class AiConversation(JsonColumnMixin, TimestampMixin, db.Model):pending_actions = db.relationship('AiPendingAction', backref='conversation', cascade='all, delete-orphan', lazy='dynamic',)+ # Parent-side backref so the delete-cascade policy covers the NOT NULL FK:+ # a user's conversations die with the account.+ user = db.relationship('User',+ backref=db.backref('ai_conversations', lazy='dynamic'))@propertydef export(self) -> dict:@@ -154,6 +158,9 @@ class AiPendingAction(JsonColumnMixin, db.Model):db.String(64), db.ForeignKey('ai_conversations.id', ondelete='CASCADE'), index=True, nullable=False,)user_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True, nullable=False)+ # Parent-side backref so the delete-cascade policy covers the NOT NULL FK.+ user = db.relationship('User',+ backref=db.backref('ai_pending_actions', lazy='dynamic'))tool_name = db.Column(db.String(128), nullable=False) # qualified name, e.g. core__restart_docker_containerplugin_slug = db.Column(db.String(128)) # None => built-in toolparams_json = db.Column(db.Text)diff --git a/backend/app/models/api_key.py b/backend/app/models/api_key.pyindex f412e02f..1d4558c9 100644--- a/backend/app/models/api_key.py+++ b/backend/app/models/api_key.py@@ -25,7 +25,10 @@ class ApiKey(JsonColumnMixin, db.Model):created_at = db.Column(db.DateTime, default=datetime.utcnow)revoked_at = db.Column(db.DateTime, nullable=True)- user = db.relationship('User', foreign_keys=[user_id])+ # Parent-side backref so the delete-cascade policy covers the NOT NULL FK:+ # a user's API keys die with the account.+ user = db.relationship('User', foreign_keys=[user_id],+ backref=db.backref('api_keys', lazy='dynamic'))TIER_STANDARD = 'standard'TIER_ELEVATED = 'elevated'diff --git a/backend/app/models/application_manifest.py b/backend/app/models/application_manifest.pyindex 7c8541c1..7658178a 100644--- a/backend/app/models/application_manifest.py+++ b/backend/app/models/application_manifest.py@@ -26,6 +26,9 @@ class ApplicationManifest(TimestampMixin, JsonColumnMixin, db.Model):id = db.Column(db.Integer, primary_key=True)project_id = db.Column(db.Integer, db.ForeignKey('projects.id'), nullable=False, index=True)+ # Parent-side backref so the delete-cascade policy covers the NOT NULL FK.+ project = db.relationship('Project',+ backref=db.backref('manifests', lazy='dynamic'))raw_text = db.Column(db.Text, nullable=True) # the manifest file as committednormalized_json = db.Column(db.Text, nullable=True) # ManifestSpecService.normalize() outputdiff --git a/backend/app/models/application_preview.py b/backend/app/models/application_preview.pyindex 1be63c36..53201d25 100644--- a/backend/app/models/application_preview.py+++ b/backend/app/models/application_preview.py@@ -32,6 +32,9 @@ class ApplicationPreview(TimestampMixin, JsonColumnMixin, db.Model):id = db.Column(db.Integer, primary_key=True)application_id = db.Column(db.Integer, db.ForeignKey('applications.id'), nullable=False, index=True)+ # Parent-side backref so the delete-cascade policy covers the NOT NULL FK.+ application = db.relationship('Application',+ backref=db.backref('previews', lazy='dynamic'))pr_number = db.Column(db.Integer, nullable=False)pr_title = db.Column(db.String(500), nullable=True)@@ -88,6 +91,9 @@ class ApplicationPreviewSettings(TimestampMixin, db.Model):application_id = db.Column(db.Integer, db.ForeignKey('applications.id'),primary_key=True, unique=True, nullable=False)+ # Parent-side backref so the delete-cascade policy covers the NOT NULL FK.+ application = db.relationship('Application',+ backref=db.backref('preview_settings', uselist=False))enabled = db.Column(db.Boolean, default=False, nullable=False)domain_template = db.Column(diff --git a/backend/app/models/dashboard.py b/backend/app/models/dashboard.pyindex aca2fc25..72e5055d 100644--- a/backend/app/models/dashboard.py+++ b/backend/app/models/dashboard.py@@ -36,6 +36,10 @@ class DashboardBoard(TimestampMixin, db.Model):nullable=False,index=True,)+ # The DB-level ondelete above is inert on SQLite (FK enforcement is off);+ # this parent-side backref lets the delete-cascade policy do it in the ORM.+ user = db.relationship('User',+ backref=db.backref('dashboard_boards', lazy='dynamic'))# The shipped-default id this board came from ('overview' / 'infra' /# 'apps'). NULL for boards the user created themselves — those have no# default to reset to.diff --git a/backend/app/models/ddns_host.py b/backend/app/models/ddns_host.pyindex 1ea084f7..1ed11540 100644--- a/backend/app/models/ddns_host.py+++ b/backend/app/models/ddns_host.py@@ -23,7 +23,10 @@ class DdnsHost(db.Model):created_at = db.Column(db.DateTime, default=datetime.utcnow)- zone = db.relationship('DNSZone')+ # Parent-side backref so the delete-cascade policy covers the NOT NULL FK:+ # a DDNS host is meaningless without its zone.+ zone = db.relationship('DNSZone',+ backref=db.backref('ddns_hosts', lazy='dynamic'))@staticmethoddef generate_token():diff --git a/backend/app/models/env_variable.py b/backend/app/models/env_variable.pyindex 27823221..06ab01c1 100644--- a/backend/app/models/env_variable.py+++ b/backend/app/models/env_variable.py@@ -17,6 +17,11 @@ class EnvironmentVariable(TimestampMixin, JsonColumnMixin, db.Model):id = db.Column(db.Integer, primary_key=True)application_id = db.Column(db.Integer, db.ForeignKey('applications.id'), nullable=False)+ # Parent-side backref so the delete-cascade policy covers the NOT NULL FK:+ # env vars hold SECRETS — SQLite can reuse a purged app id, so orphans here+ # could silently attach to a future application.+ application = db.relationship('Application',+ backref=db.backref('env_variables', lazy='dynamic'))key = db.Column(db.String(255), nullable=False)encrypted_value = db.Column(db.Text, nullable=False)is_secret = db.Column(db.Boolean, default=False) # Mark sensitive values@@ -136,6 +141,9 @@ class EnvironmentVariableHistory(db.Model):id = db.Column(db.Integer, primary_key=True)env_variable_id = db.Column(db.Integer, nullable=False) # Not FK to allow deleted varsapplication_id = db.Column(db.Integer, db.ForeignKey('applications.id'), nullable=False)+ # Parent-side backref so the delete-cascade policy covers the NOT NULL FK.+ application = db.relationship('Application',+ backref=db.backref('env_variable_history', lazy='dynamic'))key = db.Column(db.String(255), nullable=False)action = db.Column(db.String(20), nullable=False) # 'created', 'updated', 'deleted'old_value_hash = db.Column(db.String(64), nullable=True) # SHA256 hash (not the actual value)diff --git a/backend/app/models/event_subscription.py b/backend/app/models/event_subscription.pyindex 76daf1d5..ba7fd8c9 100644--- a/backend/app/models/event_subscription.py+++ b/backend/app/models/event_subscription.py@@ -21,7 +21,9 @@ class EventSubscription(TimestampMixin, JsonColumnMixin, db.Model):retry_count = db.Column(db.Integer, default=3)timeout_seconds = db.Column(db.Integer, default=10)- user = db.relationship('User', foreign_keys=[user_id])+ # Parent-side backref so the delete-cascade policy covers the NOT NULL FK.+ user = db.relationship('User', foreign_keys=[user_id],+ backref=db.backref('event_subscriptions', lazy='dynamic'))deliveries = db.relationship('EventDelivery', back_populates='subscription',lazy='dynamic', cascade='all, delete-orphan')diff --git a/backend/app/models/exposed_service.py b/backend/app/models/exposed_service.pyindex bf9ee309..c997699c 100644--- a/backend/app/models/exposed_service.py+++ b/backend/app/models/exposed_service.py@@ -28,7 +28,9 @@ class ExposedService(TimestampMixin, db.Model):last_error = db.Column(db.Text)- tunnel = db.relationship('Tunnel')+ # Parent-side backref so the delete-cascade policy covers the NOT NULL FK.+ tunnel = db.relationship('Tunnel',+ backref=db.backref('exposed_services', lazy='dynamic'))def url(self):if not self.hostname:diff --git a/backend/app/models/fleet_doctor_result.py b/backend/app/models/fleet_doctor_result.pyindex 4b57929b..87e97782 100644--- a/backend/app/models/fleet_doctor_result.py+++ b/backend/app/models/fleet_doctor_result.py@@ -30,6 +30,9 @@ class FleetDoctorResult(JsonColumnMixin, db.Model):id = db.Column(db.Integer, primary_key=True)server_id = db.Column(db.String(36), db.ForeignKey('servers.id'),nullable=False, index=True)+ # Parent-side backref so the delete-cascade policy covers the NOT NULL FK.+ server = db.relationship('Server',+ backref=db.backref('fleet_doctor_results', lazy='dynamic'))check_key = db.Column(db.String(160), nullable=False, index=True)status = db.Column(db.String(16), nullable=False, server_default='ok')title = db.Column(db.String(200), nullable=True)diff --git a/backend/app/models/invitation.py b/backend/app/models/invitation.pyindex ee0aeb8d..77af8365 100644--- a/backend/app/models/invitation.py+++ b/backend/app/models/invitation.py@@ -26,7 +26,10 @@ class Invitation(JsonColumnMixin, db.Model):created_at = db.Column(db.DateTime, default=datetime.utcnow)# Relationships- inviter = db.relationship('User', foreign_keys=[invited_by])+ # Parent-side backref so the delete-cascade policy covers the NOT NULL FK:+ # pending invitations die with the inviter's account.+ inviter = db.relationship('User', foreign_keys=[invited_by],+ backref=db.backref('sent_invitations', lazy='dynamic'))accepter = db.relationship('User', foreign_keys=[accepted_by])@propertydiff --git a/backend/app/models/login_link.py b/backend/app/models/login_link.pyindex 80e77c3b..c78ff0cb 100644--- a/backend/app/models/login_link.py+++ b/backend/app/models/login_link.py@@ -28,7 +28,9 @@ class LoginLink(db.Model):bound_ip = db.Column(db.String(64), nullable=True)created_at = db.Column(db.DateTime, default=datetime.utcnow)- user = db.relationship('User', foreign_keys=[user_id])+ # Parent-side backref so the delete-cascade policy covers the NOT NULL FK.+ user = db.relationship('User', foreign_keys=[user_id],+ backref=db.backref('login_links', lazy='dynamic'))created_by = db.relationship('User', foreign_keys=[created_by_id])@propertydiff --git a/backend/app/models/project.py b/backend/app/models/project.pyindex d9de64ed..e6ac58bf 100644--- a/backend/app/models/project.py+++ b/backend/app/models/project.py@@ -17,6 +17,11 @@ class Project(JsonColumnMixin, TimestampMixin, db.Model):id = db.Column(db.Integer, primary_key=True)workspace_id = db.Column(db.Integer, db.ForeignKey('workspaces.id'), nullable=False, index=True)+ # DELIBERATELY not cascaded (see _delete_cascade_policy): projects contain+ # environments and app groupings — delete_workspace refuses while any+ # remain instead of silently destroying them.+ workspace = db.relationship('Workspace',+ backref=db.backref('projects', lazy='dynamic'))name = db.Column(db.String(128), nullable=False)slug = db.Column(db.String(128), nullable=False)description = db.Column(db.Text, nullable=True)diff --git a/backend/app/models/proxy_stack.py b/backend/app/models/proxy_stack.pyindex 98291aed..975852b9 100644--- a/backend/app/models/proxy_stack.py+++ b/backend/app/models/proxy_stack.py@@ -28,6 +28,8 @@ class ProxyStack(TimestampMixin, JsonColumnMixin, db.Model):# 1:1 with a server. Unique so get_or_create never creates duplicates;# indexed for the per-server lookup the API does on every request.+ # Parent-side backref (below the column) lets the delete-cascade policy+ # cover the NOT NULL FK: the stack record dies with its server.server_id = db.Column(db.String(36),db.ForeignKey('servers.id'),@@ -35,6 +37,8 @@ class ProxyStack(TimestampMixin, JsonColumnMixin, db.Model):index=True,unique=True,)+ server = db.relationship('Server',+ backref=db.backref('proxy_stack', uselist=False))proxy_type = db.Column(db.String(20), nullable=False, default=PROXY_NGINX)# stopped | running | error | unknowndiff --git a/backend/app/models/restore_drill.py b/backend/app/models/restore_drill.pyindex dfd84ad0..d9d3b9da 100644--- a/backend/app/models/restore_drill.py+++ b/backend/app/models/restore_drill.py@@ -21,6 +21,10 @@ class RestoreDrill(JsonColumnMixin, db.Model):id = db.Column(db.Integer, primary_key=True)policy_id = db.Column(db.Integer, db.ForeignKey('backup_policies.id'), nullable=False, index=True)+ # Parent-side backref so the delete-cascade policy covers the NOT NULL FK:+ # drill history dies with its policy.+ policy = db.relationship('BackupPolicy',+ backref=db.backref('restore_drills', lazy='dynamic'))# The run whose restore-point (chain endpoint) was drilled.run_id = db.Column(db.Integer, db.ForeignKey('backup_runs.id'), nullable=True, index=True)job_id = db.Column(db.String(36), nullable=True, index=True)diff --git a/backend/app/models/server.py b/backend/app/models/server.pyindex d3bdd544..42a7b12b 100644--- a/backend/app/models/server.py+++ b/backend/app/models/server.py@@ -653,7 +653,9 @@ class AgentRollout(TimestampMixin, db.Model):started_at = db.Column(db.DateTime)completed_at = db.Column(db.DateTime)- version = db.relationship('AgentVersion')+ # Parent-side backref so the delete-cascade policy covers the NOT NULL FK.+ version = db.relationship('AgentVersion',+ backref=db.backref('rollouts', lazy='dynamic'))def to_dict(self):return {diff --git a/backend/app/models/server_survey.py b/backend/app/models/server_survey.pyindex c569bbc1..721c082f 100644--- a/backend/app/models/server_survey.py+++ b/backend/app/models/server_survey.py@@ -25,6 +25,9 @@ class ServerSurvey(JsonColumnMixin, db.Model):id = db.Column(db.Integer, primary_key=True)server_id = db.Column(db.String(36), db.ForeignKey('servers.id'), nullable=False, index=True)+ # Parent-side backref so the delete-cascade policy covers the NOT NULL FK.+ server = db.relationship('Server',+ backref=db.backref('surveys', lazy='dynamic'))catalog_version = db.Column(db.Integer, nullable=False, default=1)taken_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, index=True)diff --git a/backend/app/models/tunnel.py b/backend/app/models/tunnel.pyindex 17cc4aec..20c38e8b 100644--- a/backend/app/models/tunnel.py+++ b/backend/app/models/tunnel.py@@ -37,8 +37,14 @@ class Tunnel(TimestampMixin, db.Model):last_error = db.Column(db.Text)- edge_server = db.relationship('Server', foreign_keys=[edge_server_id])- private_server = db.relationship('Server', foreign_keys=[private_server_id])+ # Parent-side backrefs so the delete-cascade policy covers both NOT NULL+ # FKs: a tunnel cannot outlive either of its endpoints.+ edge_server = db.relationship(+ 'Server', foreign_keys=[edge_server_id],+ backref=db.backref('tunnels_as_edge', lazy='dynamic'))+ private_server = db.relationship(+ 'Server', foreign_keys=[private_server_id],+ backref=db.backref('tunnels_as_private', lazy='dynamic'))def _prefix(self):return self.subnet.split('/')[-1] if self.subnet and '/' in self.subnet else '24'diff --git a/backend/app/models/waf_policy.py b/backend/app/models/waf_policy.pyindex 8766dcc2..eb249a79 100644--- a/backend/app/models/waf_policy.py+++ b/backend/app/models/waf_policy.py@@ -28,6 +28,9 @@ class WafPolicy(JsonColumnMixin, db.Model):unique=True,index=True,)+ # Parent-side backref so the delete-cascade policy covers the NOT NULL FK.+ application = db.relationship('Application',+ backref=db.backref('waf_policy', uselist=False))mode = db.Column(db.String(10), default='off', nullable=False)paranoia_level = db.Column(db.Integer, default=1, nullable=False) # 1-4diff --git a/backend/app/models/wordpress_custom_plugin.py b/backend/app/models/wordpress_custom_plugin.pyindex 868c7e22..1e2ad5b0 100644--- a/backend/app/models/wordpress_custom_plugin.py+++ b/backend/app/models/wordpress_custom_plugin.py@@ -94,6 +94,9 @@ class WordPressSitePlugin(SerializableMixin, db.Model):id = db.Column(db.Integer, primary_key=True)wordpress_site_id = db.Column(db.Integer, db.ForeignKey('wordpress_sites.id'), nullable=False, index=True)+ # Parent-side backref so the delete-cascade policy covers the NOT NULL FK.+ site = db.relationship('WordPressSite',+ backref=db.backref('plugin_installs', lazy='dynamic'))custom_plugin_id = db.Column(db.Integer, db.ForeignKey('wordpress_custom_plugins.id'), nullable=False, index=True)diff --git a/backend/app/models/workspace.py b/backend/app/models/workspace.pyindex 4dd5c24b..a87950a5 100644--- a/backend/app/models/workspace.py+++ b/backend/app/models/workspace.py@@ -164,7 +164,9 @@ class ResourceGrant(db.Model):db.UniqueConstraint('user_id', 'resource_type', 'resource_id', name='uq_resource_grant'),)- user = db.relationship('User', foreign_keys=[user_id])+ # Parent-side backref so the delete-cascade policy covers the NOT NULL FK.+ user = db.relationship('User', foreign_keys=[user_id],+ backref=db.backref('resource_grants', lazy='dynamic'))def to_dict(self):return {diff --git a/backend/app/queue_bus/models.py b/backend/app/queue_bus/models.pyindex 9c48f4f5..514080ff 100644--- a/backend/app/queue_bus/models.py+++ b/backend/app/queue_bus/models.py@@ -138,7 +138,10 @@ class QueueMessage(db.Model):completed_at = db.Column(db.DateTime, nullable=True)queue = db.relationship('Queue', back_populates='messages')- group = db.relationship('QueueGroup')+ # Parent-side backref so the delete-cascade policy covers the NOT NULL+ # group FK directly (the queue chain already cascades, this closes the FK).+ group = db.relationship('QueueGroup',+ backref=db.backref('messages', lazy='dynamic'))def get_payload(self):if self.payload_json:diff --git a/backend/app/services/workspace_service.py b/backend/app/services/workspace_service.pyindex 40179113..69bd1a1d 100644--- a/backend/app/services/workspace_service.py+++ b/backend/app/services/workspace_service.py@@ -239,6 +239,14 @@ class WorkspaceService:ws = Workspace.query.get(workspace_id)if not ws:return False+ # Projects never ride a workspace delete (they carry environments and+ # app groupings) — Workspace.projects is deliberately uncascaded, so+ # without this refusal the delete would IntegrityError anyway.+ project_count = ws.projects.count()+ if project_count:+ raise ValueError(+ f'Workspace still contains {project_count} project(s) — '+ 'delete or move them first')WorkspaceApiKey.query.filter_by(workspace_id=workspace_id).delete()WorkspaceMember.query.filter_by(workspace_id=workspace_id).delete()db.session.delete(ws)diff --git a/backend/migrations/versions/095_purge_orphaned_child_rows.py b/backend/migrations/versions/095_purge_orphaned_child_rows.pynew file mode 100644index 00000000..edb5dc5a--- /dev/null+++ b/backend/migrations/versions/095_purge_orphaned_child_rows.py@@ -0,0 +1,78 @@+"""Purge child rows orphaned by past parent hard-deletes.++Before the delete-cascade policy (app/models/_delete_cascade_policy.py) and+the parent-side relationships that feed it, hard-deleting a parent left its+NOT NULL-FK children behind: SQLite ships with FK enforcement off, so nothing+stopped the delete, and nothing cleaned up after it. Worse, SQLite may reuse a+deleted parent's id, so an orphaned row — an application's env-var SECRETS+being the ugly case — could silently attach to a future record.++This is the one-off sweep for installs that accumulated such orphans. Going+forward the ORM cascades (or an explicit guard on the parent's delete path)+keep these tables clean, so downgrade has nothing to restore.++Revision ID: 095_purge_orphaned_child_rows+Revises: 094_connection_provider_health+Create Date: 2026-08-31+"""++import sqlalchemy as sa+from alembic import op++revision = '095_purge_orphaned_child_rows'+down_revision = '094_connection_provider_health'+branch_labels = None+depends_on = None++# (child_table, fk_column, parent_table) — the 26 audited relationship-less+# NOT NULL FKs, plus the Application children the first cascade fix covered+# (their orphans from purges before that fix are just as stale).+ORPHAN_SWEEP = [+ ('agent_rollouts', 'version_id', 'agent_versions'),+ ('ai_conversations', 'user_id', 'users'),+ ('ai_pending_actions', 'user_id', 'users'),+ ('api_keys', 'user_id', 'users'),+ ('application_manifests', 'project_id', 'projects'),+ ('application_preview_settings', 'application_id', 'applications'),+ ('application_previews', 'application_id', 'applications'),+ ('container_scale_policies', 'application_id', 'applications'),+ ('container_sleep_policies', 'application_id', 'applications'),+ ('dashboard_boards', 'user_id', 'users'),+ ('ddns_hosts', 'zone_id', 'dns_zones'),+ ('deployments', 'app_id', 'applications'),+ ('environment_variable_history', 'application_id', 'applications'),+ ('environment_variables', 'application_id', 'applications'),+ ('event_subscriptions', 'user_id', 'users'),+ ('exposed_services', 'tunnel_id', 'tunnels'),+ ('fleet_doctor_results', 'server_id', 'servers'),+ ('invitations', 'invited_by', 'users'),+ ('login_links', 'user_id', 'users'),+ ('projects', 'workspace_id', 'workspaces'),+ ('proxy_stacks', 'server_id', 'servers'),+ ('queue_messages', 'group_id', 'queue_groups'),+ ('resource_grants', 'user_id', 'users'),+ ('restore_drills', 'policy_id', 'backup_policies'),+ ('server_surveys', 'server_id', 'servers'),+ ('tunnels', 'edge_server_id', 'servers'),+ ('tunnels', 'private_server_id', 'servers'),+ ('waf_policies', 'application_id', 'applications'),+ ('wordpress_site_plugins', 'wordpress_site_id', 'wordpress_sites'),+]+++def upgrade():+ bind = op.get_bind()+ existing = set(sa.inspect(bind).get_table_names())+ for child, fk, parent in ORPHAN_SWEEP:+ if child not in existing or parent not in existing:+ continue+ bind.execute(sa.text(+ f'DELETE FROM {child} ' # noqa: S608 — names+ f'WHERE {fk} IS NOT NULL ' # come from the fixed+ f'AND {fk} NOT IN (SELECT id FROM {parent})' # list above+ ))+++def downgrade():+ # The deleted rows were orphans — there is nothing meaningful to restore.+ passdiff --git a/backend/tests/test_application_soft_delete.py b/backend/tests/test_application_soft_delete.pyindex 20f678b7..a9363dfb 100644--- a/backend/tests/test_application_soft_delete.py+++ b/backend/tests/test_application_soft_delete.py@@ -233,34 +233,9 @@ def test_every_not_null_child_relationship_cascades_deletes(app):# app is the nightmare case). Known debt, frozen so it can only SHRINK: a new# model declares the parent-side relationship instead (the door then handles# its delete), or consciously adds itself here in the commit that explains why.-KNOWN_DANGLING_ON_DELETE = {- 'agent_rollouts.version_id -> agent_versions',- 'ai_conversations.user_id -> users',- 'ai_pending_actions.user_id -> users',- 'api_keys.user_id -> users',- 'application_manifests.project_id -> projects',- 'application_preview_settings.application_id -> applications',- 'application_previews.application_id -> applications',- 'dashboard_boards.user_id -> users',- 'ddns_hosts.zone_id -> dns_zones',- 'environment_variable_history.application_id -> applications',- 'environment_variables.application_id -> applications',- 'event_subscriptions.user_id -> users',- 'exposed_services.tunnel_id -> tunnels',- 'fleet_doctor_results.server_id -> servers',- 'invitations.invited_by -> users',- 'login_links.user_id -> users',- 'projects.workspace_id -> workspaces',- 'proxy_stacks.server_id -> servers',- 'queue_messages.group_id -> queue_groups',- 'resource_grants.user_id -> users',- 'restore_drills.policy_id -> backup_policies',- 'server_surveys.server_id -> servers',- 'tunnels.edge_server_id -> servers',- 'tunnels.private_server_id -> servers',- 'waf_policies.application_id -> applications',- 'wordpress_site_plugins.wordpress_site_id -> wordpress_sites',-}+KNOWN_DANGLING_ON_DELETE = set() # all 26 audited FKs now declare the+# parent-side relationship (the door cascades them, or the parent's delete+# path guards) — keep this EMPTY.def test_dangling_on_delete_fk_set_may_only_shrink(app):@@ -299,6 +274,26 @@ def test_dangling_on_delete_fk_set_may_only_shrink(app):f'these entries are fixed — remove them from the set: {sorted(fixed)}')+def test_deleting_a_workspace_with_projects_is_refused(app):+ """The Workspace.projects entry in DELIBERATELY_UNCASCADED is only honest+ while delete_workspace refuses instead of 500ing."""+ import pytest as _pytest++ from app.models import Project+ from app.models.workspace import Workspace+ from app.services.workspace_service import WorkspaceService++ with app.app_context():+ ws = Workspace(name='doomed-ws', slug='doomed-ws')+ db.session.add(ws)+ db.session.commit()+ db.session.add(Project(name='keeper', slug='keeper', workspace_id=ws.id))+ db.session.commit()+ with _pytest.raises(ValueError, match='still contains'):+ WorkspaceService.delete_workspace(ws.id)+ assert Workspace.query.get(ws.id) is not None++def test_deleting_a_user_who_owns_applications_is_refused(app, client, auth_headers, dead_app):"""The User.applications entry in DELIBERATELY_UNCASCADED is only honestwhile delete_user refuses instead of 500ing — even for a tombstoned app,