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
feat(recycle-bin): applications are soft-deletable, and a delete stops keeping data hostage
Juan Denis5f8a3ef204f0
diff --git a/backend/app/api/app_volumes.py b/backend/app/api/app_volumes.pyindex 32b79de4..b2f559d9 100644--- a/backend/app/api/app_volumes.py+++ b/backend/app/api/app_volumes.py@@ -17,7 +17,7 @@ app_volumes_bp = Blueprint('app_volumes', __name__)def _load_app_for(app_id, *, write):"""Resolve (user, app) with the right ACL, or an (error_response, status)."""user = User.query.get(get_jwt_identity())- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return None, None, (jsonify({'error': 'Application not found'}), 404)allowed = (ResourceGrantService.can_edit_app(user, app) if writediff --git a/backend/app/api/apps.py b/backend/app/api/apps.pyindex 751ab773..275e451e 100644--- a/backend/app/api/apps.py+++ b/backend/app/api/apps.py@@ -203,7 +203,7 @@ def link_apps(app_id):"""Link two apps as prod/dev pair sharing database resources."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -225,7 +225,7 @@ def link_apps(app_id):if as_environment not in valid_environments:return jsonify({'error': f'Invalid environment. Must be one of: {", ".join(valid_environments)}'}), 400- target_app = Application.query.get(target_app_id)+ target_app = Application.query_active().filter_by(id=target_app_id).first()if not target_app:return jsonify({'error': 'Target application not found'}), 404@@ -302,7 +302,7 @@ def get_linked_apps(app_id):"""Get apps linked to this app."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -349,7 +349,7 @@ def unlink_apps(app_id):"""Unlink apps and reset environment types."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -360,6 +360,10 @@ def unlink_apps(app_id):if not app.linked_app_id:return jsonify({'error': 'App is not linked to any other app'}), 400+ # Deliberately NOT query_active: this is the reciprocal half of a link the+ # caller is severing, not "an app to operate on". If the partner is already+ # in the recycle bin its back-pointer still has to be cleared, or it would+ # restore holding a link to an app that no longer links back.target_app = Application.query.get(app.linked_app_id)# Reset both apps@@ -386,7 +390,7 @@ def update_environment(app_id):"""Update environment type for an app."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -432,7 +436,10 @@ def get_apps():from app.services.workspace_service import WorkspaceServicews_id = WorkspaceService.resolve_workspace_id(user, request.headers.get('X-Workspace-Id') or request.args.get('workspace_id'))- query = WorkspaceService.scope_query(Application.query, Application, user,+ # query_active() is the base the whole chain narrows: scope_query and+ # apply_query only ever add filters, so scoping here keeps deleted apps out+ # of the list (and out of $filter/$top/total) without touching either.+ query = WorkspaceService.scope_query(Application.query_active(), Application, user,workspace_id=ws_id, owner_attr='user_id',grant_resource_type='application')@@ -493,7 +500,7 @@ def set_app_workspace(app_id):from app.models.workspace import Workspacefrom app.services.workspace_service import WorkspaceServiceuser = User.query.get(get_jwt_identity())- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404# Use user.id (int) for comparisons — get_jwt_identity() is the stringified token id.@@ -562,7 +569,7 @@ def move_apps_to_project():updated = []skipped = []for app_id in app_ids:- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:skipped.append(app_id)continue@@ -678,7 +685,7 @@ def _can_edit_app(user, app):@jwt_required()def get_app(app_id):user = User.query.get(get_jwt_identity())- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -699,7 +706,7 @@ def get_compose_services(app_id):non-compose apps or when the base compose can't be read."""user = User.query.get(get_jwt_identity())- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404if not _can_access_app(user, app):@@ -717,7 +724,7 @@ def list_app_grants(app_id):"""List who has been granted access to this app (owner-or-admin)."""from app.services.resource_grant_service import ResourceGrantServiceuser = User.query.get(get_jwt_identity())- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404if user.role != 'admin' and app.user_id != user.id:@@ -732,7 +739,7 @@ def grant_app_access(app_id):"""Grant a user access to this app (owner-or-admin). Body: {user_id, role?}."""from app.services.resource_grant_service import ResourceGrantServiceuser = User.query.get(get_jwt_identity())- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404if user.role != 'admin' and app.user_id != user.id:@@ -760,7 +767,7 @@ def revoke_app_access(app_id, grant_id):"""Revoke a grant on this app (owner-or-admin)."""from app.services.resource_grant_service import ResourceGrantServiceuser = User.query.get(get_jwt_identity())- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404if user.role != 'admin' and app.user_id != user.id:@@ -832,6 +839,9 @@ def create_app_from_repository():else:return jsonify({'error': 'port must be a number'}), 400+ # NOT query_active: a tombstone keeps reserving its name (and, below, its+ # directory under APPS_DIR). Letting a new app take the name of one sitting+ # in the recycle bin would make the restore collide.if Application.query.filter_by(name=name, server_id=None).first():return jsonify({'error': f'An application named "{name}" already exists'}), 400@@ -992,6 +1002,9 @@ def create_app_from_repository():db.session.rollback()if app.id:GitService.remove_deployment(app.id)+ # Unwinding a create that failed, not deleting an app someone made:+ # a hard delete (no query_active, no tombstone) is what belongs+ # here — a half-created service must not land in the recycle bin.existing_app = Application.query.get(app.id)if existing_app:db.session.delete(existing_app)@@ -1113,6 +1126,8 @@ def create_manual_app():return jsonify({'error': 'docker-compose.yml not found and no compose_file provided'}), 400compose_file = 'docker-compose.yml'+ # NOT query_active: a tombstone keeps reserving its name so a restore can't+ # collide with an app created in the meantime.if Application.query.filter_by(name=name).first():return jsonify({'error': f'An application named "{name}" already exists'}), 400@@ -1185,8 +1200,15 @@ def upload_app_archive():if ws_id is None:ws_id = WorkspaceService.ensure_default_workspace().id- existing = Application.query.filter_by(name=name).first()- is_update = existing is not None and existing.source == 'upload'+ # The name lookup serves two purposes and a tombstone answers them+ # differently. It still RESERVES the name (so the unfiltered fallback), but+ # it is never the row an upload updates in place: that path extracts a new+ # version over the app's storage and compose_up's it, which would resurrect+ # an app the user deleted. Ask for the live row first so a tombstone can+ # never shadow it; a tombstone-only hit falls through to "already exists".+ existing = (Application.query_active().filter_by(name=name).first()+ or Application.query.filter_by(name=name).first())+ is_update = existing is not None and existing.is_active and existing.source == 'upload'temp_dir = os.path.join(paths.SERVERKIT_CACHE_DIR, 'uploads')os.makedirs(temp_dir, exist_ok=True)@@ -1299,7 +1321,7 @@ def get_app_versions(app_id):"""List versions for an uploaded app."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -1325,7 +1347,7 @@ def rollback_app_version(app_id):"""Roll an uploaded app back to a previous version."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -1375,7 +1397,7 @@ def rollback_app_version(app_id):def update_app(app_id):current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -1425,12 +1447,26 @@ def update_app(app_id):@apps_bp.route('/<int:app_id>', methods=['DELETE'])@jwt_required()def delete_app(app_id):- import shutil- from app.services.nginx_service import NginxService+ """Soft-delete an app: stop it serving, keep the record and the data.++ What used to happen here — compose_down(volumes=True) and rmtree of the+ uploaded source — has moved to the PURGE hook. Doing it here while keeping+ a tombstone would put a Restore button next to a row whose data had already+ been destroyed. The reversible half (containers down, vhost removed,+ firewall closed, cron suspended) still happens now; see+ services/application_restore.py.++ `?purge=true` is the escape hatch for "I do not want this in the bin",+ and it runs the irreversible half immediately.+ """+ from app.services import application_restore, recycle_bin_servicecurrent_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ # query_active: deleting something already in the bin is a 404, not a+ # second delete that would re-stamp deleted_at and restart the retention+ # clock on a row the user cannot even see on this page.+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -1438,70 +1474,28 @@ def delete_app(app_id):if not user.is_admin and app.user_id != user.id:return jsonify({'error': 'Access denied'}), 403- cleanup_results = {- 'docker': None,- 'folder': None,- 'nginx': None- }-- # Appliance tier (plan 35): close any public firewall ports this app opened- # so a delete leaves no orphaned holes in the firewall.- try:- from app.services.app_port_service import AppPortService- declared_ports = AppPortService.get_ports(app)- if declared_ports:- cleanup_results['firewall'] = AppPortService.close_firewall(declared_ports)- except Exception as e:- cleanup_results['firewall'] = {'error': str(e)}-- # For Docker apps, stop and remove containers (and, by default, volumes).- #- # Database engines are the exception: destroying the data volume is the one- # irreversible part of an uninstall, so an app installed from a template- # carrying an `engine:` block KEEPS its volumes unless the caller explicitly- # asks for `?remove_data=true`. Everything else keeps the historic- # volumes=True default. `?remove_data=` (or `?volumes=`) overrides either way.- remove_data = _remove_data_flag(app)- if app.app_type == 'docker' and app.root_path:- try:- # Stop and remove containers, networks, and (optionally) volumes- result = DockerService.compose_down(- app.root_path,- volumes=remove_data,- remove_orphans=True,- compose_file=_local_compose_file(app)- )- cleanup_results['docker'] = result- cleanup_results['data_volumes_removed'] = remove_data- except Exception as e:- cleanup_results['docker'] = {'error': str(e)}+ purge_now = str(request.args.get('purge', '')).lower() in ('1', 'true', 'yes')- # Delete the app folder only for ServerKit-managed uploads.- # Manual apps point at existing paths that must not be removed.- try:- if app.source == 'upload' and app.root_path and app.root_path.startswith(paths.APPS_DIR):- app_storage = get_app_storage_dir(app.name)- if os.path.exists(app_storage):- shutil.rmtree(app_storage)- cleanup_results['folder'] = {'success': True}- except Exception as e:- cleanup_results['folder'] = {'error': str(e)}-- # Remove nginx site config- try:- NginxService.disable_site(app.name)- NginxService.delete_site(app.name)- cleanup_results['nginx'] = {'success': True}- except Exception as e:- cleanup_results['nginx'] = {'error': str(e)}+ cleanup_results = application_restore.suspend_application(app, user_id=current_user_id)- # Delete from database- db.session.delete(app)- db.session.commit()+ if purge_now:+ # Carry the caller's data intent into the purge hook. Without this a+ # `?purge=true&remove_data=false` -- and every database-engine uninstall,+ # which defaults to preserving its volumes -- would lose the data the+ # flag exists to protect.+ app._purge_remove_data = _remove_data_flag(app)+ ok, warning = recycle_bin_service.purge('application', app.id)+ return jsonify({+ 'message': 'Application deleted permanently',+ 'purged': ok,+ 'cleanup': cleanup_results,+ 'warning': warning,+ }), 200return jsonify({- 'message': 'Application deleted successfully',- 'cleanup': cleanup_results+ 'message': 'Application moved to the recycle bin',+ 'recycle_bin': True,+ 'cleanup': cleanup_results,}), 200@@ -1510,7 +1504,7 @@ def delete_app(app_id):def start_app(app_id):current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -1568,7 +1562,7 @@ def apply_image_update(app_id):"""Pull the newest image for a compose-managed app and recreate it."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -1621,7 +1615,7 @@ def apply_image_update(app_id):@jwt_required()def get_sleep_policy(app_id):user = User.query.get(get_jwt_identity())- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404if not _can_access_app(user, app):@@ -1633,7 +1627,7 @@ def get_sleep_policy(app_id):@jwt_required()def update_sleep_policy(app_id):user = User.query.get(get_jwt_identity())- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404if not _can_edit_app(user, app):@@ -1648,7 +1642,7 @@ def update_sleep_policy(app_id):@jwt_required()def sleep_app(app_id):user = User.query.get(get_jwt_identity())- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404if not _can_edit_app(user, app):@@ -1663,7 +1657,7 @@ def sleep_app(app_id):@jwt_required()def wake_app(app_id):user = User.query.get(get_jwt_identity())- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404if not _can_edit_app(user, app):@@ -1721,7 +1715,7 @@ def _parse_docker_stats(stats):def get_app_resources(app_id):"""The app's configured CPU/memory limits plus best-effort live usage."""user = User.query.get(get_jwt_identity())- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404if not _can_access_app(user, app):@@ -1754,7 +1748,7 @@ def update_app_resources(app_id):saved and take effect on the next restart/redeploy."""user = User.query.get(get_jwt_identity())- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404if not _can_edit_app(user, app):@@ -1811,7 +1805,7 @@ def set_micro_cache(app_id):takes effect on first publish."""user = User.query.get(get_jwt_identity())- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404if not _can_edit_app(user, app):@@ -1860,7 +1854,7 @@ def purge_micro_cache(app_id):is near-harmless, and no nginx reload is needed."""user = User.query.get(get_jwt_identity())- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404if not _can_edit_app(user, app):@@ -1881,7 +1875,7 @@ def purge_micro_cache(app_id):@jwt_required()def get_scale_policy(app_id):user = User.query.get(get_jwt_identity())- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404if not _can_access_app(user, app):@@ -1893,7 +1887,7 @@ def get_scale_policy(app_id):@jwt_required()def update_scale_policy(app_id):user = User.query.get(get_jwt_identity())- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404if not _can_edit_app(user, app):@@ -1907,7 +1901,7 @@ def update_scale_policy(app_id):@jwt_required()def scale_app(app_id):user = User.query.get(get_jwt_identity())- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404if not _can_edit_app(user, app):@@ -1925,7 +1919,7 @@ def scale_app(app_id):@jwt_required()def evaluate_scale(app_id):user = User.query.get(get_jwt_identity())- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404if not _can_edit_app(user, app):@@ -1951,7 +1945,7 @@ def scale_sweep():def stop_app(app_id):current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -1990,7 +1984,7 @@ def stop_app(app_id):def restart_app(app_id):current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -2036,7 +2030,7 @@ def get_app_related(app_id):whole card."""user = User.query.get(get_jwt_identity())- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404if not _can_access_app(user, app):@@ -2089,7 +2083,7 @@ def get_app_logs(app_id):"""Get logs for a specific application."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -2146,7 +2140,7 @@ def get_container_logs(app_id):"""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -2251,7 +2245,7 @@ def get_app_containers(app_id):"""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -2274,7 +2268,7 @@ def get_app_status(app_id):"""Get real-time status for a Docker application."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -2367,7 +2361,7 @@ def get_app_status(app_id):def _load_app_for_backup(app_id, edit=False):"""Load an app the current user may access (or edit). Returns (app, error)."""user = User.query.get(get_jwt_identity())- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return None, (jsonify({'error': 'Application not found'}), 404)allowed = _can_edit_app(user, app) if edit else _can_access_app(user, app)diff --git a/backend/app/api/backups.py b/backend/app/api/backups.pyindex fdb00dea..c7a70682 100644--- a/backend/app/api/backups.py+++ b/backend/app/api/backups.py@@ -359,7 +359,7 @@ def backup_application():if not app_id:return jsonify({'error': 'application_id is required'}), 400- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404diff --git a/backend/app/api/bandwidth.py b/backend/app/api/bandwidth.pyindex 3c756324..ebc84e71 100644--- a/backend/app/api/bandwidth.py+++ b/backend/app/api/bandwidth.py@@ -33,7 +33,7 @@ def get_apps_bandwidth():def get_app_bandwidth(app_id):"""Full daily series (default 90 days) + current-month total for one app,scoped to the app's workspace visibility (plan 29 #9 — foreign caller 404)."""- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()user = User.query.get(get_jwt_identity())if app is None or not ResourceGrantService.can_access_app(user, app):return jsonify({'error': 'Not found'}), 404diff --git a/backend/app/api/builds.py b/backend/app/api/builds.pyindex 9b38bf99..cca2b1a1 100644--- a/backend/app/api/builds.py+++ b/backend/app/api/builds.py@@ -29,7 +29,7 @@ def get_build_config(app_id):"""Get build configuration for an app."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -49,7 +49,7 @@ def get_build_config(app_id):@admin_requireddef configure_build(app_id):"""Configure build settings for an app."""- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -95,7 +95,7 @@ def detect_build_method(app_id):"""Auto-detect build method for an app."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -113,7 +113,7 @@ def get_nixpacks_plan(app_id):"""Get Nixpacks build plan for an app."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -133,7 +133,7 @@ def trigger_build(app_id):"""Trigger a build for an app."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -154,7 +154,7 @@ def get_build_logs(app_id):"""Get build log history for an app."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -173,7 +173,7 @@ def get_build_log_detail(app_id, timestamp):"""Get detailed build log including output."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -210,7 +210,7 @@ def deploy_app(app_id):"""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -253,7 +253,7 @@ def get_deployments(app_id):"""Get deployment history for an app."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -284,7 +284,9 @@ def get_deployment(deployment_id):if not deployment:return jsonify({'error': 'Deployment not found'}), 404- app = Application.query.get(deployment.app_id)+ app = Application.query_active().filter_by(id=deployment.app_id).first()+ if not app:+ return jsonify({'error': 'Application not found'}), 404if not ResourceGrantService.can_access_app(user, app):return jsonify({'error': 'Access denied'}), 403@@ -303,7 +305,9 @@ def get_deployment_diff(deployment_id):if not deployment:return jsonify({'error': 'Deployment not found'}), 404- app = Application.query.get(deployment.app_id)+ app = Application.query_active().filter_by(id=deployment.app_id).first()+ if not app:+ return jsonify({'error': 'Application not found'}), 404if not ResourceGrantService.can_access_app(user, app):return jsonify({'error': 'Access denied'}), 403@@ -321,7 +325,7 @@ def rollback(app_id):"""Rollback to a previous deployment."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -347,7 +351,7 @@ def get_current_deployment(app_id):"""Get the currently live deployment."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404diff --git a/backend/app/api/cron.py b/backend/app/api/cron.pyindex dae6438d..b0cef45b 100644--- a/backend/app/api/cron.py+++ b/backend/app/api/cron.py@@ -30,7 +30,10 @@ def _validate_application_id(raw):aid = int(raw)except (TypeError, ValueError):return _INVALID_APP- return aid if Application.query.get(aid) else _INVALID_APP+ # query_active: a deleted app is not a legal cron target — its jobs were+ # suspended by the delete, so attaching a new one would resurrect work for+ # something that is in the bin.+ return aid if Application.query_active().filter_by(id=aid).first() else _INVALID_APPdef _attach_attribution(jobs):@@ -48,6 +51,10 @@ def _attach_attribution(jobs):if not ids:return jobs+ # Deliberately unfiltered. This is attribution only — no side effects — and+ # the jobs of a deleted app are suspended, not removed. Naming the app they+ # belonged to explains why they are suspended; dropping to the unattributed+ # "System" bucket would make them look like they were never linked.apps = {a.id: a for a in Application.query.filter(Application.id.in_(ids)).all()}ws_ids = {a.workspace_id for a in apps.values() if a.workspace_id}workspaces = ({w.id: w for w in Workspace.query.filter(Workspace.id.in_(ws_ids)).all()}@@ -300,6 +307,9 @@ def _notify_run_transition(job_id, transition, run):aid = job.get('application_id')if aid:from app.models import Application+ # Unfiltered for the same reason as _attach_attribution: this only+ # labels an alert, and a run reported for a deleted app is exactly the+ # case where the operator needs to see which app it was.app = Application.query.get(int(aid))if app:payload['app'] = app.namediff --git a/backend/app/api/database_engines.py b/backend/app/api/database_engines.pyindex 473888e5..75cad416 100644--- a/backend/app/api/database_engines.py+++ b/backend/app/api/database_engines.py@@ -138,7 +138,7 @@ def _require_app_access(app_id):user = User.query.get(get_jwt_identity())if not user:return {'error': 'Unauthorized'}, 401- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return {'error': 'Application not found'}, 404if not ResourceGrantService.can_access_app(user, app):diff --git a/backend/app/api/databases.py b/backend/app/api/databases.pyindex 5f2481d1..0fa018f9 100644--- a/backend/app/api/databases.py+++ b/backend/app/api/databases.py@@ -683,7 +683,7 @@ def list_all_docker_databases():ws_id = WorkspaceService.resolve_workspace_id(user, request.headers.get('X-Workspace-Id') or request.args.get('workspace_id'))app_q = WorkspaceService.scope_query(- Application.query.filter_by(app_type='docker'), Application, user,+ Application.query_active().filter_by(app_type='docker'), Application, user,workspace_id=ws_id, owner_attr='user_id', grant_resource_type='application')out = []@@ -712,7 +712,7 @@ def get_app_databases(app_id):"""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404diff --git a/backend/app/api/deploy.py b/backend/app/api/deploy.pyindex 1551d236..e7ca1dde 100644--- a/backend/app/api/deploy.py+++ b/backend/app/api/deploy.py@@ -20,7 +20,7 @@ def get_deploy_config(app_id):"""Get deployment configuration for an app."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -43,7 +43,7 @@ def get_deploy_config(app_id):@admin_requireddef configure_deployment(app_id):"""Configure Git deployment for an app."""- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -82,7 +82,7 @@ def trigger_deploy(app_id):"""Trigger a deployment."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -102,7 +102,7 @@ def pull_changes(app_id):"""Pull latest changes without running deploy scripts."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -122,7 +122,7 @@ def get_git_status(app_id):"""Get Git status for an app."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -140,7 +140,7 @@ def get_commit_info(app_id):"""Get current commit info for an app."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -165,7 +165,7 @@ def get_deployment_history():limit = request.args.get('limit', 50, type=int)if app_id:- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404if not user or app_access_tier(user, app) is None:@@ -215,7 +215,7 @@ def get_branches(app_id):"""Get list of remote branches for an app's repository."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -250,7 +250,7 @@ def get_webhook_logs():limit = request.args.get('limit', 50, type=int)if app_id:- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404if not user or app_access_tier(user, app) is None:diff --git a/backend/app/api/deployment_jobs.py b/backend/app/api/deployment_jobs.pyindex d236dfe4..410cf469 100644--- a/backend/app/api/deployment_jobs.py+++ b/backend/app/api/deployment_jobs.py@@ -20,7 +20,7 @@ def _job_visible_to(user, job):"""Read gate for one job: app-linked jobs follow the app's grant seam;app-less jobs belong to their requester (or a panel admin)."""if job.app_id:- app = Application.query.get(job.app_id)+ app = Application.query_active().filter_by(id=job.app_id).first()return app is not None and ResourceGrantService.can_access_app(user, app)return user.is_admin or job.requested_by == user.id@@ -29,7 +29,7 @@ def _job_operable_by(user, job):"""Operate gate (retry): app-linked jobs need member+ on the app; app-lessjobs stay requester-or-admin."""if job.app_id:- app = Application.query.get(job.app_id)+ app = Application.query_active().filter_by(id=job.app_id).first()return app is not None and ResourceGrantService.can_operate_app(user, app)return user.is_admin or job.requested_by == user.id@@ -86,7 +86,7 @@ def list_deployment_jobs():limit = request.args.get('limit', 50, type=int)if app_id:- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404if not user or app_access_tier(user, app) is None:diff --git a/backend/app/api/deployments.py b/backend/app/api/deployments.pyindex 4e0d1f9d..340e8d51 100644--- a/backend/app/api/deployments.py+++ b/backend/app/api/deployments.py@@ -22,7 +22,7 @@ deployments_bp = Blueprint('deployments', __name__)def _access(app_id):from app.services.resource_grant_service import ResourceGrantServiceuser = User.query.get(get_jwt_identity())- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return None, (jsonify({'error': 'Application not found'}), 404)if not ResourceGrantService.can_access_app(user, app):diff --git a/backend/app/api/dns_zones.py b/backend/app/api/dns_zones.pyindex c1961d99..6ef36563 100644--- a/backend/app/api/dns_zones.py+++ b/backend/app/api/dns_zones.py@@ -210,6 +210,10 @@ def list_managed_records():from app.services.dns_ownership_service import DnsOwnershipServicefrom app.models.application import Applicationrows = DnsOwnershipService.list_all()+ # Deliberately unfiltered. These records still EXIST at the provider after+ # the app that created them is deleted, and this table is where an operator+ # goes to find orphans; blanking app_name would turn the traceable ones into+ # unattributed records. Display only — nothing here acts on the app.app_names = {a.id: a.name for a in Application.query.all()} if rows else {}out = []for r in rows:diff --git a/backend/app/api/docker.py b/backend/app/api/docker.pyindex 410e7e2e..46a0761e 100644--- a/backend/app/api/docker.py+++ b/backend/app/api/docker.py@@ -603,7 +603,11 @@ def cleanup_all_apps():results = []# Get all apps from database- docker_apps = Application.query.filter_by(app_type='docker').all()+ # query_active: this loop runs compose_down(volumes=True), rmtree(root_path)+ # and a HARD db.session.delete. Over tombstones it would destroy the data a+ # soft delete deliberately kept and empty the Recycle Bin as a side effect of+ # a Docker cleanup. Purging a deleted app is the bin's job, not this one's.+ docker_apps = Application.query_active().filter_by(app_type='docker').all()for app in docker_apps:app_result = {'name': app.name, 'success': True, 'steps': []}diff --git a/backend/app/api/domains.py b/backend/app/api/domains.pyindex 559a98e9..c5e9a9c9 100644--- a/backend/app/api/domains.py+++ b/backend/app/api/domains.py@@ -107,7 +107,7 @@ def get_domains():ws_id = WorkspaceService.resolve_workspace_id(user, request.headers.get('X-Workspace-Id') or request.args.get('workspace_id'))app_q = WorkspaceService.scope_query(- Application.query, Application, user,+ Application.query_active(), Application, user,workspace_id=ws_id, owner_attr='user_id', grant_resource_type='application')app_ids = [row[0] for row in app_q.with_entities(Application.id).all()]domains = (Domain.query_active().filter(Domain.application_id.in_(app_ids)).all()@@ -128,7 +128,12 @@ def get_domain(domain_id):if not domain:return jsonify({'error': 'Domain not found'}), 404- app = Application.query.get(domain.application_id)+ # A soft-deleted app keeps its Domain rows (only the vhost is torn down), so+ # every route here has to resolve the parent live or a deleted app's domains+ # stay reachable — and operable, up to a real ACME order in enable_ssl.+ app = Application.query_active().filter_by(id=domain.application_id).first()+ if not app:+ return jsonify({'error': 'Domain not found'}), 404if not ResourceGrantService.can_access_app(user, app):return jsonify({'error': 'Access denied'}), 403@@ -164,7 +169,7 @@ def create_domain():return jsonify({'error': 'Domain already exists'}), 409# Check if application exists and user has access- app = Application.query.get(application_id)+ app = Application.query_active().filter_by(id=application_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -254,7 +259,7 @@ def suggest_subdomain():prefill the 'give this a subdomain' action. Honours an optional ``base``."""from app.services.site_domain_service import SiteDomainServiceapp_id = request.args.get('application_id', type=int)- app = Application.query.get(app_id) if app_id else None+ app = Application.query_active().filter_by(id=app_id).first() if app_id else Nonebase = SiteDomainService.resolve_base(request.args.get('base'))if not base:return jsonify({'base_domain': None, 'suggestion': None,@@ -273,7 +278,8 @@ def give_subdomain():current_user_id = get_jwt_identity()user = User.query.get(current_user_id)data = request.get_json() or {}- app = Application.query.get(data.get('application_id')) if data.get('application_id') else None+ app = (Application.query_active().filter_by(id=data.get('application_id')).first()+ if data.get('application_id') else None)if not app:return jsonify({'error': 'Application not found'}), 404if not ResourceGrantService.can_edit_app(user, app):@@ -294,7 +300,9 @@ def update_domain(domain_id):if not domain:return jsonify({'error': 'Domain not found'}), 404- app = Application.query.get(domain.application_id)+ app = Application.query_active().filter_by(id=domain.application_id).first()+ if not app:+ return jsonify({'error': 'Domain not found'}), 404if not ResourceGrantService.can_edit_app(user, app):return jsonify({'error': 'Access denied'}), 403@@ -328,7 +336,9 @@ def delete_domain(domain_id):if not domain:return jsonify({'error': 'Domain not found'}), 404- app = Application.query.get(domain.application_id)+ app = Application.query_active().filter_by(id=domain.application_id).first()+ if not app:+ return jsonify({'error': 'Domain not found'}), 404if not ResourceGrantService.can_edit_app(user, app):return jsonify({'error': 'Access denied'}), 403@@ -369,7 +379,9 @@ def enable_ssl(domain_id):if not domain:return jsonify({'error': 'Domain not found'}), 404- app = Application.query.get(domain.application_id)+ app = Application.query_active().filter_by(id=domain.application_id).first()+ if not app:+ return jsonify({'error': 'Domain not found'}), 404if not ResourceGrantService.can_edit_app(user, app):return jsonify({'error': 'Access denied'}), 403@@ -421,7 +433,9 @@ def disable_ssl(domain_id):if not domain:return jsonify({'error': 'Domain not found'}), 404- app = Application.query.get(domain.application_id)+ app = Application.query_active().filter_by(id=domain.application_id).first()+ if not app:+ return jsonify({'error': 'Domain not found'}), 404if not ResourceGrantService.can_edit_app(user, app):return jsonify({'error': 'Access denied'}), 403@@ -444,7 +458,9 @@ def renew_ssl(domain_id):if not domain:return jsonify({'error': 'Domain not found'}), 404- app = Application.query.get(domain.application_id)+ app = Application.query_active().filter_by(id=domain.application_id).first()+ if not app:+ return jsonify({'error': 'Domain not found'}), 404if not ResourceGrantService.can_edit_app(user, app):return jsonify({'error': 'Access denied'}), 403@@ -517,7 +533,7 @@ def get_ssl_status():@admin_requireddef regenerate_nginx_config(app_id):"""Regenerate nginx config for a Docker app."""- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -580,7 +596,7 @@ def diagnose_app_routing(app_id):"""from app.services.docker_service import DockerService- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -675,7 +691,7 @@ def test_app_routing(app_id):Performs active tests to verify traffic can flow from domain to container."""- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404diff --git a/backend/app/api/env_vars.py b/backend/app/api/env_vars.pyindex c39c7362..2be61b1a 100644--- a/backend/app/api/env_vars.py+++ b/backend/app/api/env_vars.py@@ -25,7 +25,7 @@ def check_app_access(app_id, user_id, write=False):read-only). Returns ``(user, app, None, None)`` on success or``(None, None, error_response, status)`` on failure."""user = User.query.get(user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return None, None, jsonify({'error': 'Application not found'}), 404diff --git a/backend/app/api/git.py b/backend/app/api/git.pyindex 2e3e2ffc..d7e20376 100644--- a/backend/app/api/git.py+++ b/backend/app/api/git.py@@ -25,6 +25,9 @@ def _webhook_visible_to(user, webhook):(owner/admin/grant/workspace member — plan 29 #11)."""if not getattr(webhook, 'app_id', None):return True+ # Deliberately unfiltered: this gate falls through to "panel-wide visible"+ # when the app can't be resolved, so hiding tombstones here would WIDEN+ # access — deleting an app would publish its webhook to every viewer.app = Application.query.get(webhook.app_id)if app is None:return True@@ -451,7 +454,7 @@ def get_deployment(deployment_id):if deployment is None:return jsonify({'success': False, 'error': 'Deployment not found'}), 404- app = Application.query.get(deployment.app_id)+ app = Application.query_active().filter_by(id=deployment.app_id).first()if app is None or app_access_tier(get_current_user(), app) is None:return jsonify({'success': False, 'error': 'Access denied'}), 403diff --git a/backend/app/api/image_updates.py b/backend/app/api/image_updates.pyindex e289085a..3c361dc8 100644--- a/backend/app/api/image_updates.py+++ b/backend/app/api/image_updates.py@@ -35,7 +35,7 @@ def latest(app_id):Scoped to the app's workspace visibility (plan 29 #9) — a foreign callergets a sealed 404."""- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()user = User.query.get(get_jwt_identity())if app is None or not ResourceGrantService.can_access_app(user, app):return jsonify({'error': 'Not found'}), 404diff --git a/backend/app/api/manifests.py b/backend/app/api/manifests.pyindex 42668993..f6336b63 100644--- a/backend/app/api/manifests.py+++ b/backend/app/api/manifests.py@@ -61,7 +61,7 @@ def scaffold_manifest():if not app_id:return jsonify({'error': 'app_id is required'}), 400- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -191,7 +191,8 @@ def reset_bootstrap():if err:return errdata = request.get_json(silent=True) or {}- app = Application.query.get(data.get('app_id')) if data.get('app_id') else None+ app = (Application.query_active().filter_by(id=data.get('app_id')).first()+ if data.get('app_id') else None)if not app:return jsonify({'error': 'Application not found'}), 404if (data.get('confirm') or '') != app.name:diff --git a/backend/app/api/previews.py b/backend/app/api/previews.pyindex 0e4eec7e..35f04171 100644--- a/backend/app/api/previews.py+++ b/backend/app/api/previews.py@@ -21,7 +21,7 @@ def _get_app_or_404(app_id, write=False):"""Resolve the app and enforce per-app access (plan 29 #9). ``write`` requirescan_edit_app (owner/admin/editor); otherwise can_access_app (adds workspacemembers). A caller without the needed tier gets a sealed 404 (no leak)."""- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return None, (jsonify({'error': 'Application not found'}), 404)user = User.query.get(get_jwt_identity())diff --git a/backend/app/api/private_urls.py b/backend/app/api/private_urls.pyindex 7aab6a6a..fa0079d0 100644--- a/backend/app/api/private_urls.py+++ b/backend/app/api/private_urls.py@@ -28,7 +28,7 @@ def enable_private_url(app_id):"""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -90,7 +90,7 @@ def get_private_url(app_id):"""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -120,7 +120,7 @@ def update_private_url(app_id):"""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -172,7 +172,7 @@ def disable_private_url(app_id):"""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -209,7 +209,7 @@ def regenerate_private_url(app_id):"""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -260,7 +260,10 @@ def resolve_private_url(slug):Returns:JSON with app_id, app_name, port, and status"""- app = Application.query.filter_by(+ # Slug-keyed: a tombstone still holds its slug (that reservation is what+ # keeps a restore from colliding), so an unfiltered .first() could resolve+ # /p/<slug> to a deleted app and hand out its port.+ app = Application.query_active().filter_by(private_slug=slug,private_url_enabled=True).first()diff --git a/backend/app/api/python.py b/backend/app/api/python.pyindex b33c3f3c..08f1e2b8 100644--- a/backend/app/api/python.py+++ b/backend/app/api/python.py@@ -18,7 +18,7 @@ def get_app_or_404(app_id, current_user_id):(user.id), which also fixes the int-vs-str identity comparison."""from app.services.resource_grant_service import ResourceGrantServiceuser = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return None, ({'error': 'Application not found'}, 404)diff --git a/backend/app/api/shared_resources.py b/backend/app/api/shared_resources.pyindex 21952fd6..36a07190 100644--- a/backend/app/api/shared_resources.py+++ b/backend/app/api/shared_resources.py@@ -74,10 +74,11 @@ def _resolve_app(resource_type, resource_id):except (TypeError, ValueError):return Noneif resource_type == 'application':- return Application.query.get(rid)+ return Application.query_active().filter_by(id=rid).first()if resource_type == 'wordpress':site = WordPressSite.query.get(rid)- return Application.query.get(site.application_id) if site else None+ return (Application.query_active().filter_by(id=site.application_id).first()+ if site else None)return Nonediff --git a/backend/app/api/snapshots.py b/backend/app/api/snapshots.pyindex a4ac4b46..26ff72c4 100644--- a/backend/app/api/snapshots.py+++ b/backend/app/api/snapshots.py@@ -26,7 +26,7 @@ def _get_app_or_404(app_id, write=False):"""Resolve the app and enforce per-app access (plan 29 #9). ``write`` requirescan_edit_app (owner/admin/editor); otherwise can_access_app. A caller withoutthe needed tier gets a 403 (the resource itself exists)."""- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return None, (jsonify({'error': 'Application not found'}), 404)user = get_current_user()diff --git a/backend/app/api/templates.py b/backend/app/api/templates.pyindex 7fe1faa4..cbbfd3ca 100644--- a/backend/app/api/templates.py+++ b/backend/app/api/templates.py@@ -401,6 +401,8 @@ def validate_installation():errors.append(error)# Check if app name is taken+ # Deliberately unfiltered: a tombstone keeps RESERVING its name, or a+ # new app takes it and the restore is refused (_live_name_clash).if app_name:existing = Application.query.filter_by(name=app_name).first()if existing:@@ -509,7 +511,7 @@ def check_app_update(app_id):"""Check if an installed app has updates available."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -527,7 +529,7 @@ def check_app_update(app_id):def update_app(app_id):"""Update an app to the latest template version."""current_user_id = get_jwt_identity()- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404@@ -542,7 +544,7 @@ def get_app_template_info(app_id):"""Get template installation info for an app."""current_user_id = get_jwt_identity()user = User.query.get(current_user_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return jsonify({'error': 'Application not found'}), 404diff --git a/backend/app/api/waf.py b/backend/app/api/waf.pyindex 9ebcbd4e..4fc505c9 100644--- a/backend/app/api/waf.py+++ b/backend/app/api/waf.py@@ -34,7 +34,7 @@ def _get_application_or_404(app_id):"""Resolve the app and enforce read access (plan 29 #9): owner / admin / grant /workspace member. A caller who can't access it gets the same 404 as a missingapp (sealed-from-open, no existence leak)."""- application = Application.query.get(app_id)+ application = Application.query_active().filter_by(id=app_id).first()if not application:return None, (jsonify({'error': 'Application not found'}), 404)if not ResourceGrantService.can_access_app(get_current_user(), application):diff --git a/backend/app/jobs/builtin_handlers.py b/backend/app/jobs/builtin_handlers.pyindex d6d0a548..b9d39f43 100644--- a/backend/app/jobs/builtin_handlers.py+++ b/backend/app/jobs/builtin_handlers.py@@ -250,6 +250,26 @@ def run_pairing_prune():pairing_service.prune_expired()+def run_recycle_bin_retention():+ """Reap tombstones past the retention window.++ Nothing called `purge_expired` on a schedule before: a deleted domain is a+ row, and leaving rows around costs nothing anyone notices. Applications+ changed that -- their delete now KEEPS the data volumes and the uploaded+ source so a restore can work, and those are reclaimed by the purge hook. So+ without this the disk a delete used to free would never come back.++ Daily is the right cadence for a 30-day window; the exact hour is irrelevant+ and a shorter period would just re-scan the same rows.+ """+ from app.services import recycle_bin_service+ counts = recycle_bin_service.purge_expired()+ if counts:+ logger.info('Recycle bin retention: purged %s', counts)+ return counts+ return None++def run_registrar_expiry():"""Notify when a registrar domain crosses an expiry threshold."""from app.services.registrar_service import RegistrarService@@ -373,6 +393,7 @@ _BUILTINS = [('builtin.api_background', run_api_background, 'api-background', 3600, 3600),('builtin.pairing_prune', run_pairing_prune, 'pairing-prune', 3600, 60),('builtin.registrar_expiry', run_registrar_expiry, 'registrar-expiry', 86400, 300),+ ('builtin.recycle_retention', run_recycle_bin_retention, 'recycle-retention', 86400, 900),('builtin.backup_scheduler', run_backup_scheduler, 'backup-scheduler', 30, 30),('builtin.extension_updates', run_extension_update_check, 'extension-updates', 86400, 600),('builtin.security_feed', run_security_feed_check, 'security-feed', 86400, 600),diff --git a/backend/app/middleware/rbac.py b/backend/app/middleware/rbac.pyindex 341e5c6a..8bd24e41 100644--- a/backend/app/middleware/rbac.py+++ b/backend/app/middleware/rbac.py@@ -240,7 +240,10 @@ def require_app_member(min_role='viewer', arg='app_id'):if not user.is_active:return jsonify({'error': 'Account is deactivated'}), 403from app.models.application import Application- application = Application.query.get(kwargs.get(arg))+ # query_active: this decorator is a route guard, and every route+ # behind it ACTS on the app. A tombstone must 404 here rather than+ # be handed to the view in g.current_application.+ application = Application.query_active().filter_by(id=kwargs.get(arg)).first()if application is None:return jsonify({'error': 'Not found'}), 404tier = app_access_tier(user, application)diff --git a/backend/app/models/application.py b/backend/app/models/application.pyindex 42f48022..0c71574d 100644--- a/backend/app/models/application.py+++ b/backend/app/models/application.py@@ -7,13 +7,36 @@ from app import db# FK targets resolvable regardless of import order.from app.models import project as _project # noqa: F401from app.models import environment as _environment # noqa: F401+from app.models.mixins import SoftDeleteMixinfrom app.utils.ingress import (default_ingress_plane as _default_ingress_plane,proxy_eligible as _proxy_eligible,)-class Application(db.Model):+class Application(SoftDeleteMixin, db.Model):+ """A managed app.++ SOFT DELETED (plan 70). `Application.query` therefore returns TOMBSTONES —+ read `query_active()` anywhere you mean "an app that still exists". That+ distinction is not cosmetic here: this model drives nginx vhosts, container+ lifecycles, DNS, backups and outbound registry calls, and the equivalent+ oversight on `Domain` produced a WordPress search-replace to a dead host and+ real ACME orders.++ Two rules specific to this model:++ * **Sibling tables are the sharp edge.** `ContainerSleepPolicy`,+ `BackupPolicy`, `DeploymentJob` and `WafPolicy` are enumerated on a+ SCHEDULE and resolve the app afterwards, so they never appear in a search+ for `Application.query`. Each of those sweeps joins on liveness; see+ `deleted_app_ids()`.+ * **A soft delete keeps the files.** Stopping containers and unpublishing+ the vhost is reversible, so it happens on delete; removing data volumes+ and the uploaded source is not, so it waits for purge. See+ `application_restore.on_purge_application`.+ """+__tablename__ = 'applications'id = db.Column(db.Integer, primary_key=True)@@ -75,7 +98,12 @@ class Application(db.Model):upload_path = db.Column(db.String(500), nullable=True)# Private URL feature- private_slug = db.Column(db.String(50), unique=True, nullable=True, index=True)+ # NOT `unique=True`: the uniqueness is a PARTIAL index predicated on+ # `deleted_at IS NULL` (migration 084), so a tombstone releases its slug and+ # deleting an app does not burn `/p/<slug>` forever. Same shape as+ # Domain.name. A column-level unique here would re-impose the burn on any+ # database built from the models.+ private_slug = db.Column(db.String(50), nullable=True, index=True)private_url_enabled = db.Column(db.Boolean, default=False)# Opt-in nginx micro-cache (task #21): short-TTL page cache emitted into@@ -121,6 +149,24 @@ class Application(db.Model):project = db.relationship('Project', foreign_keys=[project_id], viewonly=True)environment = db.relationship('Environment', foreign_keys=[environment_id], viewonly=True)+ @classmethod+ def deleted_ids(cls):+ """Ids of every tombstoned app, as a set.++ For the sweeps that DO NOT start from Application — `ContainerSleepPolicy`,+ `BackupPolicy`, `DeploymentJob`, `WafPolicy` — which enumerate their own+ table on a schedule and resolve `application_id` afterwards. Those never+ appear in a search for `Application.query`, which is exactly how they+ would keep acting on a deleted app: waking its containers, running its+ backups, executing its queued deploys.++ A set, not a join: each of those sweeps is already written as "select my+ rows, then loop", and a set membership test drops into that loop without+ restructuring the query. The table is small enough that the cost is+ nothing next to the docker/restic work the loop is about to do.+ """+ return {row.id for row in cls.query_deleted().with_entities(cls.id).all()}+@propertydef live_domains(self):"""The domains this app actually serves — tombstones excluded.diff --git a/backend/app/models/environment.py b/backend/app/models/environment.pyindex 86eb2b17..6a333578 100644--- a/backend/app/models/environment.py+++ b/backend/app/models/environment.py@@ -35,7 +35,8 @@ class Environment(db.Model):}if include_counts:from app.models.application import Application- result['app_count'] = Application.query.filter_by(environment_id=self.id).count()+ # Live apps only — see Project.to_dict.+ result['app_count'] = Application.query_active().filter_by(environment_id=self.id).count()return resultdef __repr__(self):diff --git a/backend/app/models/project.py b/backend/app/models/project.pyindex b23128a9..d9b9009f 100644--- a/backend/app/models/project.py+++ b/backend/app/models/project.py@@ -59,7 +59,8 @@ class Project(db.Model):if include_counts:from app.models.application import Applicationresult['environment_count'] = self.environments.count()- result['app_count'] = Application.query.filter_by(project_id=self.id).count()+ # Live apps only — a project claiming 5 while showing 3 is just wrong.+ result['app_count'] = Application.query_active().filter_by(project_id=self.id).count()return resultdef __repr__(self):diff --git a/backend/app/services/ai_tools_builtin.py b/backend/app/services/ai_tools_builtin.pyindex 84285e13..e6f75f31 100644--- a/backend/app/services/ai_tools_builtin.py+++ b/backend/app/services/ai_tools_builtin.py@@ -60,7 +60,9 @@ def list_applications() -> list:A list of apps with name, status, type, and port."""from app.models.application import Application- return [a.to_dict() for a in Application.query.all()]+ # The assistant answers questions about what is RUNNING; a deleted app in+ # its context would be reported as though it still existed.+ return [a.to_dict() for a in Application.query_active().all()]def list_servers() -> list:diff --git a/backend/app/services/application_restore.py b/backend/app/services/application_restore.pynew file mode 100644index 00000000..8166d146--- /dev/null+++ b/backend/app/services/application_restore.py@@ -0,0 +1,207 @@+"""Recycle-bin hooks for Application: what a delete stops, and what a purge destroys.++The split this module exists to enforce:++ SOFT DELETE stop serving. Containers down (volumes KEPT), vhost removed,+ firewall ports closed, cron suspended. Every one of those is+ reversible.+ RESTORE re-publish. Vhost rewritten from the app's live domains,+ firewall reopened, cron resumed. Containers are left STOPPED.+ PURGE the irreversible half: data volumes removed, uploaded source+ tree deleted, cron association dropped, row destroyed.++Why the split matters: `delete_app` used to run `compose_down(volumes=True)` and+`shutil.rmtree()` on the way out. Doing that AND keeping a tombstone would offer+a Restore button for a row whose data the delete had already destroyed — the one+promise the recycle bin cannot break. So the destructive half moved to purge and+the tombstone now means something.++Containers are deliberately NOT restarted on restore, for the reason+`domain_restore` does not re-issue certificates: "put it back" should not+silently start processes, open ports to the internet, or begin consuming CPU on+a machine whose owner has not looked at this app in three weeks. The row is+back, it is published, and Start is one click away.+"""+import logging+import os+import shutil++from app import db+from app.models import Application+from app.services.cron_service import CronService++logger = logging.getLogger(__name__)+++def _live_name_clash(app):+ """Another LIVE app already using this one's name, if any."""+ return (Application.query_active()+ .filter(Application.name == app.name, Application.id != app.id)+ .first())+++def pre_restore_application(app):+ """Refuse a restore that cannot work, with a sentence the user can act on.++ Mirrors `pre_restore_domain`: a partial unique index makes "restorable" a+ moving target, so the conflict has to be reported rather than raised as an+ IntegrityError at commit.+ """+ if app.private_slug:+ clash = (Application.query_active()+ .filter(Application.private_slug == app.private_slug,+ Application.id != app.id)+ .first())+ if clash:+ return (f'the private URL “/p/{app.private_slug}” has been taken by '+ f'“{clash.name}” since this was deleted. Free it there first, '+ f'or leave this in the bin.')++ # `name` has no unique constraint, so this is NOT an integrity failure — but+ # a second live app with the same name means one nginx vhost filename for+ # two apps, and whichever writes last wins. Refusing is kinder than+ # restoring something that will silently fight over its own config.+ clash = _live_name_clash(app)+ if clash:+ return (f'“{app.name}” has been created again since this was deleted '+ f'(app #{clash.id}). Rename one of them first, or leave this in '+ f'the bin.')++ if app.root_path and not os.path.exists(app.root_path):+ return (f'its files are gone from {app.root_path}, so restoring the '+ f'record would give you an app with nothing to serve')++ return None+++def on_restore_application(app):+ """Re-publish a restored app. Returns a notice string, or None.++ Deliberately does NOT start containers — see the module docstring.+ """+ notices = []++ # Re-open any public ports the app declared. Best-effort: a firewall that+ # refuses is worth telling the user about, not worth failing the restore.+ try:+ from app.services.app_port_service import AppPortService+ declared = AppPortService.get_ports(app)+ if declared:+ AppPortService.open_firewall(declared)+ except Exception as exc: # noqa: BLE001+ logger.warning('Restore %s: firewall reopen failed: %s', app.name, exc)+ notices.append('its firewall ports could not be reopened')++ # Rewrite the vhost from the app's LIVE domains, through the same path the+ # domain restore uses — write_app_vhost re-enables the site and re-attaches+ # a covering wildcard cert, which a bare create_site would not.+ try:+ from app.services.site_domain_service import SiteDomainService+ result = SiteDomainService.write_app_vhost(app) or {}+ if result.get('warning'):+ notices.append(result['warning'])+ except Exception as exc: # noqa: BLE001+ logger.warning('Restore %s: vhost rewrite failed: %s', app.name, exc)+ notices.append(f'its vhost could not be rewritten ({exc})')++ # Re-enable exactly the cron jobs the delete suspended.+ try:+ resumed = CronService.resume_for_application(app.id)+ if resumed:+ notices.append(f'{resumed} cron job{"s" if resumed != 1 else ""} resumed')+ except Exception as exc: # noqa: BLE001+ logger.warning('Restore %s: cron resume failed: %s', app.name, exc)+ notices.append('its cron jobs could not be resumed')++ notices.append('containers were left stopped — start it when you are ready')+ return f'“{app.name}” is back: ' + '; '.join(notices) + '.'+++def on_purge_application(app):+ """The irreversible half of deleting an app.++ Runs immediately before the row is destroyed, from BOTH purge paths (an+ explicit purge and the retention sweep). Anything here is unrecoverable by+ definition, which is exactly why it is not on the delete path.+ """+ from app import paths+ from app.services.docker_service import DockerService+ from app.services.upload_service import get_app_storage_dir++ # A purge normally reclaims the volumes -- that is most of what it is for.+ # `_purge_remove_data` is the one exception: DELETE ?purge=true skips the+ # bin, and the caller may have said `?remove_data=false` (or be uninstalling+ # a database ENGINE, which defaults to preserving its volumes because losing+ # the data is the only irreversible part of that uninstall). The flag is+ # stamped on the row by that route; the retention sweep sets nothing and so+ # gets the default.+ remove_data = getattr(app, '_purge_remove_data', True)+ if app.app_type == 'docker' and app.root_path:+ try:+ DockerService.compose_down(app.root_path, volumes=remove_data,+ remove_orphans=True)+ except Exception as exc: # noqa: BLE001+ logger.warning('Purge %s: compose down failed: %s', app.name, exc)++ # Only ServerKit-managed uploads. A `manual` app points at a directory the+ # operator already had, and removing that would destroy data ServerKit never+ # created — the same guard delete_app has always carried.+ try:+ if app.source == 'upload' and app.root_path and app.root_path.startswith(paths.APPS_DIR):+ storage = get_app_storage_dir(app.name)+ if os.path.exists(storage):+ shutil.rmtree(storage)+ except Exception as exc: # noqa: BLE001+ logger.warning('Purge %s: storage removal failed: %s', app.name, exc)++ # Now that the app is going for good, its cron jobs fall back to the System+ # bucket rather than pointing at an id that no longer resolves.+ try:+ CronService.clear_application(app.id)+ except Exception as exc: # noqa: BLE001+ logger.warning('Purge %s: cron detach failed: %s', app.name, exc)+++def suspend_application(app, user_id=None):+ """Tombstone an app and stop it serving. The reversible half of a delete.++ Returns a dict of what happened, in the shape `delete_app` already reports.+ """+ from app.services.docker_service import DockerService+ from app.services.nginx_service import NginxService++ results = {'docker': None, 'nginx': None, 'cron': None, 'firewall': None}++ try:+ from app.services.app_port_service import AppPortService+ declared = AppPortService.get_ports(app)+ if declared:+ results['firewall'] = AppPortService.close_firewall(declared)+ except Exception as exc: # noqa: BLE001+ results['firewall'] = {'error': str(exc)}++ if app.app_type == 'docker' and app.root_path:+ try:+ # volumes=False, ALWAYS. The volumes are what makes this undoable;+ # they go at purge. This is the single most important line here.+ results['docker'] = DockerService.compose_down(+ app.root_path, volumes=False, remove_orphans=True)+ except Exception as exc: # noqa: BLE001+ results['docker'] = {'error': str(exc)}++ try:+ NginxService.disable_site(app.name)+ NginxService.delete_site(app.name)+ results['nginx'] = {'success': True}+ except Exception as exc: # noqa: BLE001+ results['nginx'] = {'error': str(exc)}++ try:+ results['cron'] = {'suspended': CronService.suspend_for_application(app.id)}+ except Exception as exc: # noqa: BLE001+ results['cron'] = {'error': str(exc)}++ app.soft_delete(user_id)+ app.status = 'stopped'+ db.session.commit()+ return resultsdiff --git a/backend/app/services/backup_policy_service.py b/backend/app/services/backup_policy_service.pyindex 7a7d8d20..474dbbaa 100644--- a/backend/app/services/backup_policy_service.py+++ b/backend/app/services/backup_policy_service.py@@ -266,7 +266,7 @@ class BackupPolicyService:try:from app.models.application import Applicationfrom app.services.volume_service import VolumeService- app = Application.query.get(meta['app_id'])+ app = Application.query_active().filter_by(id=meta['app_id']).first()host_path = VolumeService.host_path_for_mount(app, vol_mount)if host_path:file_paths = [host_path]@@ -304,8 +304,11 @@ class BackupPolicyService:)# application+ # A BackupPolicy outlives the app it points at, and its ScheduledJob keeps+ # firing, so a deleted app must fail here rather than have tar/restic run+ # against it and eat remote storage quota.from app.models.application import Application- app = Application.query.get(policy.target_id)+ app = Application.query_active().filter_by(id=policy.target_id).first()if not app:raise BackupPolicyError('Application not found')if not app.root_path:diff --git a/backend/app/services/backup_service.py b/backend/app/services/backup_service.pyindex 7092f962..603dbf64 100644--- a/backend/app/services/backup_service.py+++ b/backend/app/services/backup_service.py@@ -999,7 +999,9 @@ class BackupService:elif backup_type == 'application':from app.models import Application- app = Application.query.filter_by(name=target).first()+ # Name-keyed and fires every 30s: a tombstone sharing the name+ # would shadow the live app and the wrong one gets backed up.+ app = Application.query_active().filter_by(name=target).first()if app:result = cls.backup_application(app.name, app.root_path, correlation_id=correlation_id)else:diff --git a/backend/app/services/bandwidth_service.py b/backend/app/services/bandwidth_service.pyindex 84d531e6..571687fa 100644--- a/backend/app/services/bandwidth_service.py+++ b/backend/app/services/bandwidth_service.py@@ -181,16 +181,19 @@ class BandwidthService:return merged_hosts, merged_plain# Per-site logs: /var/log/nginx/{app.name}.access.log- for app_row in Application.query.all():+ # Live apps only: a deleted app's vhost is gone, and a new app reusing the+ # name would otherwise have the same log file counted twice.+ for app_row in Application.query_active().all():base = os.path.join(log_dir, f'{app_row.name}.access.log')per_host, plain = _parse_with_rotation(base)+ live_domains = app_row.live_domainsprimary = None- for d in (app_row.domains or []):+ for d in live_domains:if d.is_primary:primary = d.namebreak- if primary is None and app_row.domains:- primary = app_row.domains[0].name+ if primary is None and live_domains:+ primary = live_domains[0].namedefault_domain = (primary or app_row.name or '').lower()if default_domain:_add(default_domain, app_row.id, plain[0], plain[1])diff --git a/backend/app/services/compose_env_service.py b/backend/app/services/compose_env_service.pyindex 48e98486..80081585 100644--- a/backend/app/services/compose_env_service.py+++ b/backend/app/services/compose_env_service.py@@ -82,7 +82,9 @@ class ComposeEnvService:"""The managed Application whose root_path is this project dir, if any."""try:from app.models.application import Application- return Application.query.filter_by(root_path=project_path).first()+ # Path-keyed: a tombstone whose root_path a new app reused would+ # shadow the live app and the overlay would be written for the wrong one.+ return Application.query_active().filter_by(root_path=project_path).first()except Exception as e: # pragma: no cover - DB guardlogger.debug('compose overlay app lookup failed for %s: %s', project_path, e)return Nonediff --git a/backend/app/services/configuration_service.py b/backend/app/services/configuration_service.pyindex c2a5afd0..8bed0683 100644--- a/backend/app/services/configuration_service.py+++ b/backend/app/services/configuration_service.py@@ -254,7 +254,9 @@ class ConfigurationService:def _resolve_domains(application):"""Resolve domain names attached to the app."""try:- return [d.name for d in (application.domains or [])]+ # live_domains: the snapshot / serverkit.yaml records what the app+ # actually serves, and it is replayed on restore.+ return [d.name for d in (application.live_domains or [])]except Exception: # pragma: no cover - defensivereturn []@@ -393,7 +395,11 @@ class ConfigurationService:if not snapshot:return {'success': False, 'error': 'Snapshot not found'}- application = Application.query.get(snapshot.application_id)+ # query_active(): restoring a snapshot rewrites env and redeploys, so a+ # tombstoned app must 404 here rather than be brought back to life+ # outside the Recycle Bin.+ application = Application.query_active().filter_by(+ id=snapshot.application_id).first()if not application:return {'success': False, 'error': 'Application not found'}diff --git a/backend/app/services/container_scale_service.py b/backend/app/services/container_scale_service.pyindex 0e9a0113..61f41964 100644--- a/backend/app/services/container_scale_service.py+++ b/backend/app/services/container_scale_service.py@@ -86,7 +86,8 @@ class ContainerScaleService:@classmethoddef scale_to(cls, application_id, replicas):- app = Application.query.get(application_id)+ # query_active: this runs `docker compose up --scale` — never on a tombstone.+ app = Application.query_active().filter_by(id=application_id).first()if not app:return {'success': False, 'error': 'Application not found'}policy = cls.get_or_create_policy(application_id)@@ -101,7 +102,7 @@ class ContainerScaleService:@classmethoddef evaluate(cls, application_id):- app = Application.query.get(application_id)+ app = Application.query_active().filter_by(id=application_id).first()if not app:return {'success': False, 'error': 'Application not found'}policy = cls.get_or_create_policy(application_id)@@ -140,7 +141,12 @@ class ContainerScaleService:def sweep(cls):"""Evaluate every enabled policy. Meant to run periodically."""scaled = []+ # Scale policies outlive a soft-deleted app; skip them rather than+ # spawning docker/compose probes for an app that no longer exists.+ dead = Application.deleted_ids()for policy in ContainerScalePolicy.query.filter_by(enabled=True).all():+ if policy.application_id in dead:+ continueresult = cls.evaluate(policy.application_id)if result.get('action') in ('scaled_up', 'scaled_down'):scaled.append({'application_id': policy.application_id,diff --git a/backend/app/services/container_sleep_service.py b/backend/app/services/container_sleep_service.pyindex ce1acc4b..c427508e 100644--- a/backend/app/services/container_sleep_service.py+++ b/backend/app/services/container_sleep_service.py@@ -66,7 +66,8 @@ class ContainerSleepService:@classmethoddef sleep_app(cls, application_id):- app = Application.query.get(application_id)+ # query_active: this stops containers — never touch a tombstoned app.+ app = Application.query_active().filter_by(id=application_id).first()if not app:return {'success': False, 'error': 'Application not found'}result = cls._stop(app)@@ -81,7 +82,9 @@ class ContainerSleepService:@classmethoddef wake_app(cls, application_id):- app = Application.query.get(application_id)+ # query_active: waking a deleted app would restart the very containers+ # the delete tore down.+ app = Application.query_active().filter_by(id=application_id).first()if not app:return {'success': False, 'error': 'Application not found'}result = cls._start(app)@@ -102,7 +105,12 @@ class ContainerSleepService:now = datetime.utcnow()slept = []policies = ContainerSleepPolicy.query.filter_by(enabled=True, asleep=False).all()+ # Policies outlive a soft-deleted app; without this the scheduler keeps+ # running compose_down against a deleted app forever.+ dead = Application.deleted_ids()for policy in policies:+ if policy.application_id in dead:+ continueif not policy.last_activity_at:continue # no activity baseline yet — never sleep blindif now - policy.last_activity_at < timedelta(minutes=policy.idle_timeout_minutes):diff --git a/backend/app/services/container_status_service.py b/backend/app/services/container_status_service.pyindex fd7eda77..eb89ce29 100644--- a/backend/app/services/container_status_service.py+++ b/backend/app/services/container_status_service.py@@ -593,7 +593,7 @@ def get_app_status(application_id, use_cache=True, index: Optional[_ContainerIndtry:from app.models import Application- app = Application.query.get(application_id)+ app = Application.query_active().filter_by(id=application_id).first()except Exception as e:logger.warning('Failed to load application %s: %s', application_id, e)app = None@@ -686,7 +686,9 @@ def list_app_statuses():summaries = []try:from app.models import Application- apps = Application.query.all()+ # query_active: a tombstone has no containers left, so it would emit a+ # permanently-'unknown' row the socket snapshot could never clear.+ apps = Application.query_active().all()except Exception as e:logger.warning('Failed to list applications for status: %s', e)return summariesdiff --git a/backend/app/services/cron_service.py b/backend/app/services/cron_service.pyindex b4a31c04..6363534a 100644--- a/backend/app/services/cron_service.py+++ b/backend/app/services/cron_service.py@@ -793,29 +793,94 @@ class CronService:# Application attribution (member-facing surface)# ------------------------------------------------------------------ #+ @classmethod+ @staticmethod+ def _same_application(candidate, application_id) -> bool:+ """Do these two ids name the same app? Ids arrive as int or str."""+ if candidate in (None, ''):+ return False+ try:+ return int(candidate) == int(application_id)+ except (TypeError, ValueError):+ return str(candidate) == str(application_id)+@classmethoddef clear_application(cls, application_id) -> int:"""Drop the association from every job attributed to `application_id`- (called when the app is deleted — jobs fall back to the System bucket- rather than being deleted). Returns the number of jobs changed."""+ (called when the app is PURGED — jobs fall back to the System bucket+ rather than being deleted). Returns the number of jobs changed.++ This is lossy on purpose and therefore purge-only: it nulls the link+ without recording what it was, so nothing could put it back. A soft+ delete uses `suspend_for_application` instead, which is reversible.+ """metadata = cls._load_jobs_metadata()changed = 0for job_data in metadata.get('jobs', {}).values():- aid = job_data.get('application_id')- if aid in (None, ''):- continue- try:- same = int(aid) == int(application_id)- except (TypeError, ValueError):- same = str(aid) == str(application_id)- if same:+ if cls._same_application(job_data.get('application_id'), application_id):job_data['application_id'] = None+ job_data['suspended_by_app'] = Falsejob_data['updated_at'] = datetime.now().isoformat()changed += 1if changed:cls._save_jobs_metadata(metadata)return changed+ @classmethod+ def suspend_for_application(cls, application_id) -> int:+ """Disable an app's cron jobs when the app is soft-deleted.++ This is the one piece of a soft delete that CANNOT be handled by making+ readers liveness-aware. Everything else that acts on an app is swept+ from a table we can join against; cron jobs are lines in the operating+ system's crontab, and the OS does not know the app is in the bin. Left+ alone they keep firing — running shell commands against a `root_path`+ the purge may later remove.++ Only jobs that are currently ENABLED are touched, and each one is+ stamped `suspended_by_app`. That flag is what makes this reversible:+ without it, restoring would re-enable jobs the user had deliberately+ turned off long before the app was deleted.+ """+ metadata = cls._load_jobs_metadata()+ targets = [+ job_id for job_id, job_data in metadata.get('jobs', {}).items()+ if cls._same_application(job_data.get('application_id'), application_id)+ and job_data.get('enabled')+ ]+ for job_id in targets:+ cls.toggle_job(job_id, False)++ if targets:+ # Re-read: toggle_job persists on each call, so the copy above is+ # stale by now and writing it back would undo those saves.+ metadata = cls._load_jobs_metadata()+ for job_id in targets:+ if job_id in metadata.get('jobs', {}):+ metadata['jobs'][job_id]['suspended_by_app'] = True+ cls._save_jobs_metadata(metadata)+ return len(targets)++ @classmethod+ def resume_for_application(cls, application_id) -> int:+ """Re-enable exactly the jobs `suspend_for_application` disabled."""+ metadata = cls._load_jobs_metadata()+ targets = [+ job_id for job_id, job_data in metadata.get('jobs', {}).items()+ if cls._same_application(job_data.get('application_id'), application_id)+ and job_data.get('suspended_by_app')+ ]+ for job_id in targets:+ cls.toggle_job(job_id, True)++ if targets:+ metadata = cls._load_jobs_metadata()+ for job_id in targets:+ if job_id in metadata.get('jobs', {}):+ metadata['jobs'][job_id]['suspended_by_app'] = False+ cls._save_jobs_metadata(metadata)+ return len(targets)+@classmethoddef jobs_for_application(cls, application_id) -> List[Dict]:"""All jobs attributed to `application_id`, enriched with a humandiff --git a/backend/app/services/database_engine_extension_service.py b/backend/app/services/database_engine_extension_service.pyindex f3df5180..cb4b4300 100644--- a/backend/app/services/database_engine_extension_service.py+++ b/backend/app/services/database_engine_extension_service.py@@ -448,7 +448,7 @@ def engine_instances() -> List[Dict]:from app.models import Applicationdescribed = []- for app in Application.query.order_by(Application.created_at.asc()).all():+ for app in Application.query_active().order_by(Application.created_at.asc()).all():record = _describe(app)if record:described.append(record)@@ -459,7 +459,7 @@ def _find_instance(app_id: int) -> Optional[Dict]:"""One installed engine by app id, or ``None`` when it is not an engine."""from app.models import Application- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()return _describe(app) if app is not None else Nonediff --git a/backend/app/services/database_engine_service.py b/backend/app/services/database_engine_service.pyindex a4e7983c..7a31f7fd 100644--- a/backend/app/services/database_engine_service.py+++ b/backend/app/services/database_engine_service.py@@ -98,7 +98,7 @@ def engine_catalog() -> List[Dict]:from app.models import Applicationcounts: Dict[str, List[int]] = {}- for app in Application.query.all():+ for app in Application.query_active().all():template_id = app_template_id(app)if template_id:counts.setdefault(template_id, []).append(app.id)@@ -129,7 +129,7 @@ def installed_engines(live_status: bool = True) -> List[Dict]:from app.models import Applicationresults = []- for app in Application.query.order_by(Application.created_at.asc()).all():+ for app in Application.query_active().order_by(Application.created_at.asc()).all():template_id = app_template_id(app)if not template_id:continue@@ -202,6 +202,8 @@ def default_instance_name(template_id: str) -> str:from app.models import Applicationbase = _slug(template_id) or 'engine'+ # Deliberately unfiltered: a soft-deleted app must KEEP reserving its name,+ # or a new instance takes it and restoring from the recycle bin collides.taken = {a.name for a in Application.query.all()}if base not in taken:return basediff --git a/backend/app/services/deployment_job_service.py b/backend/app/services/deployment_job_service.pyindex b9fe2d8b..038f19e5 100644--- a/backend/app/services/deployment_job_service.py+++ b/backend/app/services/deployment_job_service.py@@ -42,6 +42,8 @@ class DeploymentJobService:"""Create a template installation job and optionally run it synchronously."""normalized_server_id = cls._normalize_server_id(server_id)+ # Deliberately NOT query_active: a soft-deleted app keeps reserving its+ # name, or a new install takes it and the Recycle Bin restore collides.existing = Application.query.filter_by(name=app_name, server_id=normalized_server_id).first()if existing:return {@@ -309,7 +311,10 @@ class DeploymentJobService:the UI sees the same progress/log stream as a template install."""runner = DeploymentPlanRunner(job)try:- app = Application.query.get(job.app_id) if job.app_id else None+ # Jobs outlive the app: a queued/retried deploy must not build and+ # start containers for one that has been deleted.+ app = (Application.query_active().filter_by(id=job.app_id).first()+ if job.app_id else None)if not app:raise RuntimeError(f'Application not found for deployment job {job.id}')@@ -712,6 +717,8 @@ class DeploymentJobService:writer drops in) before it can be reused."""try:+ # Deliberately NOT query_active: a soft-deleted app still owns its+ # directory until purge, so reusing it would break the restore.if Application.query.filter_by(root_path=app_path).first():return Falseentries = os.listdir(app_path)diff --git a/backend/app/services/deployment_service.py b/backend/app/services/deployment_service.pyindex ae89e765..03453fd6 100644--- a/backend/app/services/deployment_service.py+++ b/backend/app/services/deployment_service.py@@ -39,7 +39,9 @@ class DeploymentService:def create_deployment(cls, app_id: int, user_id: int = None,trigger: str = 'manual', version_tag: str = None) -> Dict:"""Create a new deployment record."""- app = Application.query.get(app_id)+ # query_active: a deploy builds, writes files and restarts containers —+ # a tombstoned app must fail here rather than be redeployed.+ app = Application.query_active().filter_by(id=app_id).first()if not app:return {'success': False, 'error': 'Application not found'}@@ -100,7 +102,7 @@ class DeploymentService:deployment_id = result['deployment']['id']deployment = Deployment.query.get(deployment_id)- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()build_config = BuildService.get_app_build_config(app_id)try:@@ -364,7 +366,8 @@ class DeploymentService:If target_version is not specified, rolls back to the previous successful deployment."""- app = Application.query.get(app_id)+ # query_active: a rollback re-deploys code and restarts the app.+ app = Application.query_active().filter_by(id=app_id).first()if not app:return {'success': False, 'error': 'Application not found'}@@ -526,7 +529,11 @@ class DeploymentService:if not previous or not deployment.commit_hash or not previous.commit_hash:return- app = Application.query.get(deployment.app_id)+ # Deployment rows outlive the app; a tombstone's root_path may be+ # gone (purge removes it), so don't shell out to git for one.+ app = Application.query_active().filter_by(id=deployment.app_id).first()+ if not app:+ returnapp_path = app.root_path# Get git diffdiff --git a/backend/app/services/drift_service.py b/backend/app/services/drift_service.pyindex 51aef318..09fb68ef 100644--- a/backend/app/services/drift_service.py+++ b/backend/app/services/drift_service.py@@ -323,8 +323,12 @@ def _nginx_list_resources():"""Apps published via host nginx = apps that have Domain rows."""from app.models.application import Applicationfrom app.models.domain import Domain- rows = (Application.query+ # Both sides must be live: drift REPAIR rewrites the vhost, so a tombstoned+ # app (or an app whose only remaining domains are tombstoned) would have the+ # config the delete removed written back.+ rows = (Application.query_active().join(Domain, Domain.application_id == Application.id)+ .filter(Domain.deleted_at.is_(None)).distinct().all())return [(app.id, app.name) for app in rows]@@ -335,7 +339,7 @@ def _nginx_render_expected(app_id):from app.services.nginx_service import NginxServicefrom app.services.site_domain_service import SiteDomainService- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if app is None:return {}kwargs, warning = SiteDomainService.app_vhost_kwargs(app)@@ -357,7 +361,7 @@ def _nginx_repair(app_id):from app.services.nginx_service import NginxServicefrom app.services.site_domain_service import SiteDomainService- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if app is None:return {'success': False, 'error': f'Application {app_id} not found'}res = SiteDomainService.write_app_vhost(app)@@ -386,7 +390,7 @@ register_check({def _compose_list_resources():"""Managed apps that live in a project dir (candidate compose apps)."""from app.models.application import Application- rows = Application.query.filter(Application.root_path.isnot(None)).all()+ rows = Application.query_active().filter(Application.root_path.isnot(None)).all()out = []for app in rows:try:@@ -403,7 +407,7 @@ def _compose_render_expected(app_id):from app.models.application import Applicationfrom app.services.compose_env_service import ComposeEnvService- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if app is None or not app.root_path:return {}spec = ComposeEnvService.render_override(app.root_path, app.compose_file)@@ -418,7 +422,7 @@ def _compose_repair(app_id):from app.services.compose_env_service import ComposeEnvServicefrom app.services.docker_service import DockerService- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if app is None:return {'success': False, 'error': f'Application {app_id} not found'}written = ComposeEnvService.refresh_for_project(app.root_path, app.compose_file)@@ -461,7 +465,7 @@ def _manifest_list_resources():from app.services.manifest_apply_service import ManifestApplyServiceout = []- rows = Application.query.filter(Application.project_id.isnot(None)).all()+ rows = Application.query_active().filter(Application.project_id.isnot(None)).all()for app in rows:try:if ManifestApplyService.resolved_for_app(app) is not None:@@ -475,7 +479,7 @@ def _manifest_render_expected(app_id):from app.models.application import Applicationfrom app.services.manifest_apply_service import ManifestApplyService- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if app is None:return {}resolved = ManifestApplyService.resolved_for_app(app)@@ -496,7 +500,7 @@ def _manifest_read_actual(paths):except (ValueError, IndexError):actual[path] = Nonecontinue- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()resolved = ManifestApplyService.resolved_for_app(app) if app else Noneif app is None or resolved is None:actual[path] = None@@ -510,7 +514,7 @@ def _manifest_repair(app_id):from app.models.application import Applicationfrom app.services.manifest_apply_service import ManifestApplyService- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if app is None:return {'success': False, 'error': f'Application {app_id} not found'}if not app.project_id:diff --git a/backend/app/services/env_reference_service.py b/backend/app/services/env_reference_service.pyindex 41f2781b..a9d3e8c4 100644--- a/backend/app/services/env_reference_service.py+++ b/backend/app/services/env_reference_service.py@@ -108,13 +108,15 @@ class EnvReferenceResolver:if managed is not None:return cls._db_property(managed, prop)- # app sibling (Application by name within the project)+ # app sibling (Application by name within the project). Name-keyed, so a+ # tombstone sharing the name would shadow the live app and the wrong+ # app's host/port/secrets would get baked into a live container's env.from app.models.application import Applicationsibling = Noneif project_id is not None:- sibling = Application.query.filter_by(project_id=project_id, name=service_name).first()+ sibling = Application.query_active().filter_by(project_id=project_id, name=service_name).first()if sibling is None:- sibling = Application.query.filter_by(name=service_name).first()+ sibling = Application.query_active().filter_by(name=service_name).first()if sibling is not None:return cls._app_property(sibling, service_name, prop)diff --git a/backend/app/services/env_service.py b/backend/app/services/env_service.pyindex cd06f8d5..b7bdfebe 100644--- a/backend/app/services/env_service.py+++ b/backend/app/services/env_service.py@@ -61,7 +61,7 @@ class EnvService:as sensitive. Shared resolution is best-effort: if it fails, the app'slocal env vars are still returned so a deploy is never blocked."""- app = Application.query.get(application_id)+ app = Application.query_active().filter_by(id=application_id).first()if not app:return {}@@ -122,7 +122,7 @@ class EnvService:valid, error = EnvService.validate_key(key)if not valid:return None, False, error- app = Application.query.get(application_id)+ app = Application.query_active().filter_by(id=application_id).first()if not app:return None, False, 'Application not found'@@ -163,7 +163,7 @@ class EnvService:Returns ``{service_name: {key: value}}`` (decrypted). Best-effort — sharedresolution failures fall back to local vars and never block a deploy."""- app = Application.query.get(application_id)+ app = Application.query_active().filter_by(id=application_id).first()if not app or not service_names:return {}@@ -231,7 +231,7 @@ class EnvService:norm_target = None if target_service in ('', _UNSET) else target_service# Check if application exists- app = Application.query.get(application_id)+ app = Application.query_active().filter_by(id=application_id).first()if not app:return None, False, "Application not found"diff --git a/backend/app/services/file_integrity_service.py b/backend/app/services/file_integrity_service.pyindex 4a613507..e0e43a05 100644--- a/backend/app/services/file_integrity_service.py+++ b/backend/app/services/file_integrity_service.py@@ -108,7 +108,10 @@ class FileIntegrityService:else:app_id = int(_APP_SCOPE_RE.match(scope).group(1))from app.models.application import Application- application = Application.query.get(app_id)+ # query_active: this root is what the sweep walks, hashes and+ # notifies on. A baseline outlives the app, so a deleted one must+ # fail to resolve rather than hand back a docroot purge removed.+ application = Application.query_active().filter_by(id=app_id).first()if not application:raise FileIntegrityScopeError(f'Application {app_id} not found')roots = [application.root_path] if application.root_path else []@@ -394,6 +397,9 @@ class FileIntegrityService:if optins:try:from app.models.application import Application+ # Deliberately NOT query_active: this is only a label map, so a+ # stale opt-in still renders its name. Liveness is enforced in+ # _scope_roots, which leaves the scope unavailable.for application in Application.query.filter(Application.id.in_(optins)).all():app_names[application.id] = application.nameexcept Exception:diff --git a/backend/app/services/git_deploy_service.py b/backend/app/services/git_deploy_service.pyindex e2fdeb66..087e8279 100644--- a/backend/app/services/git_deploy_service.py+++ b/backend/app/services/git_deploy_service.py@@ -38,7 +38,9 @@ class GitDeployService:from app.models import Application, GitWebhook, GitDeploymentfrom app.services.docker_service import DockerService- app = Application.query.get(app_id)+ # query_active: a webhook can still fire for a deleted app — this pulls+ # code and rebuilds/restarts containers, so a tombstone must not deploy.+ app = Application.query_active().filter_by(id=app_id).first()if not app:return {'success': False, 'error': 'Application not found'}@@ -176,7 +178,7 @@ class GitDeployService:from app.models import Application, GitDeploymentfrom app.services.docker_service import DockerService- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return {'success': False, 'error': 'Application not found'}@@ -313,7 +315,7 @@ class GitDeployService:"""Trigger a manual deployment."""from app.models import Application, GitWebhook- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return {'success': False, 'error': 'Application not found'}diff --git a/backend/app/services/image_scanner_service.py b/backend/app/services/image_scanner_service.pyindex 7a15dfa5..497e94cb 100644--- a/backend/app/services/image_scanner_service.py+++ b/backend/app/services/image_scanner_service.py@@ -181,7 +181,8 @@ class ImageScannerService:@classmethoddef scan_application(cls, application_id: int) -> Dict:"""Run a CVE scan for the Docker image of an application."""- app = Application.query.get(application_id)+ # query_active: a scan spawns Grype and pulls from the registry.+ app = Application.query_active().filter_by(id=application_id).first()if not app:return {'success': False, 'error': 'Application not found'}image_ref = app.docker_image or app.container_id@@ -224,7 +225,8 @@ class ImageScannerService:@classmethoddef generate_sbom(cls, application_id: int) -> Dict:"""Generate and persist an SPDX SBOM for an application image."""- app = Application.query.get(application_id)+ # query_active: Syft pulls/inspects the image out of process.+ app = Application.query_active().filter_by(id=application_id).first()if not app:return {'success': False, 'error': 'Application not found'}image_ref = app.docker_image or app.container_iddiff --git a/backend/app/services/image_update_service.py b/backend/app/services/image_update_service.pyindex a5cd0ec6..886d4f48 100644--- a/backend/app/services/image_update_service.py+++ b/backend/app/services/image_update_service.py@@ -49,7 +49,9 @@ class ImageUpdateService:@classmethoddef check_application(cls, application_id):- app = Application.query.get(application_id)+ # query_active: this runs `docker manifest inspect` against the registry+ # (and a `docker login` when a private registry is bound).+ app = Application.query_active().filter_by(id=application_id).first()if not app:return {'success': False, 'error': 'Application not found'}image_ref = app.docker_imagediff --git a/backend/app/services/malware_scan_service.py b/backend/app/services/malware_scan_service.pyindex d6df8ceb..f9a0d3e4 100644--- a/backend/app/services/malware_scan_service.py+++ b/backend/app/services/malware_scan_service.py@@ -68,7 +68,10 @@ class MalwareScanService:"""Resolve an application's docroot on disk from its DB row."""from app.models.application import Application- app_row = Application.query.get(app_id)+ # query_active: the scan reads — and quarantines files in — this+ # docroot, which purge may already have removed. A queued job for a+ # deleted app must fail to resolve rather than scan somebody's path.+ app_row = Application.query_active().filter_by(id=app_id).first()if not app_row:raise ValueError(f'Application {app_id} not found')diff --git a/backend/app/services/manifest_apply_service.py b/backend/app/services/manifest_apply_service.pyindex abae72f4..c964c923 100644--- a/backend/app/services/manifest_apply_service.py+++ b/backend/app/services/manifest_apply_service.py@@ -229,7 +229,7 @@ class ManifestApplyService:declared_domains = resolved.get('_domains', [])if declared_domains:- live_hosts = {d.name for d in (app.domains or [])}+ live_hosts = {d.name for d in app.live_domains}expected['domains'] = declared_domainsobserved['domains'] = sorted(h for h in declared_domains if h in live_hosts)@@ -455,7 +455,9 @@ class ManifestApplyService:host = dom.get('host')svc_name = dom.get('service')app = cls._find_app(project, svc_name) if svc_name else None- already = bool(app) and any(d.name == host for d in (app.domains or []))+ # live_domains, not domains: a tombstoned Domain would make this look+ # attached and the apply would skip the vhost/DNS/cert work entirely.+ already = bool(app) and any(d.name == host for d in app.live_domains)if already:continuesteps.append({@@ -727,7 +729,7 @@ class ManifestApplyService:deploy_configs = GitService.get_config().get('apps', {})except Exception:return None- for sibling in Application.query.filter_by(project_id=project.id).all():+ for sibling in Application.query_active().filter_by(project_id=project.id).all():cfg = deploy_configs.get(str(sibling.id))if cfg and cfg.get('repo_url'):return {'repo_url': cfg['repo_url'], 'branch': cfg.get('branch') or 'main'}@@ -966,7 +968,7 @@ class ManifestApplyService:@classmethoddef _do_update_app(cls, project, env, payload, user_id):import json- app = Application.query.get(payload['app_id'])+ app = Application.query_active().filter_by(id=payload['app_id']).first()if not app:raise RuntimeError('app not found')changes = payload['changes']@@ -1035,7 +1037,8 @@ class ManifestApplyService:@classmethoddef _do_ensure_volume(cls, project, env, payload, user_id):from app.services.volume_service import VolumeService- app = Application.query.get(payload.get('app_id') or cls._resolve_app_id(project, payload))+ app = Application.query_active().filter_by(+ id=payload.get('app_id') or cls._resolve_app_id(project, payload)).first()if not app:raise RuntimeError('app not found')if any(v.mount_path == payload['mount_path'] for v in (app.volumes or [])):@@ -1052,7 +1055,8 @@ class ManifestApplyService:@classmethoddef _do_bootstrap(cls, project, env, payload, user_id):from app.services.bootstrap_service import BootstrapService- app = Application.query.get(payload.get('app_id') or cls._resolve_app_id(project, payload))+ app = Application.query_active().filter_by(+ id=payload.get('app_id') or cls._resolve_app_id(project, payload)).first()if not app:raise RuntimeError('app not found')if getattr(app, 'bootstrap_done', False):@@ -1077,7 +1081,8 @@ class ManifestApplyService:@classmethoddef _do_open_port(cls, project, env, payload, user_id):from app.services.app_port_service import AppPortService- app = Application.query.get(payload.get('app_id') or cls._resolve_app_id(project, payload))+ app = Application.query_active().filter_by(+ id=payload.get('app_id') or cls._resolve_app_id(project, payload)).first()if not app:raise RuntimeError('app not found')ports = payload['ports']@@ -1123,7 +1128,7 @@ class ManifestApplyService:cls._resolve_app_id(project, payload) if payload.get('service') else None)if not app_id:return {'skipped': 'no target service'}- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:raise RuntimeError('app not found for domain')result = DomainAttachService.attach(app, payload['host'], ssl=payload.get('ssl', 'auto'))@@ -1300,7 +1305,10 @@ class ManifestApplyService:def _find_app(project: Project, name: Optional[str]) -> Optional[Application]:if not name:return None- return Application.query.filter_by(project_id=project.id, name=name).first()+ # Name-keyed, and every apply step routes through here: a tombstone+ # sharing the name would shadow the live app and the apply would attach+ # domains / create DNS / start containers against the deleted one.+ return Application.query_active().filter_by(project_id=project.id, name=name).first()@classmethoddef _resolve_app_id(cls, project, payload):diff --git a/backend/app/services/manifest_sync_service.py b/backend/app/services/manifest_sync_service.pyindex be2fe3bc..3293a58b 100644--- a/backend/app/services/manifest_sync_service.py+++ b/backend/app/services/manifest_sync_service.py@@ -43,7 +43,7 @@ class ManifestSyncService:def _resync(cls, app_id: int, commit: Optional[str], trigger: str) -> Dict[str, Any]:from app.services.repository_manifest_service import RepositoryManifestService- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app or not app.project_id or not app.root_path:return {'synced': False, 'reason': 'no project/root'}diff --git a/backend/app/services/nginx_service.py b/backend/app/services/nginx_service.pyindex f8fb82f6..22d24d13 100644--- a/backend/app/services/nginx_service.py+++ b/backend/app/services/nginx_service.py@@ -1027,8 +1027,10 @@ location /p/ {{from app.models import Applicationtry:- # Query all apps with private URLs enabled- apps = Application.query.filter(+ # Query all apps with private URLs enabled. query_active(): a+ # tombstoned app's container is gone, so re-publishing its /p/<slug>+ # would proxy to a dead port.+ apps = Application.query_active().filter(Application.private_url_enabled == True,Application.private_slug.isnot(None),Application.port.isnot(None)diff --git a/backend/app/services/preview_service.py b/backend/app/services/preview_service.pyindex 6a4cb57a..06302a85 100644--- a/backend/app/services/preview_service.py+++ b/backend/app/services/preview_service.py@@ -361,6 +361,9 @@ class PreviewService:app = Nonetry:from app.models import Application+ # Deliberately NOT query_active: this is the teardown path, and+ # a deleted app's previews still have to be torn down. Scoping+ # it here would leak the WordPress preview instance.app = Application.query.get(preview.application_id)except Exception:pass@@ -402,7 +405,9 @@ class PreviewService:try:from app.models import Application- app = Application.query.get(application_id)+ # query_active: syncing provisions preview infra (domains,+ # containers) — never for a deleted app.+ app = Application.query_active().filter_by(id=application_id).first()if not app:return {'error': 'application not found'}@@ -474,7 +479,9 @@ class PreviewService:def _job_create(cls, job):from app.models import Applicationpayload = job.get_payload() or {}- app = Application.query.get(payload.get('application_id'))+ # query_active: a queued preview job can outlive its app.+ app = Application.query_active().filter_by(+ id=payload.get('application_id')).first()if not app:return {'error': 'application not found'}return cls.create_preview(app, payload.get('pr') or payload)diff --git a/backend/app/services/private_url_service.py b/backend/app/services/private_url_service.pyindex d5c5ce3b..c531dd3c 100644--- a/backend/app/services/private_url_service.py+++ b/backend/app/services/private_url_service.py@@ -78,7 +78,13 @@ class PrivateURLService:"""from app.models import Application- query = Application.query.filter_by(private_slug=slug)+ # query_active, and this is the Class-B trap from the Domain round:+ # migration 084 made the slug unique only among LIVE rows precisely so+ # a delete stops burning `/p/<slug>`. Checking every row here would+ # re-impose at the application level the reservation the schema just+ # released. A restore whose slug was taken meanwhile is refused by+ # pre_restore_application, which is where that conflict belongs.+ query = Application.query_active().filter_by(private_slug=slug)if exclude_app_id:query = query.filter(Application.id != exclude_app_id)diff --git a/backend/app/services/project_service.py b/backend/app/services/project_service.pyindex c18b9cc2..bcf99b18 100644--- a/backend/app/services/project_service.py+++ b/backend/app/services/project_service.py@@ -102,6 +102,8 @@ class ProjectService:project = Project.query.get(project_id)if not project:return None+ # Deliberately counts tombstones too: a soft-deleted app still points at+ # this project, and hard-deleting the project would leave it unrestorable.if Application.query.filter_by(project_id=project_id).count() > 0:return 'has_apps'db.session.delete(project) # cascades to environments@@ -204,6 +206,8 @@ class ProjectService:return 'last'# Detach apps from the deleted environment (keep them in the project).+ # Tombstones included on purpose — the Environment row is going away, so+ # leaving a soft-deleted app pointing at it would dangle on restore.Application.query.filter_by(environment_id=environment_id).update({'environment_id': None}, synchronize_session=False)was_default = env.is_default@@ -247,12 +251,12 @@ class ProjectService:@staticmethoddef list_project_apps(project_id):- return Application.query.filter_by(project_id=project_id).all()+ return Application.query_active().filter_by(project_id=project_id).all()@staticmethoddef list_environment_apps(environment_id):- return Application.query.filter_by(environment_id=environment_id).all()+ return Application.query_active().filter_by(environment_id=environment_id).all()@staticmethoddef count_project_apps(project_id):- return Application.query.filter_by(project_id=project_id).count()+ return Application.query_active().filter_by(project_id=project_id).count()diff --git a/backend/app/services/proxy_stack_service.py b/backend/app/services/proxy_stack_service.pyindex 2b4b8b80..7056ae29 100644--- a/backend/app/services/proxy_stack_service.py+++ b/backend/app/services/proxy_stack_service.py@@ -569,7 +569,9 @@ class ProxyStackService:grouped = {}try:from app.models.application import Application- apps = Application.query.filter(Application.server_id.isnot(None)).all()+ # query_active(): a tombstoned app is not served by any proxy, so+ # counting it here would report a mismatch nothing can resolve.+ apps = Application.query_active().filter(Application.server_id.isnot(None)).all()except Exception as e: # pragma: no cover - DB guardlogger.warning(f"_apps_by_server query failed: {e}")return grouped@@ -641,7 +643,9 @@ class ProxyStackService:server = Server.query.get(server_id)stack = ProxyStack.query.filter_by(server_id=server_id).first()proxy_type = (stack.proxy_type if stack else 'nginx') or 'nginx'- apps = Application.query.filter_by(server_id=server_id).all()+ # query_active(): these rows are the repair allowlist — a tombstone+ # would become a phantom mismatch no action can clear.+ apps = Application.query_active().filter_by(server_id=server_id).all()except Exception as e: # pragma: no cover - DB guardlogger.warning(f"ingress_audit query failed: {e}")diff --git a/backend/app/services/recycle_bin_service.py b/backend/app/services/recycle_bin_service.pyindex f23811f0..ddc9a847 100644--- a/backend/app/services/recycle_bin_service.py+++ b/backend/app/services/recycle_bin_service.py@@ -28,7 +28,7 @@ DEFAULT_RETENTION_DAYS = 30def register(kind, model, *, label, description=None, on_restore=None,- pre_restore=None, noun=None):+ pre_restore=None, on_purge=None, noun=None):"""Make a soft-deletable model visible to the Recycle Bin.`pre_restore(row)` runs BEFORE the tombstone is cleared and returns an error@@ -37,6 +37,17 @@ def register(kind, model, *, label, description=None, on_restore=None,live may hold it by the time you press Restore. Clearing the tombstone thenviolates the index and raises IntegrityError at commit — a 500 for what isreally a normal, explainable conflict.++ `on_purge(row)` runs just BEFORE the row is destroyed for good, and is where+ a type puts the work that cannot be undone. Deleting an application stops+ its containers and unpublishes it — reversible — but removing its data+ volumes and its uploaded source is not, so that half waits here. Without+ this hook the bin would be offering to restore a row whose files the delete+ had already destroyed, which is a promise it cannot keep.++ An exception from `on_purge` must NOT block the purge: the caller asked for+ the row to go, and a failure to reclaim a directory is not a reason to keep+ a record they have said twice they do not want."""if not hasattr(model, 'deleted_at'):raise TypeError(f'{model.__name__} does not use SoftDeleteMixin')@@ -46,6 +57,7 @@ def register(kind, model, *, label, description=None, on_restore=None,'description': description,'on_restore': on_restore,'pre_restore': pre_restore,+ 'on_purge': on_purge,'noun': noun or kind.replace('_', ' '),}@@ -120,6 +132,22 @@ def restore(kind, record_id):return item, None+def _run_purge_hook(entry, row):+ """The type's irreversible cleanup, best-effort.++ Never allowed to block the purge: the caller has now said twice that they+ want the row gone, and failing to reclaim a directory is not a reason to+ keep a record against their wishes. Returns a warning string, or None.+ """+ if not entry.get('on_purge'):+ return None+ try:+ entry['on_purge'](row)+ return None+ except Exception as exc: # noqa: BLE001+ return f'purged, but cleanup failed: {exc}'++def purge(kind, record_id):"""Delete for real. The only irreversible action in this module."""entry = _entry(kind)@@ -128,9 +156,10 @@ def purge(kind, record_id):return False, 'not found'if row.deleted_at is None:return False, 'record is not in the recycle bin'+ warning = _run_purge_hook(entry, row)db.session.delete(row)db.session.commit()- return True, None+ return True, warningdef purge_expired(retention_days=DEFAULT_RETENTION_DAYS):@@ -143,6 +172,11 @@ def purge_expired(retention_days=DEFAULT_RETENTION_DAYS):entry['model'].deleted_at < cutoff,).all()for row in rows:+ # The retention sweep is the OTHER way a row reaches the end of its+ # life, so it owes the same cleanup an explicit purge does — without+ # it, a directory is reclaimed only when someone happens to click+ # Purge, and never for the 30-day expiry path.+ _run_purge_hook(entry, row)db.session.delete(row)if rows:counts[kind] = len(rows)@@ -153,10 +187,26 @@ def purge_expired(retention_days=DEFAULT_RETENTION_DAYS):def register_builtin_types():"""Wire the models that ship with the panel. Called from create_app."""+ from app.models.application import Applicationfrom app.models.domain import Domainfrom app.models.saved_view import SavedView+ from app.services.application_restore import (+ on_purge_application, on_restore_application, pre_restore_application,+ )from app.services.domain_restore import on_restore_domain, pre_restore_domain+ # Applications carry the only on_purge in the registry: a delete stops the+ # app, a PURGE destroys its volumes and uploaded source. See+ # application_restore for why that split is what makes the tombstone honest.+ register(+ 'application', Application, noun='application',+ label=lambda a: a.name,+ description=lambda a: (f'{a.app_type} · {a.root_path}' if a.root_path else a.app_type),+ pre_restore=pre_restore_application,+ on_restore=on_restore_application,+ on_purge=on_purge_application,+ )+register('domain', Domain, noun='domain',label=lambda d: d.name,diff --git a/backend/app/services/search_service.py b/backend/app/services/search_service.pyindex 02f2e693..d6278e6f 100644--- a/backend/app/services/search_service.py+++ b/backend/app/services/search_service.py@@ -51,8 +51,11 @@ class SearchService:# --- service / app ---try:from app.models.application import Application+ # Deleted apps are not findable: the recycle bin is where they+ # live now, and this id list also scopes the domain/backup+ # searches below.q = WorkspaceService.scope_query(- Application.query, Application, user,+ Application.query_active(), Application, user,workspace_id=ws_id, owner_attr='user_id',grant_resource_type='application',)diff --git a/backend/app/services/site_import_service.py b/backend/app/services/site_import_service.pyindex bd6990c1..d46af88f 100644--- a/backend/app/services/site_import_service.py+++ b/backend/app/services/site_import_service.py@@ -463,6 +463,9 @@ class SiteImportService:raw_name = (options.get('app_name') or primary.get('domain')or analysis.get('account_user') or f'imported-{imp.id}')name = slugify(raw_name)[:100] or f'imported-{imp.id}'+ # Unfiltered on purpose: a tombstoned app keeps reserving its name and+ # its APPS_DIR/<name> directory until purge, so reusing the name here+ # would collide with the files a restore expects to find.if Application.query.filter_by(name=name).first():name = f'{name}-{imp.id}'@@ -507,7 +510,8 @@ class SiteImportService:return ctx['app']from app.models import Applicationapp_id = ctx['result'].get('app_id') or imp.get_result().get('app_id')- application = Application.query.get(app_id) if app_id else None+ application = (Application.query_active().filter_by(id=app_id).first()+ if app_id else None)if not application:raise SiteImportError('Imported application row not found — '"retry from step 'create_app'")diff --git a/backend/app/services/support_bundle_service.py b/backend/app/services/support_bundle_service.pyindex 12cb7b4b..fd7037a5 100644--- a/backend/app/services/support_bundle_service.py+++ b/backend/app/services/support_bundle_service.py@@ -100,7 +100,9 @@ def _collect_counts():from app.models import Application, Domain, Server, Userfrom app.jobs.models import Jobreturn {- 'applications': Application.query.count(),+ # Live rows only, matching `domains` below — the bundle reports what the+ # install currently runs, not how much is sitting in the recycle bin.+ 'applications': Application.query_active().count(),'domains': Domain.query_active().count(),'servers': Server.query.count(),'users': User.query.count(),diff --git a/backend/app/services/template_service.py b/backend/app/services/template_service.pyindex 9fd55a48..e2e64873 100644--- a/backend/app/services/template_service.py+++ b/backend/app/services/template_service.py@@ -1090,6 +1090,8 @@ class TemplateService:used_ports = set()try:from app.models import Application+ # Deliberately unfiltered: a soft-deleted app must KEEP reserving its+ # port, or a new app takes it and restoring from the recycle bin collides.apps = Application.query.filter(Application.port.isnot(None)).all()for app in apps:if app.port:@@ -2240,7 +2242,7 @@ class TemplateService:if not installed:return {'success': False, 'error': 'App not installed from template'}- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:return {'success': False, 'error': 'Application not found'}@@ -2381,8 +2383,8 @@ class TemplateService:"""from app.models import Application- source_app = Application.query.get(source_app_id)- target_app = Application.query.get(target_app_id)+ source_app = Application.query_active().filter_by(id=source_app_id).first()+ target_app = Application.query_active().filter_by(id=target_app_id).first()if not source_app or not target_app:return {'success': False, 'error': 'App not found'}diff --git a/backend/app/services/waf_service.py b/backend/app/services/waf_service.pyindex fac011b9..d24921c5 100644--- a/backend/app/services/waf_service.py+++ b/backend/app/services/waf_service.py@@ -304,14 +304,16 @@ class WafService:"""from app.models.application import Application- application = Application.query.get(application_id)+ application = Application.query_active().filter_by(id=application_id).first()if not application:return Nonecandidates = set()if application.name:candidates.add(application.name)- for domain in getattr(application, 'domains', []) or []:+ # live_domains, not domains: a tombstoned domain's server_name is no+ # longer in any vhost, and matching on it could land on another app's file.+ for domain in getattr(application, 'live_domains', []) or []:if getattr(domain, 'domain', None):candidates.add(domain.domain)@@ -385,7 +387,7 @@ class WafService:from app.models.application import Applicationfrom app.models.waf_policy import WafPolicy- application = Application.query.get(application_id)+ application = Application.query_active().filter_by(id=application_id).first()if not application:return {'success': False, 'error': 'Application not found'}diff --git a/backend/app/services/webhook_service.py b/backend/app/services/webhook_service.pyindex 46b4a6d4..a41d46b4 100644--- a/backend/app/services/webhook_service.py+++ b/backend/app/services/webhook_service.py@@ -60,7 +60,9 @@ class WebhookService:# Validate app_id if providedif app_id:- app = Application.query.get(app_id)+ # query_active(): binding a webhook to a tombstoned app would let a+ # push fire deploys and outbound callbacks for a deleted app.+ app = Application.query_active().filter_by(id=app_id).first()if not app:return {'success': False, 'error': 'Application not found'}@@ -474,8 +476,14 @@ class WebhookService:actions = ['synced']deployment_result = None- # Trigger deployment if configured- if webhook.deploy_on_push and webhook.app_id:+ # Trigger deployment if configured. The liveness check is here and+ # not only at bind time: a push must not rebuild and restart the+ # containers of an app that was deleted after the webhook was saved.+ from app.models import Application+ deploy_app = (Application.query_active()+ .filter_by(id=webhook.app_id).first()+ if webhook.app_id else None)+ if webhook.deploy_on_push and deploy_app:deployment_result = GitDeployService.deploy(app_id=webhook.app_id,webhook_id=webhook.id,diff --git a/backend/app/sockets.py b/backend/app/sockets.pyindex 721906a2..5e12763e 100644--- a/backend/app/sockets.py+++ b/backend/app/sockets.py@@ -466,7 +466,7 @@ def handle_subscribe_container_logs(data):# Get app and verify accesstry:- app = Application.query.get(app_id)+ app = Application.query_active().filter_by(id=app_id).first()if not app:emit('container_log_error', {'message': 'Application not found', 'app_id': app_id})returndiff --git a/backend/cli.py b/backend/cli.pyindex 47894bcf..e451362b 100644--- a/backend/cli.py+++ b/backend/cli.py@@ -367,7 +367,11 @@ def cleanup_apps(delete_volumes, keep_db):app = create_app()with app.app_context():- apps = Application.query.all()+ # Live apps only. `docker compose down -v` on a soft-deleted app would+ # destroy the data volumes the delete deliberately KEPT for restore,+ # leaving a restorable row with nothing behind it. Recycle-bin entries+ # are removed by purging them, not here.+ apps = Application.query_active().all()click.echo(f'Found {len(apps)} application(s) in database...\n')@@ -516,7 +520,10 @@ def factory_reset():click.echo('Starting factory reset...\n')# 1. Clean up all applications from database- apps = Application.query.all()+ # Only live apps have a stack to bring down; a soft-deleted app's+ # containers are already stopped, and steps 2-4 + drop_all() below sweep+ # up whatever it left behind anyway.+ apps = Application.query_active().all()click.echo(f'Stopping {len(apps)} tracked application(s)...')for application in apps:if application.root_path and os.path.exists(application.root_path):@@ -624,7 +631,7 @@ def list_apps(show_all, as_json):app = create_app()with app.app_context():- apps = Application.query.all()+ apps = Application.query_active().all()if as_json:_echo_json({'apps': [diff --git a/backend/migrations/versions/084_soft_delete_applications.py b/backend/migrations/versions/084_soft_delete_applications.pynew file mode 100644index 00000000..7d3adfbf--- /dev/null+++ b/backend/migrations/versions/084_soft_delete_applications.py@@ -0,0 +1,118 @@+"""Soft delete for applications: tombstone columns + a live-rows-only slug index.++Same shape as 083 (domains / saved_views), with one table-specific hazard:++`applications.private_slug` is UNIQUE and is what the `/p/<slug>` private-URL+route resolves against. Left as a plain UNIQUE, deleting an app would burn its+slug forever — the recycle bin's whole promise is that the delete is undoable,+and "you can have the app back but not its URL" is not that. It becomes a+unique INDEX predicated on `deleted_at IS NULL`, so a tombstone releases the+slug and a live row still cannot collide.++Deliberately NOT touched: `applications.name` has no unique constraint (two+apps may share a name today), so there is nothing to convert. Do not add one+here — that would be a behaviour change wearing a migration's clothes.++Revision ID: 084_soft_delete_applications+Revises: 083_soft_delete_recycle_bin+"""+import sqlalchemy as sa+from alembic import op++revision = '084_soft_delete_applications'+down_revision = '083_soft_delete_recycle_bin'+branch_labels = None+depends_on = None+++def _has_table(name):+ bind = op.get_bind()+ return name in sa.inspect(bind).get_table_names()+++def _columns(table):+ bind = op.get_bind()+ return {c['name'] for c in sa.inspect(bind).get_columns(table)}+++def _indexes(table):+ bind = op.get_bind()+ return {i['name'] for i in sa.inspect(bind).get_indexes(table)}+++def _unique_constraints(table):+ bind = op.get_bind()+ try:+ return {c['name'] for c in sa.inspect(bind).get_unique_constraints(table)}+ except NotImplementedError: # some dialects+ return set()+++def _mk_index(table, name, cols, unique=False, live_only=False):+ """create_index that tolerates the index already existing.++ `deleted_at` is declared index=True on the mixin, so a database built from+ the models rather than replayed through migrations already has it — and a+ bare create_index would abort the upgrade on exactly the installs we most+ want to keep working.+ """+ if name in _indexes(table):+ return+ kwargs = {}+ if live_only:+ kwargs = {+ 'sqlite_where': sa.text('deleted_at IS NULL'),+ 'postgresql_where': sa.text('deleted_at IS NULL'),+ }+ op.create_index(name, table, cols, unique=unique, **kwargs)+++def upgrade():+ if not _has_table('applications'):+ return++ existing = _columns('applications')+ # Batch mode validates the whole recipe when the block EXITS, so a missing+ # constraint raises there rather than at the drop call — check first instead+ # of wrapping it in try/except (the lesson from 083).+ drop_uq = 'uq_applications_private_slug' in _unique_constraints('applications')+ with op.batch_alter_table('applications') as batch:+ if 'deleted_at' not in existing:+ batch.add_column(sa.Column('deleted_at', sa.DateTime(), nullable=True))+ if 'deleted_by_id' not in existing:+ batch.add_column(sa.Column('deleted_by_id', sa.Integer(), nullable=True))+ if drop_uq:+ batch.drop_constraint('uq_applications_private_slug', type_='unique')++ _mk_index('applications', 'ix_applications_deleted_at', ['deleted_at'])++ # The unique may have been materialised as an index instead of a table+ # constraint depending on how old the install is; drop whichever exists.+ for drop in (+ lambda: op.drop_index('ix_applications_private_slug', table_name='applications'),+ ):+ try:+ drop()+ except Exception: # noqa: BLE001 - constraint shape varies by install age+ pass++ # Plain lookup index (the /p/<slug> route reads it) + the live-only unique.+ _mk_index('applications', 'ix_applications_private_slug', ['private_slug'])+ _mk_index('applications', 'uq_applications_private_slug_live',+ ['private_slug'], unique=True, live_only=True)+++def downgrade():+ if not _has_table('applications'):+ return+ for name in ('uq_applications_private_slug_live', 'ix_applications_deleted_at'):+ try:+ op.drop_index(name, table_name='applications')+ except Exception: # noqa: BLE001+ pass+ with op.batch_alter_table('applications') as batch:+ for col in ('deleted_by_id', 'deleted_at'):+ try:+ batch.drop_column(col)+ except Exception: # noqa: BLE001+ passdiff --git a/backend/tests/test_application_soft_delete.py b/backend/tests/test_application_soft_delete.pynew file mode 100644index 00000000..da735e24--- /dev/null+++ b/backend/tests/test_application_soft_delete.py@@ -0,0 +1,265 @@+"""A deleted application must stop being an application.++Making Application soft-deletable silently changed the meaning of every+existing `Application.query`: before, it could only return live rows. Domain+went through this and TEN read paths were wrong, four with effects outside the+panel. Application has 13x the call sites and drives more: container+lifecycles, nginx, backups, registry pulls, the OS crontab.++These pin the behaviours where a leaked tombstone is a real, externally-visible+bug rather than a cosmetic one, plus the promise that makes the tombstone worth+keeping at all: that a restore gives you a working app back.+"""+import os++import pytest++from app import db+from app.models import Application, Domain+from app.services import application_restore, recycle_bin_service+from app.services.cron_service import CronService+++def live_app(app):+ with app.app_context():+ row = Application(name='shop', app_type='docker', port=8001, user_id=1,+ root_path='/srv/apps/shop', source='upload',+ private_slug='shop', private_url_enabled=True)+ db.session.add(row)+ db.session.commit()+ yield row+++def dead_app(app, live_app):+ with app.app_context():+ row = Application.query.get(live_app.id)+ row.soft_delete(user_id=1)+ db.session.commit()+ yield row+++# ---------------------------------------------------------------- the basics++def test_soft_delete_keeps_the_row_but_query_active_hides_it(app, dead_app):+ with app.app_context():+ assert Application.query.get(dead_app.id) is not None+ assert Application.query_active().filter_by(id=dead_app.id).first() is None+++def test_a_tombstone_is_offered_by_the_recycle_bin(app, dead_app):+ with app.app_context():+ kinds = [i['kind'] for i in recycle_bin_service.list_deleted()]+ assert 'application' in kinds+++def test_deleted_ids_is_what_the_sibling_sweeps_read(app, dead_app, live_app):+ """ContainerSleepPolicy/BackupPolicy/DeploymentJob enumerate their OWN table+ and resolve application_id afterwards, so they never appear in a search for+ Application.query. This set is how those loops skip a deleted app."""+ with app.app_context():+ dead = Application.deleted_ids()+ assert dead_app.id in dead+++# ------------------------------------------------- the promise of a tombstone++def test_a_deleted_app_frees_its_private_slug(app, dead_app):+ """The partial unique index is what lets the slug be reused; without it the+ delete would burn `/p/<slug>` forever and 'you can get it back' would be a+ lie about the URL."""+ with app.app_context():+ twin = Application(name='shop2', app_type='docker', port=8002, user_id=1,+ private_slug='shop')+ db.session.add(twin)+ db.session.commit() # must not raise+ assert twin.id != dead_app.id+++def test_restore_is_refused_when_the_slug_was_taken_again(app, dead_app):+ """Reachable precisely BECAUSE the delete frees the slug — so it has to be+ a readable refusal, not an IntegrityError at commit."""+ with app.app_context():+ db.session.add(Application(name='shop2', app_type='docker', port=8002,+ user_id=1, private_slug='shop'))+ db.session.commit()++ item, err = recycle_bin_service.restore('application', dead_app.id)+ assert item is None+ assert 'private URL' in err+ # A refused restore must not half-apply.+ assert Application.query.get(dead_app.id).deleted_at is not None+++def test_restore_is_refused_when_the_name_was_reused(app, dead_app, monkeypatch):+ """Two live apps with one name means one vhost filename for two apps, and+ whichever writes last wins."""+ monkeypatch.setattr(os.path, 'exists', lambda _p: True)+ with app.app_context():+ db.session.add(Application(name='shop', app_type='docker', port=8002, user_id=1))+ db.session.commit()++ item, err = recycle_bin_service.restore('application', dead_app.id)+ assert item is None+ assert 'created again' in err+++def test_restore_is_refused_when_the_files_are_gone(app, dead_app):+ """Restoring the record without its files gives an app with nothing to+ serve — say so instead of handing back a broken row."""+ with app.app_context():+ item, err = recycle_bin_service.restore('application', dead_app.id)+ assert item is None+ assert 'files are gone' in err+++# ------------------------------------------------------- delete vs purge line++def test_soft_delete_never_removes_volumes(app, live_app, monkeypatch):+ """THE line that makes the tombstone honest. compose_down(volumes=True) on+ the delete path would destroy the data the Restore button is promising."""+ calls = []+ from app.services import docker_service+ monkeypatch.setattr(docker_service.DockerService, 'compose_down',+ classmethod(lambda cls, path, **kw: calls.append(kw) or {'success': True}))+ monkeypatch.setattr(application_restore.CronService, 'suspend_for_application',+ classmethod(lambda cls, _id: 0))++ with app.app_context():+ row = Application.query.get(live_app.id)+ application_restore.suspend_application(row, user_id=1)++ assert calls, 'compose_down should still run — the app must stop serving'+ assert all(kw.get('volumes') is False for kw in calls), \+ 'a soft delete must keep the volumes; they go at purge'+++def test_purge_is_what_removes_the_volumes(app, dead_app, monkeypatch):+ calls = []+ from app.services import docker_service+ monkeypatch.setattr(docker_service.DockerService, 'compose_down',+ classmethod(lambda cls, path, **kw: calls.append(kw) or {'success': True}))+ monkeypatch.setattr(application_restore.CronService, 'clear_application',+ classmethod(lambda cls, _id: 0))++ with app.app_context():+ ok, warning = recycle_bin_service.purge('application', dead_app.id)+ assert ok+ # Assert NO warning, not just success. _run_purge_hook swallows anything+ # the hook raises so a failed cleanup cannot block the purge -- which+ # means a plain `assert ok` passes even when the cleanup did nothing at+ # all. A bad import inside the hook hid exactly that during development:+ # volumes never reclaimed, source never removed, purge still "fine".+ assert warning is None, warning+ assert Application.query.get(dead_app.id) is None++ assert calls and calls[0].get('volumes') is True+++def test_purge_honours_an_explicit_remove_data_false(app, dead_app, monkeypatch):+ """Database engines default to preserving their volumes — losing the data is+ the only irreversible part of that uninstall."""+ calls = []+ from app.services import docker_service+ monkeypatch.setattr(docker_service.DockerService, 'compose_down',+ classmethod(lambda cls, path, **kw: calls.append(kw) or {'success': True}))+ monkeypatch.setattr(application_restore.CronService, 'clear_application',+ classmethod(lambda cls, _id: 0))++ with app.app_context():+ row = Application.query.get(dead_app.id)+ row._purge_remove_data = False+ application_restore.on_purge_application(row)++ assert calls and calls[0].get('volumes') is False+++def test_a_failing_purge_hook_still_purges(app, dead_app):+ """The caller has said twice that they want the row gone; a directory that+ will not delete is not a reason to keep the record."""+ # Re-register with a throwing hook, and put the real registration back in a+ # finally. _REGISTRY is module-level global state that outlives monkeypatch,+ # so leaving a broken hook in it silently breaks every LATER test in the+ # session -- which is exactly what happened: a purge test two files away+ # started failing only when this one ran first.+ def _boom(_row):+ raise RuntimeError('disk busy')++ recycle_bin_service.register(+ 'application', Application, noun='application',+ label=lambda a: a.name, on_purge=_boom,+ )+ try:+ with app.app_context():+ ok, warning = recycle_bin_service.purge('application', dead_app.id)+ assert ok+ assert 'cleanup failed' in warning+ assert Application.query.get(dead_app.id) is None+ finally:+ recycle_bin_service.register_builtin_types()+++# -------------------------------------------------------------------- cron++def test_soft_delete_suspends_only_the_jobs_that_were_enabled(app, monkeypatch):+ """The OS crontab does not know the app is in the bin, so the jobs have to+ be actively disabled — and ONLY the ones that were on, or a restore would+ re-enable jobs the user had deliberately turned off."""+ store = {'jobs': {+ 'a': {'application_id': 7, 'enabled': True, 'command': 'x', 'schedule': '* * * * *'},+ 'b': {'application_id': 7, 'enabled': False, 'command': 'y', 'schedule': '* * * * *'},+ 'c': {'application_id': 9, 'enabled': True, 'command': 'z', 'schedule': '* * * * *'},+ }}+ monkeypatch.setattr(CronService, '_load_jobs_metadata', classmethod(lambda cls: store))+ monkeypatch.setattr(CronService, '_save_jobs_metadata', classmethod(lambda cls, d: None))+ monkeypatch.setattr(CronService, 'is_linux', classmethod(lambda cls: False))++ assert CronService.suspend_for_application(7) == 1+ assert store['jobs']['a']['suspended_by_app'] is True+ assert store['jobs']['b'].get('suspended_by_app') is not True # was already off+ assert store['jobs']['c'].get('suspended_by_app') is not True # different app+++def test_restore_resumes_exactly_what_the_delete_suspended(app, monkeypatch):+ store = {'jobs': {+ 'a': {'application_id': 7, 'enabled': False, 'suspended_by_app': True,+ 'command': 'x', 'schedule': '* * * * *'},+ 'b': {'application_id': 7, 'enabled': False, 'command': 'y', 'schedule': '* * * * *'},+ }}+ monkeypatch.setattr(CronService, '_load_jobs_metadata', classmethod(lambda cls: store))+ monkeypatch.setattr(CronService, '_save_jobs_metadata', classmethod(lambda cls, d: None))+ monkeypatch.setattr(CronService, 'is_linux', classmethod(lambda cls: False))++ assert CronService.resume_for_application(7) == 1+ assert store['jobs']['a']['enabled'] is True+ assert store['jobs']['a']['suspended_by_app'] is False+ assert store['jobs']['b']['enabled'] is False # never ours to re-enable+++def test_clear_application_is_purge_only_and_lossy(app, monkeypatch):+ """It nulls the link without recording it, which is why the soft-delete path+ must NOT use it — nothing could put the association back."""+ store = {'jobs': {'a': {'application_id': 7, 'enabled': True}}}+ monkeypatch.setattr(CronService, '_load_jobs_metadata', classmethod(lambda cls: store))+ monkeypatch.setattr(CronService, '_save_jobs_metadata', classmethod(lambda cls, d: None))++ assert CronService.clear_application(7) == 1+ assert store['jobs']['a']['application_id'] is None+++# ----------------------------------------------------------- domains cascade++def test_a_tombstoned_app_keeps_its_domains(app, live_app):+ """delete-orphan on `domains` hard-deletes a child that falls out of the+ collection. A soft delete is an UPDATE, so nothing should cascade — the+ domains must survive for the restore to have anything to publish."""+ with app.app_context():+ db.session.add(Domain(name='shop.example.com', application_id=live_app.id))+ db.session.commit()++ row = Application.query.get(live_app.id)+ row.soft_delete()+ db.session.commit()++ assert Domain.query.filter_by(application_id=live_app.id).count() == 1diff --git a/backend/tests/test_database_engines.py b/backend/tests/test_database_engines.pyindex 15c3e13e..d3db5e8e 100644--- a/backend/tests/test_database_engines.py+++ b/backend/tests/test_database_engines.py@@ -838,7 +838,15 @@ class TestInstalledEngines:# ── uninstall: the data volume ───────────────────────────────────────────────class TestUninstallPreservesData:- """Safety rule 5, enforced on the shared app-delete route."""+ """Safety rule 5, now enforced by the shape of the delete rather than a flag.++ Application became soft-deletable (plan 70), so DELETE no longer destroys+ anything: it stops the app and tombstones the row, and the volumes go at+ PURGE. That makes the rule STRONGER than it was — an engine's data used to+ be protected only because `_remove_data_flag` defaulted it off, and one+ `?remove_data=true` was enough to lose it. Now nothing loses a volume until+ the row is purged, and the flag only decides what a purge does.+ """@pytest.fixturedef compose_down_calls(self, monkeypatch):@@ -861,19 +869,47 @@ class TestUninstallPreservesData:assert response.status_code == 200assert compose_down_calls == [{'volumes': False}]- def test_remove_data_true_removes_the_volume(self, client, auth_headers,- tmp_path, monkeypatch,- compose_down_calls):+ def test_remove_data_true_alone_no_longer_destroys_anything(+ self, client, auth_headers, tmp_path, monkeypatch, compose_down_calls):+ """The flag is not enough on its own any more: without ?purge the row+ goes to the bin, and a bin entry whose volumes were already destroyed+ would be a Restore button that cannot deliver."""application = _make_installed_engine(tmp_path, monkeypatch)response = client.delete(f'/api/v1/apps/{application.id}?remove_data=true',headers=auth_headers)assert response.status_code == 200- assert compose_down_calls == [{'volumes': True}]+ assert response.get_json().get('recycle_bin') is True+ assert compose_down_calls == [{'volumes': False}]- def test_ordinary_apps_keep_the_historic_behavior(self, client, auth_headers,- tmp_path, monkeypatch,- compose_down_calls):+ def test_purge_with_remove_data_true_removes_the_volume(+ self, client, auth_headers, tmp_path, monkeypatch, compose_down_calls):+ """Skipping the bin AND asking for the data gone is the one path that+ still destroys it — two explicit signals, not one."""+ application = _make_installed_engine(tmp_path, monkeypatch)+ response = client.delete(+ f'/api/v1/apps/{application.id}?purge=true&remove_data=true',+ headers=auth_headers)+ assert response.status_code == 200+ # down(volumes=False) on the way to the bin, then down(volumes=True) at purge.+ assert compose_down_calls[-1] == {'volumes': True}++ def test_purging_an_engine_still_preserves_its_data_by_default(+ self, client, auth_headers, tmp_path, monkeypatch, compose_down_calls):+ """The engine default survives the bin: losing the data is still the one+ irreversible part of an engine uninstall, so even a purge keeps it+ unless asked."""+ application = _make_installed_engine(tmp_path, monkeypatch)+ response = client.delete(f'/api/v1/apps/{application.id}?purge=true',+ headers=auth_headers)+ assert response.status_code == 200+ assert all(call['volumes'] is False for call in compose_down_calls)++ def test_ordinary_apps_also_keep_their_volumes_until_purge(+ self, client, auth_headers, tmp_path, monkeypatch, compose_down_calls):+ """This is the behaviour that CHANGED. An ordinary app used to lose its+ volumes the moment you pressed delete; now every app gets the engines'+ old protection, because every app is recoverable for 30 days."""application = _make_installed_engine(tmp_path, monkeypatch,template_id='gitea', name='git')client.delete(f'/api/v1/apps/{application.id}', headers=auth_headers)- assert compose_down_calls == [{'volumes': True}]+ assert compose_down_calls == [{'volumes': False}]diff --git a/backend/tests/test_jobs.py b/backend/tests/test_jobs.pyindex 269260c6..1aef43a3 100644--- a/backend/tests/test_jobs.py+++ b/backend/tests/test_jobs.py@@ -178,17 +178,21 @@ class TestBuiltins:assert 'builtin.security_feed' in kindsassert 'builtin.job_retention' in kindsassert 'builtin.monitor_check' in kinds- assert len([k for k in kinds if k.startswith('builtin.')]) == 13+ # Reclaims the disk a soft delete no longer frees: an Application+ # tombstone holds its data volumes and source tree until purge, and+ # nothing else calls purge_expired on a schedule.+ assert 'builtin.recycle_retention' in kinds+ assert len([k for k in kinds if k.startswith('builtin.')]) == 14builtin_handlers.seed_builtin_schedules()- # 13 builtin.* schedules (incl. job-retention, the monitor sweep and the- # security-feed check) ++ # 14 builtin.* schedules (incl. job-retention, the monitor sweep, the+ # security-feed check and the recycle-bin retention sweep) +# login-link/SSO reapers + drift/FIM/bandwidth sweeps + the host doctor# sweep (plan 26) + the setup-health nag (plan 22).- assert ScheduledJob.query.count() == 20+ assert ScheduledJob.query.count() == 21# Seeding twice doesn't duplicate.builtin_handlers.seed_builtin_schedules()- assert ScheduledJob.query.count() == 20+ assert ScheduledJob.query.count() == 21class TestApi: