Pilot structure cleanup

Status. Phase 1 is open as PR #812. Phase 2 is open as PR #813, stacked on #812. Phase 3 is open as PR #815, stacked on #813. Phase 4a (platform classes) is open as PR #816, 4b (settings and notifications) as PR #817 and 4c (task callbacks) as PR #818. Phase 5 is open as PR #819, phase 6 as PR #820, phase 7a (folders) as PR #821, and the docstrings part of phase 7b as PR #822. Phases 1 to 7a, #822 and constants part 1 (PR #823) are merged. Constants part 2 is open as PR #824. Phase 8 (frontend) is dropped: this work does not change the frontend. A correction since the first version of this page: the API TypedDict classes are not dead code. scripts/generate_ts_types.py builds the frontend TypeScript types from them on every install and build. That item is removed.

Plan · 12 November 2026 · based on branch perf/admin-api at b49ed96b

1. Why do this

Pilot has 51,600 lines of Python in pilot/ and 14,000 in admin/backend/. The main objects (Server, Bench, Site, App) are good. But much of the behavior does not live on them. It lives in loose module-level functions that take (bench_root, site_name) and similar arguments.

This causes three problems:

The goal is less code and one clear owner for each behavior. No behavior changes. Each phase is one small pull request (PR) that keeps all tests green.

2. The rule: every behavior has an owner

A loose function is a function at module level that is not a method. This plan keeps a loose function only in these cases:

All other behavior goes onto a class. The class is owned by a domain object and you get it through that object:

# Before: the caller passes the bench path and the site name
from pilot.core.site.config import list_active_apps, is_setup_complete
apps = list_active_apps(site_config, bench.path, "one.local")
done = is_setup_complete(bench.path, "one.local")

# After: the site owns its database facts
site = bench.site("one.local")
apps = site.database_state.active_apps
done = site.database_state.is_setup_complete

Rules every phase follows

This follows the repo rules in CLAUDE.md: object-owned syntax, @property for nouns, get_*() for work, and one owner for state.

3. What the audit found

All numbers are from static scans of the branch above (AST walks and grep).

FindingCountExample
Loose functions in pilot/ (not counting commands, patches, run, main)588core/site 72, internal/tasks 66, core/bench 58
Files with 10 or more loose functions34site/config.py 36, utils.py 34, platform.py 25
Module wrappers in site/__init__.py that only re-import a function from site/config.py or provisioning.py12list_installed_apps, is_setup_complete; two of them have 0 callers
Same function name defined twice10task_has_secrets in internal/tasks/args.py and managers/task/policy.py
Path(current_app.config["BENCH_ROOT"]) in API code123also 5 local _bench() / _current_bench() helpers
except Exception in API routes145a global handler for Exception and TaskConflictError already exists in api/errors.py
Routes that read Idempotency-Key and queue a task by hand24the 5 database quick-action routes are almost identical
"Read a file backwards" implementations5internal/jsonl_log.py, providers/logs.py, providers/waf.py, providers/windowed_log.py, plus a safe-JSON parse in hourly_rollup.py
Flat folders with too many files—pilot/tasks 47, tests/pilot/core 76, admin/backend/providers 17
The site config module today, and its shape after phase 2.

4. Phases

The order is by risk. Deleting dead code is first because it makes the later moves smaller. Each phase is one PR. Each PR runs ruff, mypy (mypy pilot admin/backend) and the full suite in CI. No phase changes a URL, a JSON shape or a CLI command.

Each phase below gives the same five parts: problem, change (file by file), before → after code, callers that must change, and tests.

Phase 1: Delete forwarding wrappers low risk PR #812 · −175 lines

Problem. Some code has no callers, and some functions have two copies. Every later phase must move this code, so delete it first.

FileChange
pilot/core/site/__init__.pyDelete the 12 module wrappers at the bottom of the file (lines 440–533). Two of them (_safe_site_config_path, _query_installed_apps_via_frappe) have no callers.
pilot/managers/task/policy.pyDelete the file. It only wraps internal/tasks/args.task_has_secrets. managers/task/__init__.py exports the real one.
pilot/core/database/__init__.pyread_site_config(bench_root, site_name) also checks an untrusted site name, so it is not a plain copy. It moves into SiteConfigFile in phase 2, not in this phase.
api/v1/benches/__init__.py, api/v1/sites/core.pyDelete the 4 shim routes that only import and call cloning.py. Register the cloning.py functions on the blueprints directly.
providers/waf.py, providers/windowed_log.pyTwo identical _safe_json() functions. Phase 5 merges them, so this phase does not change them.

Before → after (site/__init__.py):

# Before: a wrapper whose only job is to re-import the real function
def is_setup_complete(bench_root: Path, site_name: str) -> bool | None:
    from pilot.core.site.config import is_setup_complete as _is_setup_complete
    return _is_setup_complete(bench_root, site_name)

# After: the wrapper is gone. Callers import from the module that owns the function.

Callers. 8 import lines changed.

Tests. Tests that only check a wrapper are deleted. Behavior tests stay as they are.

Phase 2: Give Site its config and database facts medium risk

Problem. pilot/core/site/config.py has 36 loose functions and no class. They do three unrelated jobs, and each one takes (bench_root, site_name) again. SiteApps already wraps four of them with local imports.

Change. Replace the file with a site/config/ folder that holds three classes:

New class (how to get it)JobFunctions it replaces
SiteConfigFile
site.config_file
Read and write site_config.json. Refuse a path that escapes the sites folder.read_site_config, set_site_config_values, set_site_ssl_flag, clear_certificate_pin, safe_site_config_path, read_public_config, update_public_config
SiteDatabaseState
site.database_state
Read facts from the site's own database.list_installed_apps, list_active_apps, exclude_disabled_apps, query_installed_apps_via_db, query_disabled_apps_via_db, query_installed_apps_setting_via_db, has_app_disabling, has_module_defs_for_app, is_setup_complete, query_setup_wizard_apps_via_db, is_backup_encryption_enabled, query_installed_apps_via_frappe
PublicConfigMask secrets for the Admin UI and check a config patch from it.public_config, merge_public_config, config_patch_error, is_public_config_key, is_secret_config_key and 9 private helpers

Before → after:

# Before (admin/backend/providers/sites.py and others)
from pilot.core.site.config import list_active_apps, is_setup_complete
apps = list_active_apps(site_config, bench_root, name)
done = is_setup_complete(bench_root, name)

# After
site = Bench(bench_root).site(name)
apps = site.database_state.active_apps          # @property
done = site.database_state.is_setup_complete    # @property

# Before (site/apps.py): a method that only imports and forwards
def has_module_rows(self, app_name):
    from pilot.core.site.config import has_module_defs_for_app
    return has_module_defs_for_app(self.site.bench.path, self.site.config.name, app_name)

# After: SiteApps uses the owner directly, and the forwarding method goes
self.site.database_state.has_module_rows(app_name)

Callers. is_setup_complete has 15 call sites, query_installed_apps_via_db 7 and provision_from_backup 6. Most are in admin/backend/providers and tests.

Tests. Move test_site_config.py and test_config_patch.py to tests/pilot/core/site/. Patch SiteDatabaseState methods in place of module functions.

Phase 3: Break up pilot/utils.py medium risk

Problem. utils.py has 34 functions with five unrelated jobs, and 165 import lines point to it. When a file has no clear job, new code keeps landing in it.

Change. Move each job to an owner. The table shows how many importers each part has today.

Functions nowNew ownerImporters
cli_root, benches_dir, iter_sibling_benches, admin_urlServer properties: server.root, server.benches_dir (a wrapper already exists), a new server.benches property; admin_url → BenchConfig.admin_url83
run_command + 6 private helpersCommand class in internal/command.py. run_command() stays as the one public shortcut.46
host_owner, matches_wildcard, wildcard_suffix, hosts_line_contains, _bench_hosts, _site_config_hostsHostClaims → server.host_claims. normalize_host stays a pure helper.28
open_private, write_private_text, make_private_directoryPrivateFile in internal/atomic_file.py, next to atomic_write_private_text24
validate_tar_archive, extract_tar_archive + 6 helpersTarArchive(path, limits) with validate() and extract_to(root), in internal/archive.py2
directory_bytes, pick_free_port, is_port_listening, installed_app_version, redact_textMove onto the one object that uses each (SiteStorage, bench creation, App, Command)—

Before → after:

# Before
from pilot.utils import cli_root, iter_sibling_benches
for path, config in iter_sibling_benches(cli_root() / "benches" / ".rollup-placeholder"):
    ...

# After: Server gets a new `benches` property
for bench in Server().benches:
    ...

After this phase, pilot/utils.py is deleted.

Tests. tests/pilot/test_utils.py splits by new owner. The tar safety tests stay unchanged; only their imports change.

Phase 4: Platform, settings, alerts and task callbacks as objects medium risk

Problem. Four modules hold related functions with no class. Each caller must know which loose function to import.

Module nowChange
managers/platform.py
25 functions
HostPlatform with properties distro, os_version, kernel_version, is_macos, is_linux, is_root, has_passwordless_sudo, native_process_manager. ServiceControl(name) with start(), enable(), disable(), is_running in place of the 4 service_* functions. HostsFile(path) with add(host) and remove(host).
core/bench/settings.py
20 functions
The 11 *_payload(config) functions become methods on one SettingsPayload(config) class. regenerate_configs, restart_running_workload and the two restart helpers become BenchSettings methods.
core/alerts.py
12 functions
Move into core/notification/, which already owns notifications. AlertMail(mail_config) handles SMTP, rendering and sending. Notifier(bench) → bench.notifier handles send(), webhooks, mail and Central.
internal/tasks/callbacks.py
20 functions
One TaskCallbacks(task) class with one method for each hook.

Before → after:

# Before (api/v1/settings/__init__.py)
"workers": worker_groups_payload(config),
"firewall": firewall_payload(config),
"proxy": proxy_payload(config),
**waf_payload(config),

# After
payload = SettingsPayload(config)
"workers": payload.worker_groups,
"firewall": payload.firewall,
"proxy": payload.proxy,
**payload.waf,

# Before (server/monitoring.py, certificates.py, notification/events.py)
from pilot.core.alerts import notify
notify(bench, payload)

# After
bench.notifier.send(payload)

Callers. notify has 4 call sites. platform has about 40 import lines. The settings payloads have 2 callers.

Phase 5: One JSON-lines log reader low risk about −120 lines

Problem. Five modules each read a log file backwards, block by block, with their own copy of the same loop. Two of them also have the same _safe_json().

Copy nowUsed for
internal/jsonl_log.py _reversed_linesAudit log and notifications
providers/windowed_log.py _iter_lines_reversed + _safe_jsonSite monitoring windows
providers/waf.py _iter_records_reversed + _safe_jsonWAF analytics
providers/logs.py _read_tail_textLogs page tail
site/hourly_rollup.py _parseHourly rollups (reads forward from an offset)

Change. One class in internal/jsonl_log.py. All five callers use it:

class JsonLines:
    """One JSON record per line. Reads from either end without loading the file."""
    def __init__(self, path: Path) -> None: ...
    def read_lines_newest_first(self) -> Iterator[bytes]: ...
    def read_newest_first(self) -> Iterator[dict]: ...   # skips bad lines
    def read_tail_text(self, min_lines: int) -> str: ...
    @staticmethod
    def parse(line: bytes) -> dict | None: ...

The weekly-sharded JsonlLog keeps its job and uses JsonLines for each shard.

Tests. One new test_jsonl_lines.py covers block edges, a partial last line and bad JSON. Provider tests stay and must pass unchanged.

Phase 6: Thin Admin API routes medium risk about −600 lines

Problem. Routes repeat the same setup and error handling. api/errors.py already has global handlers for Exception, TaskConflictError and ConfigError, but routes catch these themselves 145 times.

Change. Add three helpers to admin/backend/api/ and use them everywhere:

HelperReplaces
current_bench() -> Bench123 Path(current_app.config["BENCH_ROOT"]), and the 5 local _bench() / _current_bench() / _bench_root() functions in databases.py, migrations.py, git.py, ssh_keys.py, tasks.py
json_body() -> dict55 request.get_json(silent=True) calls and their isinstance(data, dict) checks. It raises ApiProblem("malformed_body", 400).
queue_task(TaskClass, bench, **args)24 hand-written blocks that read Idempotency-Key, call .queue() and build the 202 response

Then delete each local except that returns the same response as the global handler. Keep a local catch only when the route returns a different code or message.

Before → after (api/v1/databases.py, real code):

# Before: 18 lines
@database_bp.post("/quick-actions/restart")
def restart_database():
    try:
        _quick_actions().require_restart()
        bench = _bench()
        task_id = RestartDatabaseTask.queue(
            bench,
            idempotency_key=request.headers.get("Idempotency-Key"),
            resource_key=_DATABASE_RESOURCE_KEY,
        )
        return accepted_task_response(bench.path, task_id)
    except (DatabaseError, TaskConflictError) as exc:
        return error_response("database_action_unavailable", str(exc), 409)
    except ValueError as exc:
        return error_response("invalid_database_action", str(exc), 422)
    except Exception:
        return error_response("database_action_failed", "Could not queue the database restart.", 500)

# After: 6 lines. DatabaseError → 409 is registered once for the blueprint.
@database_bp.post("/quick-actions/restart")
def restart_database():
    bench = current_bench()
    DatabaseQuickActions(bench).require_restart()
    return queue_task(RestartDatabaseTask, bench, resource_key=_DATABASE_RESOURCE_KEY)

The five quick-action routes (restart, performance schema, buffer pool, max connections, memory share) have the same shape. After the change each one is about 8 lines.

Risk and check. The error code strings in responses must stay the same, because the frontend reads them. Before the change, a test records the code and status for every error branch in test_databases_view.py and the other view tests. The same test must pass after the change.

Phase 7: Group crowded folders low risk, many files move

Problem. Flat folders with many files make it hard to see which parts belong together.

Folder nowNew layout
pilot/tasks/ (47 files)tasks/site/ (new, restore, backup, rename, drop, reinstall, migrate, clone), tasks/app/ (get, install, uninstall, remove, switch branch, revert), tasks/bench/ (build, restart, nginx, letsencrypt, update, lite mode), tasks/database/ (the 5 MariaDB setting tasks and restart), tasks/migration/ (4 tasks). pilot/tasks/__init__.py keeps its explicit exports, so from pilot.tasks import NewSiteTask still works.
admin/backend/providers/ (17 files)providers/site/ (uptime, monitoring, access log, summaries, sites), providers/database/ (database, slow queries, database monitoring), providers/server/ (os, system monitoring, WAF, storage, logs)
pilot/core/site/ (22 files)Add site/config/ (phase 2) and site/backups/ (backups, retention, migration backup, restore, restore directories)

This phase only moves files and fixes imports. It changes no code, so the review stays easy.

Phase 7b: Names, docstrings and constants low risk #822, #823 merged · #824 constants part 2

Problem. 2,629 of 3,871 functions and methods in pilot/ and admin/backend/ have no docstring. There are 346 module-level constants that start with an underscore.

Change. Docstrings and constants are two separate PRs, not one PR per package. PR #822 adds a one-line docstring to every function and method in pilot, admin/backend and scripts. The vendored code in pilot/_vendor is not changed. PR #823 inlines 80 _CONSTANTS that are used once and moves 97 that one class uses to lowercase class attributes. The count goes from 340 to 163. PR #824 inlines 73 more and moves 27 more to class attributes, including constants that tests patch. The count goes to 61. These 61 are in modules that have only free functions, so they have no class to move to yet. Public CLI and API names stay the same.

Check. Two counts must reach zero for each package that is done: functions without a docstring, and ^_[A-Z] module constants. A small AST script in scripts/ reports both.

Phase 8: Frontend formatters dropped

Dropped. This cleanup does not change the frontend.

Problem. Twelve components define their own formatters. formatBytes and formatPercent each have two local copies, and utils/format.ts already exports formatBytes.

Change. Move formatPercent, formatSeconds, formatMegabytes and formatGB into utils/format.ts. Move formatDate, formatFullTime and formatTimeOnly into utils/time.ts. Delete the local copies and add a new utils/format.test.ts next to the existing time.test.ts.

5. Tests

The suite has 3,889 test functions in 67,700 lines. A full local run took about 7.5 minutes, and one test used almost half of that. The suite is mostly useful. The problems are its layout and the tests that check private internals.

Slow tests

I measured a full local run with pytest --durations=40: 4,482 passed in 447 s.

TestTimeCause and fix
test_site_rename.py::test_readers_keep_the_old_path_during_failed_renames_and_retries and about 40 other rename tests205 s + about 100 sFixed in PR #812. Each rename called cert_files_exist(), which ran a real sudo test -f /etc/letsencrypt/... on the test machine. Without -n, sudo waited about 2.4 s for a password. The test setup already stubbed the other root-only certificate reads but not this one. Now the 205 s test takes 0.97 s.
test_editor_path_fuzz.py (2 tests)15 sFuzz tests. Keep them, but lower the number of examples in CI and keep a larger run for nightly builds.

Expected result: the full suite goes from about 447 s to about 150 s.

6. What this plan does not change

7. How to check success

MeasureNowTarget
Loose functions in pilot/ (same scan)588under 300
Files with 10 or more loose functions34under 8
except Exception in API routes145about 30
BENCH_ROOT reads in API code1231
Reverse log readers51
Functions and methods without a docstring2,6290
Module constants that start with _3460
Duplicate function definitions100
Full test suite, local447 sabout 150 s

Each phase must also keep ruff, mypy and the full CI suite green, and must not change any API response. The scan scripts that produced these numbers are small AST walks. They can go into scripts/ so that CI can report the numbers on each PR.