PHP 7.4.34
Preview: cloudlinux-multiphp-sync Size: 499.79 KB
//usr/sbin/cloudlinux-multiphp-sync

#!/opt/cloudlinux/venv/bin/python3 -Ibb
# -*- coding: utf-8 -*-

# Copyright © Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2026 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENSE.TXT

"""MultiPHP Manager <-> PHP Selector sync engine.

Keeps the PHP version recorded in cPanel's MultiPHP store and the version
recorded in PHP Selector in agreement for every covered domain.

Two principles govern every decision:

STATE-PURE classification — every verdict is a function of (pin value,
selector-current, isolation) only, never of stored provenance — so the same
answers hold at event time, reconcile time and restore time.

POSITIVE LEDGER — the per-user ownership record carries an entry for every
pin the mirror writes, and the mirror may only write over a pin that is
provably its own (a matching `selector` entry, or a matching `released`
one — the value we ourselves wrote on the way out) or a value that itself
delegates the domain to Selector (`inherit` / the system default — the
gateway rule: those values ARE the act of assigning control). Any other
explicit pin is takeover-as-found: recorded, skipped, never fought. Under
any uncertainty — lost record, missed event, cold start — the sync backs
off instead of overwriting an admin's decision.

COVERAGE — the sync mirrors only where PHP Selector actually serves: not
on PHP-FPM domains, and not where the web server does not run PHP as the
user inside CageFS (Coverage). A domain that was never ours out there is
reported and left alone; coverage decides where we may write, not who owns
a pin we never wrote.

HAND-BACK — a pin we DID write is returned when its domain leaves
coverage. Left standing it stops describing what the Selector serves and
starts deciding what cPanel serves, outside the cage and without the
user's Selector configuration: same version number, bare package defaults
(measured: 32 extensions against 65, PDO among the missing). cPanel pins a
whole document-root group with one value, so the value is decided per
group (handback_by_group), and ownership is released only after the write
lands (record_released) — the ledger row is the proof the pin is ours, and
dropping it early strands every withdrawal that fails. What it goes back
TO is the pin the domain arrived with, recorded as `was` by the first
mirror: `inherit` and an explicit system default mean the same thing only
until the default moves, and an admin's explicit pin must survive that.
Stopping the sync hands EVERY pin of ours back the same way (--disable,
--withdraw): a mirror pin left standing decides what is served — PHP
Selector governs only domains on the system default — so a stopped sync
with pins standing leaves the Selector non-functional for every synced
domain (measured: pin alt-php85, Selector moved to 8.4, site kept serving
8.5; unpinned, 8.4 at once).

The mirror (Selector -> MultiPHP): a complete pass over the account —
every covered domain is pinned to its selector version (account-current, or
the per-domain current for isolated domains). Partial passes are forbidden:
Apache .htaccess cascades a parent's pin onto nested-docroot children, so a
pass must always pin the children too.

The listener (MultiPHP -> Selector): classify_event() on each vhost of a
php_set_vhost_versions event:
    gateway-return  pin is inherit/system-default -> domain re-enters selector
                    coverage; ownership entry cleared, mirror pass re-run
    mirror-confirm  pin equals selector-current -> the mirror, confirmed
                    where a write of ours put it (a pending mark of ours,
                    or a pass of ours running); set in MultiPHP Manager
                    otherwise, and a takeover like any other
    takeover        anything else (any other alt-php pin, isolated website
                    or not; any non-default ea-* pin) -> domain visibly
                    transfers to MultiPHP control. The listener never writes
                    the Selector: adopting a pin into an isolated website's
                    slot changed the extensions the site loads

Own mirror writes are pre-registered as intents and consumed by the event
handler as echoes. A missed echo is harmless rather than correct: the write
classifies on its own state, as a mirror-confirm that its pending mark or
the pass still running names ours, or as a gateway-return on a native
account, where it converges on the next pass. Never as a self-takeover.

A claim that restates the pin the ledger already records as our mirror is a
no-op, not a classification: nothing changed, and the hook fires for
rejected calls too — which match precisely when they claim the value
already stored.

A domain leaves the sync only while a foreign pin stands: once that pin
reads back as a gateway value the ledger entry goes with it, so the mirror
can recover a domain even if the event that handed it back was never seen.
Every decision rests on a pin that was actually read: a domain with no pin
still appears in /etc/userdatadomains with an empty version field, so a
domain the file omits is a hole in the reading rather than an unpinned
domain, and the pass leaves it alone.

CLI (root only):
    --mirror --user U [--dry-run] [--reason TXT]   complete Selector ->
                                                   MultiPHP mirror pass;
                                                   --dry-run previews it
    --reconcile [--dry-run] [--reason TXT]         converge every account;
                                                   --dry-run previews the
                                                   plan without changes
    --check  (--user U | --all-users) [--json]     drift/ownership report;
                                                   --all-users also writes
                                                   the last-check snapshot
                                                   and logs CHECK-SUMMARY
    --first-run [--reason TXT]                     turn the sync on and
                                                   converge: baseline (once
                                                   ever), both switches on,
                                                   reconcile. The enable
                                                   verb, and the re-enable
                                                   one after --disable
    --enable/--disable [selector-to-multiphp|multiphp-to-selector|all]
                                                   kill switches (default
                                                   off); the first enable of
                                                   selector-to-multiphp also
                                                   records a baseline report.
                                                   A disable of it turns the
                                                   switch off FIRST and then
                                                   withdraws every pin of
                                                   ours (disable(), below)
    --withdraw [--dry-run] [--reason TXT]          hand every pin of ours
                                                   back to the pin its
                                                   domain arrived with; runs
                                                   only while the write
                                                   direction is off, and
                                                   reports what still stands
                                                   (exit 2 while any does)

The sync ships OFF. An administrator's --first-run (or --enable) turns it
on, and so does the `multiphp-sync` remote feature flag on a server nobody
turned it on or off for by hand (apply_flag). The flag only ever turns off
a sync it turned on itself (`enabled_by`). The boot catch-up unit only
converges an enabled box.

While a direction is on, a daily cron runs `--daily`: a fleet reconcile,
which catches whatever no hook reported, then `--check --all-users --json`,
the drift-evidence trail. Like everything that runs the sync by
itself (refresh_triggers), it is set up when a direction is turned on and
removed once both are off: a box nobody turned the sync on for carries
none of it. The package's own calls (--refresh-triggers on install and
upgrade, --remove-triggers on removal, --migrate-flag once before the
flag's units are first enabled, and --apply-flag, which those units run)
are not listed in --help.

End-user PHP Selector changes reach the engine through the CageFS proxyexec
alias MULTIPHP_SYNC: cagefs.server runs the script as root and passes the
authenticated caller's uid in PROXYEXEC_UID; the engine then mirrors that
account and refuses any argument, because cagefs.server forwards argv the
caller appended (see proxyexec_mirror and main).
"""

from __future__ import absolute_import
from __future__ import print_function

import contextlib
import fcntl
import json
import os
import pwd
import random
import re
import shutil
import subprocess
import sys
import tempfile
import time
import traceback
from collections import namedtuple
from contextlib import contextmanager

STATE_DIR = "/var/cloudlinux/multiphp-sync"
CONF_PATH = os.path.join(STATE_DIR, "sync.conf")
# refresh_triggers' own lock. Outside STATE_DIR on purpose: the installer
# takes it on every install and upgrade, and a box that never enabled the
# sync must not get even an empty state directory. /run is root's alone.
TRIGGERS_LOCK = "/run/cl-multiphp-sync.triggers.lock"
# The one switch a tenant's code may read: whether the mirror runs, which
# decides if "Handled by" and "selectorCompatible" ask whose a MultiPHP pin
# is (owned_pins, through the door from inside CageFS, where the 0600
# sync.conf and the ledger are out of reach); /opt is mounted live into
# every cage. Written by set_conf; clselect.multiphp_sync_client reads it.
PUBLIC_STATE_PATH = "/opt/cl-multiphp-sync/mirroring"
# The engine's own files share this directory with the per-account
# records (<account>.json, <account>.lock). An account name must start
# alphanumerically (ACCOUNT_NAME), so the leading underscore is a name
# no account can ever produce — `intents`, `baseline` and `reconcile`
# are all otherwise valid account names, and would collide.
INTENTS_PATH = os.path.join(STATE_DIR, "_intents.json")
LAST_CHECK_PATH = os.path.join(STATE_DIR, "_last-check.json")
BASELINE_PATH = os.path.join(STATE_DIR, "_baseline.json")
# Stands from the moment --disable turns the mirror off until nothing of
# ours stands (withdraw): a PHP Selector change meanwhile hands its account
# back first (release), and the public copy of the switch says so.
WITHDRAW_PENDING = os.path.join(STATE_DIR, "_withdraw.pending")
# LiteSpeed's handler table, kept because the log it comes from rotates:
# the table only changes when LiteSpeed itself does, and that restarts it,
# which re-logs the table. A stale copy is therefore an OLD LiteSpeed's
# table — never a newer one — so it can only withhold a mirror, never
# permit one the server cannot serve.
LSWS_ROUTES_PATH = os.path.join(STATE_DIR, "_lsws-handlers.json")
# Serializes fleet passes: the install-time job, the system-default spawn,
# the bulk-change spawn and the boot catch-up can fire close together, and
# two walks planning from independent reads would double-write and reload
# Apache twice. Non-blocking — a second pass is redundant, not queued.
RECONCILE_LOCK = os.path.join(STATE_DIR, "_reconcile.lock")
# Left behind by a pass that could not take the lock. The pass that
# holds it re-runs on seeing this, so a request is never simply lost:
# a bulk version change suppresses its per-account dispatches and
# relies on the follow-up walk, and the in-flight pass may already
# have walked past the accounts that change touched.
RECONCILE_REQUEST = os.path.join(STATE_DIR, "_reconcile.requested")
# How many times one holder will re-run for queued requests before
# leaving the rest to the next trigger — a bound, so a stream of
# requests cannot pin a box in permanent convergence.
RECONCILE_FOLLOWUPS = 2
FPM_POOL_DIR = os.path.join(STATE_DIR, "_fpm-pools")
FPM_POOL_SRC = "/var/cpanel/userdata/%s/%s.php-fpm.yaml"
LOG_PATH = "/var/log/cloudlinux/cl-multiphp-sync.log"
# The daily run's schedule (a reconcile, then the drift check), present
# only while a direction is on
# (refresh_triggers). A file of its own rather than a line in the
# package's lvemanager-cron, which every install rewrites from scratch;
# no dot in its name, which is the rule cron.d files have to meet.
CHECK_CRON_PATH = "/etc/cron.d/cl-multiphp-sync"
# --daily converges, then checks: a fleet pass catches whatever changed with
# no hook to report it, and the check it is followed by records the result
CHECK_CRON_COMMAND = ("/usr/bin/flock -n /var/run/cl_multiphp_sync_check.cronlock "
                      "/usr/share/l.v.e-manager/utils/multiphp_sync.py "
                      "--daily > /dev/null 2>&1")
# EasyApache changes which Apache modules and PHP handlers there are, and so
# where PHP Selector serves and through which handler: cPanel's package
# managers run the scripts in these directories after every ea-* transaction
# (the same places cagefs's own EasyApache hooks live). The entry is a
# symlink to EASYAPACHE_HOOK_SCRIPT, present while a direction is on
# (refresh_triggers); its name sorts after cPanel's own scripts and
# cagefs's, so the reconcile it dispatches reads what they left.
UNIVERSAL_HOOK_DIRS = (
    ("/etc/dnf/universal-hooks", "multi_pkgs/transaction"),
    ("/etc/apt/universal-hooks", "multi_pkgs/Post-Invoke"),
    ("/etc/yum/universal-hooks", "multi_pkgs/posttrans"),
)
EASYAPACHE_HOOK_DIR = "ea-__WILDCARD__"
EASYAPACHE_HOOK_NAME = "zzz-cl-multiphp-sync"
EASYAPACHE_HOOK_SCRIPT = "/usr/share/l.v.e-manager/utils/multiphp_sync_easyapache.sh"
# The rest of what runs the sync by itself, registered only while a
# direction is on too (refresh_triggers): the cPanel hooks of the
# MultiPHP -> Selector direction, and the boot catch-up.
HOOK_SCRIPT = "/usr/share/l.v.e-manager/utils/multiphp_sync_hook.py"
MANAGE_HOOKS = "/usr/local/cpanel/bin/manage_hooks"
RESTART_CPSRVD = "/usr/local/cpanel/scripts/restartsrv_cpsrvd"
SYSTEMCTL = "/usr/bin/systemctl"
CATCHUP_TIMER = "cl-multiphp-sync-catchup.timer"
# The `multiphp-sync` remote feature flag (CLOS-7859), declared by the
# package without its switch file, so it ships off. lve-utils'
# cloudlinux-flags-sync writes these per server from cl-settings; the sync
# writes the switch and the opt-out only for an administrator's own command,
# and never creates clflags' directories (cllib's).
FLAG_NAME = "multiphp-sync"
FLAGS_DIR = "/opt/cloudlinux/flags"
FLAG_SWITCH = os.path.join(FLAGS_DIR, "enabled-flags.d", FLAG_NAME + ".flag")
FLAG_OPT_OUT = os.path.join(FLAGS_DIR, "opt-out.d", FLAG_NAME + ".flag")
FLAG_REMOTE_OFF = os.path.join(FLAGS_DIR, "remote-off.d", FLAG_NAME + ".flag")
# In /run like TRIGGERS_LOCK: --apply-flag runs on every server, and one the
# flag leaves alone must get no state directory.
FLAG_LOCK = "/run/cl-multiphp-sync.flag.lock"
# A hand-back the flag's disable left unfinished, retried while the flag
# stays off at most this often: a retry is a fleet pass.
FLAG_WITHDRAW_PENDING = os.path.join(STATE_DIR, "_flag-withdraw.pending")
FLAG_WITHDRAW_RETRY = 3600
# The flag's first run, from before its switch change until its fleet pass
# ends: one cut short in between is finished by the next --apply-flag.
FLAG_FIRST_RUN_PENDING = os.path.join(STATE_DIR, "_flag-first-run.pending")
# --apply-flag's actions per run: a flag that changes during one gets the
# next, but one that keeps changing waits for the timer's next run
FLAG_ACTIONS = 3
CPANEL_DIR = "/usr/local/cpanel"
# (category, event, weight, escalateprivs), each at stage post; what each
# event means is in multiphp_sync_hook.py. escalateprivs: the classifier
# reads selector state and writes ownership records, which needs root.
# Weight 400 is meant to run after cagefs's own handler, which re-evaluates
# the Selector for the new default, so the reconcile this hook dispatches
# reads the updated state — cagefs registers at the default weight (200),
# so the order is intended, not guaranteed, and an overlap costs a pass for
# the accounts it catches. 200 on Restore: after clcommon's handler.
# set_handler (WHM MultiPHP Handlers, whmapi1 php_set_handler and
# rebuild_phpconf all raise it): a handler that moves can make a pin of ours
# change how its site runs, so the fleet is judged again.
SYNC_HOOKS = (
    ("Whostmgr", "Lang::PHP::set_vhost_versions", None, False, "post"),
    ("Cpanel", "UAPI::LangPHP::php_set_vhost_versions", None, True, "post"),
    ("Whostmgr", "Lang::PHP::set_system_default_version", 400, False, "post"),
    ("PkgAcct", "Restore", 200, False, "post"),
    # the start of every restore (phase 1, before its domains and their
    # pins), into a new account or an existing one: handle_restore_start
    ("PkgAcct", "Restore", None, False, "postExtract"),
    ("Whostmgr", "Lang::PHP::set_handler", 400, False, "post"),
    # a new account, after CloudLinux's own hook (postwwwacct, weight 300)
    # has set it up in CageFS and PHP Selector; a new subdomain (and the
    # subdomain an addon domain lives on); a new addon or alias
    ("Whostmgr", "Accounts::Create", 600, False, "post"),
    ("Whostmgr", "Domain::addsubdomain", None, False, "post"),
    ("Whostmgr", "Domain::park", None, False, "post"),
    # WHM's Modify Account: its start notes the account's main domain, its
    # end carries the ledger to a new username or main domain
    # (handle_modify_start, handle_modify). The end at weight 100, before
    # CloudLinux's own (postmodifyacct, 700), whose cagefs handler
    # re-isolates a renamed website and runs the account's pass with it:
    # unweighted, the sync's ran last, after that pass (found in review)
    ("Whostmgr", "Accounts::Modify", None, False, "pre"),
    ("Whostmgr", "Accounts::Modify", 100, False, "post"),
)
# How long an unconsumed mirror-write intent still counts as an echo. Both
# directions of error are real: too short and our own write comes back looking
# like an admin's, too long and a genuine admin write of the same value inside
# the window is swallowed as an echo. cPanel raises the hook once, inside the
# write call and after all of its writes (Whostmgr/API/1/Lang/PHP.pm), so the
# gap is that call's own duration — milliseconds for a single domain, but
# tens of seconds for a batched fleet write (see RECONCILE_CHUNK). Slack
# rather than a
# deadline in either case: classification is state-pure, so a miss costs the
# full path and still reaches the ledger entry the shortcut would have.
INTENT_TTL = 120
STATE_MODE = 0o600  # the state names who owns which domain: root-only
USERDATA_FIELDS = 10  # `==`-separated fields of an /etc/userdatadomains line
WHMAPI_TIMEOUT = 300  # a vhost batch rebuilds Apache configuration
# How long a withdrawal waits for a pass holding the fleet: a mirroring pass
# stops at its next chunk once it reads the switch off, and a chunk writes
# one cPanel call per version (fleet_lock_for_withdrawal).
WITHDRAW_LOCK_WAIT = WHMAPI_TIMEOUT + 60
# The reason cPanel gives when one domain of a php_set_vhost_versions call
# fails validation (measured, out of Cpanel::PHP::Config::_get_php_conf).
# It is the ONE failure worth splitting a batch over: the other domains
# are fine and the call was refused whole. Not a contract — if the wording
# moves, a batch with a stale domain stops converging until this is
# realigned, which its MIRROR-FAIL line makes visible; it never storms.
REJECTED_DOMAIN = "Failed to find the domain"
SELECTOR_TIMEOUT = 60  # selector queries touch one account's config only
# How many accounts one batched write covers.
#
# php_set_vhost_versions takes one version and any number of vhosts,
# whoever owns them, and its cost barely grows with the vhosts in the call
# (measured: 1 vhost 5.1s, 18 vhosts 5.3s, 108 vhosts 9.5s) while it does
# grow with the accounts touched (72 accounts in one call, 31.9s). So the
# fleet converges in chunks of accounts rather than one account per call.
#
# Measured per term on a 230-account fleet: cPanel's own work is 350ms per
# writing account (three runs, under 1% apart) and dominates; this pass
# adds ~10ms of ledger write per writing account and ~13ms of planning
# per account per round. End to end that was 53 writes in 47.6s, and 3.0s
# for the whole fleet when there is nothing to write — against the ~8s
# EACH a per-account pass cost. Do not divide a whole-pass time by the
# writes in it to get a per-account cost: the planning and the bulk reads
# are per round, and on a small fleet they dwarf the writes.
#
# This size is NOT a throughput knob — raising it does not make the pass
# faster. Measured: the same divergence took 77.7s over three chunks and
# 77.8s in one, because the cost is per account, not per call. What it
# bounds is:
#   * the chunk's per-account pass locks are open files held across the
#     call, and a shell or cron invocation gets a 1024 soft nofile limit
#     (a systemd unit gets far more, but the CLI is not always one);
#   * a rejected call costs its whole chunk a retry (see apply_batch);
#   * INTENT_TTL must outlive the call. cPanel raises our hook once, after
#     the call's writes, so every intent of a long call is as old as the
#     call when the hook reads it; past the TTL the hook takes the full
#     classification path instead of the echo shortcut. The end state is
#     the same (it is state-pure), but it is precisely the work the
#     shortcut exists to avoid — at 350ms an account, 120s is reached
#     around 340;
#   * WHMAPI_TIMEOUT is a hard ceiling — at 350ms an account the call
#     reaches 300s somewhere around 850 accounts, and a timeout there is
#     a failed call mid-write. It recovers (written_of reports whatever
#     landed and the rest is retried) but it is wasted work, so keep this
#     value an order of magnitude clear of that.
# argv is not a constraint: ARG_MAX is 2MB and a thousand vhosts costs
# ~20KB.
#
# Concurrency is deliberately absent. cPanel serialises this work
# internally, measured: four parallel chunks gave 1.2x and eight gave
# 0.8x — worse than sequential. Do not add it back.
RECONCILE_CHUNK = 100
# The tenant door is a different concern from the chunk size above: a
# rate limit on how often one account's own changes may trigger a root
# pass, so a change loop cannot drive one pass straight after another.
DOOR_PACE = 5
# A paced pass that writes nothing is logged only when the account's
# previous pass is older than this: the first no-op of a burst still shows
# that the dispatch arrived, and a tenant looping the door cannot fill the
# log with them (one line every DOOR_PACE was ~17k a day, enough for a few
# tenants to rotate the audit lines out).
NOOP_TRACE_GAP = 300
# How many times a pass will re-run for changes that arrived while it was
# running before leaving the rest to the next trigger — a bound, so a
# stream of changes cannot hold a root pass open.
PASS_FOLLOWUPS = 2
# A new domain's pass waits until the account's new domains have been quiet
# this long (settle): cPanel raises the hook before it has
# finished the domain — /etc/userdatadomains, where a pass reads pins, is
# rewritten after it, and an addon is parked onto its subdomain after the
# subdomain's hook. A stream of new domains holds it off at most
# NEW_DOMAIN_WAIT_MAX.
NEW_DOMAIN_SETTLE = 30
NEW_DOMAIN_WAIT_MAX = 600
# New accounts go to one fleet reconcile once they have been quiet this
# long (debounce): a provisioning run's creations become one walk, not one
# per account (found in review: a reconcile walks every account).
NEW_ACCOUNT_SETTLE = 120
# cPanel's account files, STARTDATE among their keys (forget_account)
CPANEL_USERS_DIR = "/var/cpanel/users"
# A restore holds its account from every pass while the process restoring
# it lives (restoring): the home directory is restored before the domains,
# and can take hours. This bounds a restore whose process hangs.
RESTORE_TTL = 7 * 86400
# A mark naming no process (an Accounts::Create of a restore, should the
# restore's start have gone unseen) holds this long.
RESTORE_UNTRACKED_TTL = 86400
# cPanel's own Perl, for the one userdata key no API removes
# (unset_phpversion)
CPANEL_PERL = "/usr/local/cpanel/3rdparty/bin/perl"
# A PHP Selector change in flight on an account (begin_change): until it
# ends, no pass writes the account, since a pin written then names the
# version the account is leaving. A caller that dies mid-change holds its
# account at most this long. A bulk move holds a chunk of accounts while
# it switches them one after another, which this has to outlast.
CHANGE_TTL = 900
# A change begun through the root CLI names the process that began it (the
# client's caller) and lasts while that one does, this long at most: a bulk
# move switching its accounts for longer than CHANGE_TTL lost its first
# accounts' changes (found in review), and one whose caller died goes at
# once rather than CHANGE_TTL later.
CHANGE_OWNED_TTL = 86400
# Changes one account may have in flight at once. A tenant opens them
# through the door, and each one is a file.
MAX_CHANGES = 16
# A change's name, chosen by the client and never a path.
CHANGE_TOKEN = re.compile(r"^[0-9a-f]{16,64}\Z")
# How long a release, and the pass that ends a change, wait for a pass
# already running on the account. Usually seconds. A fleet chunk holds all
# of its accounts while it plans and writes them, which can take longer:
# past this a release is refused, and the client says so, and the pass
# ending a change leaves a request the running pass serves.
CHANGE_LOCK_WAIT = WHMAPI_TIMEOUT + 60

# cPanel account names, which are also our state file names: the length cap
# is cPanel's own limit, and the character set keeps a name from becoming a
# path
ACCOUNT_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,31}\Z")

# The environment root children get (see run()). HOME is pinned rather than
# dropped so their behaviour does not depend on who invoked us.
SAFE_ENV = {"PATH": "/usr/local/cpanel/bin:/usr/local/sbin:/usr/local/bin:"
                    "/usr/sbin:/usr/bin:/sbin:/bin",
            "HOME": "/root"}

WHMAPI1 = "/usr/local/cpanel/bin/whmapi1"
PHP_CONF = "/etc/cpanel/ea4/php.conf"
# EasyApache's binary, at the path lve-utils reads it from on every panel
# and platform (cldetectlib.get_apache_modules)
HTTPD = "/usr/sbin/httpd"
# `httpd -M` parses the whole vhost set; generous, but it must not sit in
# a cPanel request forever (see run)
HTTPD_TIMEOUT = 60
SELECTORCTL = "/usr/bin/selectorctl"
CL_SELECTOR = "/usr/sbin/cloudlinux-selector"

# LiteSpeed builds one PHP handler per alt-php version, from a candidate
# list compiled into the server, and logs the whole table on every config
# load. cPanel's registry is wider than that list: measured on a stock
# litespeed-CL7 box with no sync installed, php_get_installed_versions
# offers alt-php86 and php_set_vhost_versions accepts it, LiteSpeed builds
# handlers for alt-php44..85 only, and the domain then serves the PHP CGI
# notice at HTTP 200. Apache serves the same pin correctly. Nothing on the
# cPanel side reflects the difference, so the log is the only statement of
# it — see Coverage.route_gap for what is done with it and why reading it
# here is sound.
LSWS_BIN = "/usr/local/lsws/bin/lshttpd"
# LiteSpeed reads a document root's .htaccess, where cPanel writes a
# domain's MultiPHP version, from a cache it checks against the file only
# every few seconds; Apache reads the file on every request. Measured on
# LSWS 6.3.6 with two worker processes: the last request served from the
# old .htaccess started 1.0 to 3.7 s after the new one landed (24 changes
# at random points of the check's cycle). A release waits this long after
# its hand-backs (settle_for_lsws), or the switch it steps aside for comes
# first, and the site runs the version it is leaving with the server-wide
# extensions until LiteSpeed serves the new pin (found in CI: 9 and 16
# responses on the CL7 LiteSpeed cell).
LSWS_HTACCESS_SETTLE = 5
LSWS_LOG = "/var/log/apache2/error_log"
# Only the tail: the table is re-logged on every config load, so the
# current one is at the end, and this file is a busy server's error log.
# Small deliberately — read_coverage runs on the hook path too, inside the
# cPanel request php_set_vhost_versions raises it from, and that write is
# itself what restarts LiteSpeed and re-logs the table. A box whose table
# has scrolled past this is covered by the cached copy instead.
LSWS_LOG_TAIL = 4 * 1024 * 1024
# Anchored to LiteSpeed's OWN line, because this log is reachable by
# anyone who can make a request: a GET for a missing path echoes the path
# back as `File not found [...]`, with a real timestamp, so `Create PHP
# handler [alt-php86] with PHP binary [` in a URL is otherwise a
# perfectly-formed table row from an unauthenticated stranger. Everything
# LiteSpeed derives from a request carries its connection field
# (`[ip:port#vhost]`) after `[T0] `; the config-load lines this reads do
# not, and nothing request-shaped can begin at that offset. The binary
# path is checked against the package for the same reason (lsws_binary_ok).
LSWS_PREFIX = (r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+ "
               r"\[[A-Z]+\] \[\d+\] \[T\d+\] ")
LSWS_HANDLER_RE = re.compile(
    LSWS_PREFIX + r"Create PHP handler \[((?:alt|ea)-php\d{2,3})\] "
                  r"with PHP binary \[([^\]]+)\]\s*$")
# The lines that bracket one config load's table. BOTH are required,
# because a PARTIAL table is worse than none: it marks still-routable pins
# unroutable and the planner then withdraws them. The end marker is absent
# while the table is still being written; the start marker is absent when
# the tail began inside the burst. Markers rather than line positions
# because the rows are NOT adjacent — worker lines sit between them, which
# is the same interleaving LSWS_TABLE_WINDOW exists for.
LSWS_TABLE_START_RE = re.compile(
    LSWS_PREFIX + r"Loading configuration from /")
LSWS_TABLE_END_RE = re.compile(
    LSWS_PREFIX + r"Default PHP handler is \[")
LSWS_TS_RE = re.compile(r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})")
# One table is logged in a burst — measured at under a millisecond end to
# end — but the workers of a graceful restart write theirs into the same
# file, so the lines of one table are NOT contiguous. The window is what
# separates one config load's table from the previous load's, and it is
# generous because being late by a table only ever withholds a mirror.
LSWS_TABLE_WINDOW = 5.0


# --------------------------------------------------------------------------
# pure decision core (unit-tested in tests/common-tests/test_multiphp_sync.py)
# --------------------------------------------------------------------------

def since_of(entry, owner, now):
    """When the current owner took the domain: preserved while the owner
    stays the same, restamped when the domain changes hands."""
    return entry.get("since") if entry.get("owner") == owner else now


def to_pkg(sel_ver):
    """
    Translate Selector version -> MultiPHP pin value that the mirror
    writes into cPanel's store:
        '8.2' -> 'alt-php82'
        'native' -> 'inherit'
    """
    if sel_ver == "native":
        return "inherit"
    return "alt-php" + sel_ver.replace(".", "")


def from_pkg(pkg):
    """
    MultiPHP pin value -> selector version, or None if unrepresentable:
        'alt-php82' -> '8.2'
        'ea-php*'/'inherit' -> None
    """
    if not pkg or not pkg.startswith("alt-php"):
        return None
    digits = pkg[len("alt-php"):]
    # isdigit() alone accepts non-ASCII digits, and a version that only
    # LOOKS numeric would read as the Selector's own value
    # (arrival_is_selectors) and as a version the Selector could hold.
    # Under two digits there is no minor version to split off: 'alt-php8'
    # would yield '8.'
    if not digits.isascii() or not digits.isdigit() or len(digits) < 2:
        return None
    return "%s.%s" % (digits[0], digits[1:])


class NoKey(str):
    """The pin of a domain whose userdata has no phpversion key: the empty
    last field of /etc/userdatadomains. It is `inherit` to every reader;
    only a claim tells it apart (selector_claim's `bare`): cPanel's restore
    takes the backup's version only where the live vhost has no key, and
    setting `inherit` in MultiPHP Manager writes one (found in review: read
    alike, a restore's start took an admin's `inherit` away)."""


NO_KEY = NoKey("inherit")


def arrival_of(was, bare):
    """A stored `was` as a claim's `arrived` (selector_claim): an `inherit`
    recorded with no key (`bare`, or a row from before the field) is NO_KEY
    again. Found in review: read from a pending mark as a plain `inherit`,
    the claim recorded a key the admin set, and the next restore kept the
    sync's key over the backup's version."""
    return NO_KEY if was == "inherit" and bare is not False else was


def parse_userdatadomains(lines):
    """
    Parse /etc/userdatadomains lines into (alias_map, raw_pins).

    whmapi's php_get_vhost_versions RESOLVES `inherit` to the effective
    version (an addon reports its parent's pin), hiding whether an explicit
    pin exists — raw_pins carries the real per-domain record. alias_map maps
    each addon's internal subdomain-FQDN form to the addon name: hook events
    may carry either form, and exact mapping is required (containment
    matching routed the alias to the PARENT domain).

    Line format of /etc/userdatadomains — ten `==`-separated fields, the
    last of them the pin (empty when the domain has none):
    name: user==owner==type==<linked>==docroot==ip:80==ip:443====0==phpversion

    E.g. these two lines
      a.test: bob==root==addon==a.test.main.test==/home/bob/a==...==inherit
      main.test: bob==root==main==main.test==/home/bob/ph==...==alt-php82
    yield
      alias_map = {"a.test.main.test": "a.test"}
      raw_pins  = {"a.test": "inherit", "main.test": "alt-php82"}

    A line with fewer fields is truncated, not a shorter dialect: reading
    its last field would take the docroot for a pin, and a docroot is
    neither a gateway value nor anything the ledger can prove, so the
    domain would freeze as takeover-as-found.
    """
    aliases, raw_pins = {}, {}
    for line in lines:
        if ": " not in line:
            continue
        name, rest = line.split(": ", 1)
        fields = rest.split("==")
        if len(fields) < USERDATA_FIELDS:
            continue
        dom_type, linked = fields[2], fields[3]
        raw_pins[name] = fields[USERDATA_FIELDS - 1].strip() or NO_KEY
        if dom_type == "addon" and linked:
            aliases[linked] = name
    return aliases, raw_pins


def resolve_event_vhost(target, by_name, aliases):
    """Resolve an event's domain name to a known vhost entry, exactly.

    Never guess: an unresolved name returns None (skip + log) rather than a
    containment match — 'third.test.clos4727.test' contains 'clos4727.test',
    and attributing the event to the parent would mis-record a takeover
    against the wrong domain."""
    if target in by_name:
        return by_name[target]
    alias = aliases.get(target)
    if alias and alias in by_name:
        return by_name[alias]
    return None


def selector_suspended(default_pkg):
    """True when the sync must not act, because its gateway rule does not
    hold here.

    The rule reads `inherit`, and a pin equal to the system default, as
    "delegated to the selector" — true only while that default IS the
    ea-php chain the selector bends. Under an alt-php default `inherit`
    resolves to a version an admin chose, so gateway-return and same-value
    verdicts would both be wrong. An unknown default suspends for the
    same reason: without it, every
    default-pinned domain reads as a takeover.

    Asked of the default we compare pins against, not of a second source
    that could disagree with it. That also settles LVEMAN-1170 without
    asking about it, since the selector disables only when the default is
    NOT ea-php. The converse — a live selector under an alt-php default,
    where selector modules are required — suspends deliberately rather than
    sync against a rule that does not hold; the checker is not gated by
    this, so the drift stays visible."""
    return not (default_pkg or "").startswith("ea-php")


def is_gateway(value, default_pkg):
    """The gateway rule: `inherit`, and a pin equal to the system default,
    ARE the act of delegating a domain to the selector — they say "serve
    the default", and the default is the chain the selector bends
    (selector_suspended() gates every consumer on that premise). Stated
    once because three decisions apply it — classify_event, verdict_of and
    the planner via domain_reading — and they must never disagree."""
    return value in ("inherit", default_pkg)


def native_target(entry, raw_pin, default_pkg):
    """What the mirror carries for a domain of a native account or website.
    The Selector names no version there, so the site serves MultiPHP's own
    value, the one it would carry without the sync: a gateway value that is
    not ours stays as it is, and a pin of ours goes back to the gateway
    value it arrived with, `inherit` where that is not known. An explicit
    default is not `inherit` here: it shields the sites below it from a pin
    above, where `inherit` lets that pin through (found in review: the
    mirror rewrote one to `inherit`, and a nested site ran its parent's
    version)."""
    ours = (entry.get("owner") == "selector"
            or entry.get("reason") == "released") \
        and entry.get("version") == raw_pin
    value = entry.get("was") if ours else raw_pin
    return value if is_gateway(value, default_pkg) else "inherit"


# The reason a withdrawal gives for taking every domain out of coverage at
# once — carried on the Coverage (Coverage.withdrawn) so the planner, its
# skip lines and the log all say it, rather than something false about the
# box's Apache.
WITHDRAWING = "the sync is withdrawing its pins"
# A release's (release()): the same walk for one change, which hands each
# pin of ours back to a value PHP Selector serves through, so that the
# Selector's switch reaches the site by itself.
RELEASING = "the sync is stepping aside for a PHP Selector change"
# PHP Selector's own answer for an account outside CageFS: selectorctl
# refuses it (ClSelectExcept.NotCageFSUser, printed as "ERROR:User <name>
# not in CageFS"), which it does only where it runs on CageFS, not in its
# without-CageFS mode. selector_state reads it as this, in place of the
# account's version, and every domain of the account as out of coverage
# (domain_reading): the Selector serves none of them.
OUTSIDE_CAGEFS = "the account is outside CageFS"


class Coverage(namedtuple("Coverage",
                          ["suexec", "suphp", "handlers", "routes",
                           "withdrawn"])):
    """Where PHP Selector actually serves on this box — read once per pass
    by read_coverage(), asked per domain through gap().

    The Selector bends the PHP binary inside the user's CageFS, so a script
    the web server does not run as the user, in the cage, is served by
    MultiPHP alone whatever version the Selector holds — and a mirror pin
    there would change what the site runs instead of naming it. The
    Selector's own statistics already state the conditions
    (clselectstatistics.get_php_selector_usage and
    clselectdomains._is_acceptable_php_handler_cpanel); this is the same
    rule, applied before a write: Apache must load suEXEC or suPHP at all,
    and a domain's php.conf handler must be suphp or lsapi, or cgi/fcgi
    under suEXEC.

    LiteSpeed gets no exemption here, deliberately, though it does run PHP
    as the user itself. The rule this copies has none either — the
    statistics ask for suEXEC or suPHP whatever the server is — and the
    only reading of "LiteSpeed is running" available to us is a pid file
    in the world-writable temporary directory, which an uncaged user can
    forge; believed, it would answer "covered" for every domain and
    resume precisely the writes withheld here. A LiteSpeed box reaches
    the same conclusion by its own facts instead: whatever suEXEC or
    suPHP its EasyApache configuration carries, and the lsapi handler its
    domains sit on, which is covered outright. Where it carries neither
    module the sync writes no new pin and hands back the ones it wrote,
    which is what the statistics already say of such a box — and visible
    in the log, since the withdrawal is a write like any other.

    An account outside CageFS is judged by the Selector's own answer: it
    refuses such an account by name (OUTSIDE_CAGEFS), which takes every
    domain of the account out of coverage, so the pins of ours there go
    back; on a box running the Selector's own without-CageFS mode it does
    answer and really is serving. Its answer is the boundary either way —
    a CageFS test of our own would disable that mode's boxes wrongly. Any
    other failure is no answer, and such an account is never written.
    Found in CI: left standing, a pin of ours ran its alt-php outside the
    cage with the server-wide extensions, where without the sync the site
    ran what it arrived with, after an admin's `cagefsctl --disable` and,
    in CageFS's "Disable All" mode, after a restore or a rename.

    handlers: {package: handler} from php.conf, None when it could not be
    read — a version without a row is unknown here, not excluded (its pin
    is hold_unservable's to hold). PHP-FPM is the vhost's own flag, judged
    by domain_reading next to this. A reading nobody could take is not a
    Coverage at all: read_coverage returns None, and every caller refuses
    as it refuses an unanswered vhost list.

    routes: what the web server can route a vhost to (lsws_routes) — None
    where the question does not arise, which is every box without
    LiteSpeed. handlers answers a different question and cannot stand in
    for it: php.conf lists alt-php86 and Apache really does serve it,
    while LiteSpeed builds no handler for it at all.

    withdrawn: the reason a disable is handing every pin of ours back, or
    None on every reading taken from the box. Set by the withdrawal pass
    on a coverage read for real (_replace), never by read_coverage: `inert`
    then answers it for every domain, so plan_mirror can only plan
    hand-backs — the path a box that lost suEXEC already takes — while
    `handlers` still says which values the web server can serve. Like
    `routes`, it can only ever take coverage away."""

    def __new__(cls, suexec, suphp, handlers, routes=None, withdrawn=None):
        return super(Coverage, cls).__new__(cls, suexec, suphp, handlers,
                                            routes, withdrawn)

    @property
    def inert(self):
        """Why the Selector serves nothing on this box — or why the sync is
        leaving every domain alone regardless — or None."""
        if self.withdrawn:
            return self.withdrawn
        if self.suexec or self.suphp:
            return None
        return Why("Apache runs neither suEXEC nor suPHP", "handler")

    def handler_inert(self, pkg):
        """Why a domain served through pkg's handler is beyond the
        Selector, or None."""
        handler = (self.handlers or {}).get(pkg)
        if handler is None or handler in ("suphp", "lsapi"):
            return None
        if handler in ("cgi", "fcgi"):
            if self.suexec:
                return None
            return Why("%s handler without suEXEC" % handler, "handler")
        return Why("%s handler" % handler, "handler")

    def route_gap(self, pkg):
        """Why the web server cannot serve a domain pinned to pkg, or None.

        The Selector reaches its versions through one version-agnostic
        handler (`phpsel` -> /usr/local/bin/lsphp) whose binary CageFS
        substitutes per user, so it can serve any installed alt-php and
        never asks the web server about a version. A mirror pin moves the
        domain onto a PER-VERSION handler instead. Same binary, same cage,
        same version — but only while that handler exists, and on
        LiteSpeed it may not.

        `inherit` is exempt and must stay so: it is the way back OUT of an
        unroutable pin, so holding it would strand the domain on one."""
        if pkg in ("inherit", "", None) or self.routes is None:
            return None
        if self.routes is ROUTES_UNKNOWN:
            return Why("handler list unreadable", "unroutable")
        if pkg not in self.routes:
            return Why("no %s handler" % pkg, "unroutable")
        return None

    def handler_mismatch(self, pkg, default_pkg):
        """Why a pin to pkg would run the site through another handler than
        the one PHP Selector serves it through, or None.

        PHP Selector serves every site it governs through the system
        default's handler: CageFS bends the default version's binary, and
        the request never leaves that handler. A pin moves the site onto
        pkg's own handler, so where the two differ the pin changes how the
        site runs even though the PHP version is the same — measured on a
        live box with alt-php81 on lsapi and the default on cgi: the SAPI
        turned from cgi-fcgi to litespeed and `.htaccess` php_value lines
        began to apply.

        No row for pkg is not judged here: Apache has no handler for it at
        all, and hold_unservable holds that write. An unreadable php.conf
        likewise. No row for the default is: nothing can be compared, so no
        pin is written, and pins of ours go back. LiteSpeed serves every
        version through its own
        LSAPI whatever php.conf says, so there this rule can only withhold
        a pin that would have been harmless — the safe side."""
        if pkg in ("inherit", "", None) or pkg == default_pkg \
                or self.handlers is None:
            return None
        want = self.handlers.get(pkg)
        if want is None:
            return None
        base = self.handlers.get(default_pkg)
        if base is None:
            return Why("no handler recorded for the system default %s"
                       % default_pkg, "handler")
        if want != base:
            return Why("%s runs PHP through %s, the system default %s "
                       "through %s" % (pkg, want, default_pkg, base),
                       "handler")
        return None

    def gap(self, reported, target, default_pkg):
        """Why the sync must leave a domain alone, or None. Both the
        handler serving it now and the one its mirror pin would bring must
        be the Selector's, and the pin's must be the one the Selector
        serves the site through: otherwise the write itself changes how
        the site is served.

        `reported` is the version whmapi RESOLVES for the domain, never
        its raw pin — an addon that merely inherits its parent's alt-php74
        is served through alt-php74's handler, not the default's, and
        judging it by the default would permit exactly the write this
        forbids. The product's own rule reads the same resolved version
        (cpapi's get_domains_php_info). Only when there is nothing to
        resolve does the default stand in for it. Whether that parent's
        pin makes the domain the Selector's at all is domain_reading's
        question (upstream_pins), not this one's."""
        if self.inert:
            return self.inert
        served = default_pkg if reported in ("inherit", "", None) else reported
        wanted = default_pkg if target == "inherit" else target
        return (self.handler_inert(served) or self.handler_inert(wanted)
                or self.handler_mismatch(wanted, default_pkg))


def classify_event(version, cur_pkg, default_pkg, isolated):
    """State-pure classification of a MultiPHP pin write on one domain.

    version     pin just written ('inherit', 'ea-php83', 'alt-php82', ...)
    cur_pkg     pkg-mapped selector-current for the domain
    default_pkg system default version (the ea-php chain)
    isolated    the domain has its own per-domain selector slot
    """
    if is_gateway(version, default_pkg):
        return "gateway-return"
    if version == cur_pkg:
        # Same-value marker-less pin: the mirror, confirmed, where a write
        # of ours put it, and an admin's otherwise. Decided in the write
        # phase, under the lock (handle_event): our own pass is running, or
        # its pending mark names the value. A reconcile's writes are ours by
        # both.
        return "mirror-confirm"
    # Anything else is MultiPHP's — on an isolated website too. Adopting an
    # alt-php pin into the website's own selector slot used to keep the
    # Selector in control, but it changed how the site runs: the website
    # then loads its own extension set for that version, where without the
    # sync it runs the server-wide one (CageFS links only the SELECTED
    # version to the Selector's extensions). `isolated` stays in the
    # signature as a fact the caller has; no decision rests on it now.
    return "takeover"


# Everything a decision may know about one domain, assembled in one place:
# the planner and the checker must judge the same facts, read the same way.
DomainReading = namedtuple("DomainReading", [
    "dom",       # vhost name
    "reported",  # the version whmapi reports (inherit already resolved away)
    "fpm",       # PHP-FPM serves this domain: out of coverage
    "entry",     # its ownership-ledger entry, or {}
    "pin_read",  # the raw pin was actually read from /etc/userdatadomains
    "raw_pin",   # that raw pin, or None when it was not read
    "gateway",   # the pin is a gateway value (False when it was not read)
    "sel_cur",   # selector version serving the domain ('8.2' or 'native')
    "target",    # the pin the mirror would write: to_pkg(sel_cur)
    "inert",     # why the sync leaves the domain alone: 'fpm', a Coverage
                 # reason, or None when it is covered (or its pin unread)
    "unroutable",  # the subset of `inert` the web server causes: covered,
                 # but it has no handler for the pin this domain would
                 # carry. Named apart because the remedy is not the
                 # admin's handler configuration but the web server's
                 # version support, and because an admin's own pin keeps
                 # its ownership verdict while still reporting this.
    "served",    # PHP Selector serves the domain: `inert` judged without a
                 # withdrawal or a release (Coverage.withdrawn), which
                 # leave every domain alone whoever serves it. A release
                 # steps aside only where the Selector serves (group_back).
])


def effective_entry(entry, raw_pin):
    """The ledger row as the evidence has it.

    A pass marks each write pending, with what it replaces, before making it
    (record_pending); the claim that follows replaces the mark. A mark still
    there whose version the store holds is a write of ours that landed while
    its claim did not — the pass died in between — and the row is the claim
    it would have left. Read as it stands instead, the next pass took our
    own pin for one set in MultiPHP Manager, and a withdrawal did not see a
    pin of ours at all. A mark the store does not hold is a write that never
    landed, and changes nothing.

    A step-aside of ours whose pin has moved since is a hand-back whose pin
    moved, and reads as the `released` row it is: someone else's pin stands
    there, set while the listener left the domain alone (out of coverage,
    handle_event) or was off, and what the domain carries now is what a
    later hand-back restores (selector_claim). Found by a sequence fuzzer:
    read as ours, the pass that pinned the domain again kept the alt-php it
    had first arrived with, and the --disable after it restored that over
    the admin's `inherit`."""
    pending = entry.get("pending")
    if not isinstance(pending, dict) or raw_pin is None \
            or pending.get("version") != raw_pin \
            or entry.get("reason") in ("takeover", "takeover-as-found") \
            or (entry.get("owner") == "selector"
                and entry.get("version") == raw_pin):
        if entry.get("reason") == "step-aside" and raw_pin is not None \
                and entry.get("version") != raw_pin:
            return dict(entry, owner="multiphp", reason="released")
        return entry
    row = {"owner": "selector", "version": raw_pin, "reason": "mirror",
           "since": pending.get("since") or entry.get("since")}
    if isinstance(pending.get("was"), str):
        row["was"] = pending["was"]
        if "bare" in pending:
            row["bare"] = pending["bare"]
    return row


def arrived_pin_stands(entry, raw_pin):
    """Whether `entry`, a row of ours or the hand-back of one, stands on an
    alt-php pin at the version the domain arrived with (`was` equal to it):
    a pin set in MultiPHP Manager, which the sync once took for its own
    without writing it, or which a hand-back restored. MultiPHP's, also
    where it equals the account's PHP Selector version: served with the
    Selector's settings only while the two agree, it stays on its version
    when the Selector moves, without the sync (the_domains_own). Decided
    2026-10-12: taken for the sync's own (7.11.51), such a pin followed
    every later Selector change."""
    return raw_pin is not None and from_pkg(raw_pin) is not None \
        and entry.get("version") == raw_pin and entry.get("was") == raw_pin \
        and (entry.get("owner") == "selector"
             or entry.get("reason") == "released")


def arrival_is_selectors(was, default_pkg, handlers=None):
    """Whether a domain that arrived with `was` would be PHP Selector's
    without the sync — the question every pin of ours is held to.

    `inherit` and the system default are the gateway: the Selector serves
    them. An alt-php version is the Selector's own value, which an admin
    set to match it, or which a restore or a transfer brought back as one
    of ours; it follows the Selector, documented. An ea-php version that is
    not the default is an admin's choice, which the gateway rule took only
    because it WAS the default when the sync first mirrored the domain:
    with the default moved away, the domain would serve it without the
    sync, so it goes back to it — while it is installed (handlers, php.conf's
    table). One EasyApache has since removed serves nothing, and cPanel
    moves its domains to the default: the Selector's again. Found in review:
    handed back as `inherit` instead, every pass flipped the domain between
    that and the Selector's version. A row with no `was` predates the field,
    and a hand-back of one restores `inherit` (handback_by_group)."""
    if was is None or not isinstance(was, str):
        return True
    if is_gateway(was, default_pkg) or from_pkg(was) is not None:
        return True
    return handlers is not None and was not in handlers


def nosync_pins(raw_pins, record, default_pkg, handlers=None):
    """The pin map as it would read without the sync, for judging what the
    .htaccess cascade brings a nested site. A pin of ours standing reads as
    what the domain would carry instead: `inherit` where it arrived with the
    Selector's own value (arrival_is_selectors), the admin's version it
    arrived with otherwise. Found in review: read as it stood, a pin of
    ours on blog in public_html/blog hid main's admin version from dev in
    public_html/blog/dev, and only a later pass handed dev back.

    Except a pin set in MultiPHP Manager that a row of ours stands on (`was`
    equal to it: arrived_pin_stands), which reads as itself: MultiPHP's,
    it stands without the sync, and the sites below it run it. Found in
    review: read as `inherit`, it made the isolated website below the main
    domain the Selector's, and the next pass pinned the website from
    main's 8.2 to its own 8.0. And an arrival on the explicit default reads
    as that:
    the Selector's as `inherit` is, it shields the sites below it from a
    pin higher up, which `inherit` does not (found in review: read as
    `inherit`, the site below was taken for one under a foreign pin, and
    every pass handed both back and the next re-pinned them). So does an
    alt-php the domain arrived with that a pin of ours has followed since:
    an explicit pin, as serving_gap reads it, and the Selector's, which is
    the named default, where its hand-back goes (group_back). Found in
    review: read as `inherit` here, an admin's pin above reached the
    website below, every other pass pinned the website and re-pinned this
    domain, and the next handed both back, an Apache restart each."""
    if not raw_pins:
        return raw_pins
    entries = record["domains"]
    pins = dict(raw_pins)
    for dom, pin in raw_pins.items():
        entry = effective_entry(entries.get(dom, {}), pin)
        if entry.get("owner") == "selector" and entry.get("version") == pin \
                and entry.get("was") != pin:
            was = entry.get("was")
            explicit_default = isinstance(was, str) and was == default_pkg \
                and was not in ("", "inherit")
            if explicit_default or not arrival_is_selectors(
                    was, default_pkg, handlers):
                pins[dom] = was
            elif isinstance(was, str) and from_pkg(was) is not None \
                    and default_pkg:
                pins[dom] = default_pkg
            else:
                pins[dom] = "inherit"
    return pins


def upstream_pins(vhosts, raw_pins):
    """{domain: (parent domain, its pin)} for each domain another domain's
    explicit pin reaches through Apache's .htaccess cascade while its own
    pin is `inherit` — the nearest such one. It is that pin, and whose it
    is, that decides whether PHP Selector serves the domain at all
    (serving_gap).

    Two readings, and either one is enough. cPanel names the domain whose
    pin it resolves an `inherit` domain to (whmapi's phpversion_source,
    measured: a subdomain in public_html/in under a main domain pinned to
    ea-php81 reports {"domain": main}). That answer is gone where a pin of
    ours stands on the domain — cPanel then names the domain itself — so
    the document roots are walked too: a root inside another domain's of
    the same account is nested, and a directory that only shares a name
    prefix is not. A domain sharing the root is nearer than any parent:
    the two have one .htaccess, which carries its pin (cPanel writes such
    a group together, handback_by_group; found in review, a subdomain made
    in a main domain's root beside the admin's ea-php81 was the Selector's
    to the planner, and the group flipped every pass). An `inherit` parent
    explains nothing, and the walk goes on up; one whose pin nobody read is
    unknown, and comes back as (domain, None): found in review, a parent
    missing from /etc/userdatadomains read as no parent, and the site below
    it as the Selector's. The callers pass the pin map as it would read
    without the sync (nosync_pins), so a parent carrying a pin of ours is
    read as the parent it would be without one. Two readings that could
    disagree can only ever take a domain OUT of the sync: a domain wrongly
    left alone is served as without the sync, never differently."""
    if not raw_pins:
        return {}
    groups = {}
    for v in vhosts:
        root = (v.get("documentroot") or "").rstrip("/")
        if root:
            groups.setdefault((v.get("account"), root), []).append(v["vhost"])
    result = {}
    # each root's own directories, nearest first (found in review: every
    # root against every other, sorted once per domain, took 9 s a pass
    # for an account of 4,000 domains)
    for (account, root), doms in groups.items():
        for dom in doms:
            path = root
            while path and dom not in result:
                for p_dom in sorted(groups.get((account, path), ())):
                    pin = raw_pins.get(p_dom)
                    if p_dom != dom and pin != "inherit":
                        result[dom] = (p_dom, pin)
                        break
                path = path.rpartition("/")[0]
    for v in vhosts:
        source = v.get("phpversion_source")
        parent = source.get("domain") if isinstance(source, dict) else None
        if not isinstance(parent, str) or parent == v["vhost"] \
                or v["vhost"] in result:
            continue
        pin = raw_pins.get(parent)
        if pin != "inherit":
            result[v["vhost"]] = (parent, pin)
    return result


class Why(str):
    """A reason in words, with the code the daily report counts it by
    (CLOS-7904): the words are the log's and the admin's, the code the
    fleet counters', so no message is ever parsed."""

    def __new__(cls, text, code):
        why = str.__new__(cls, text)
        why.code = code
        return why


class UnknownAbove(Why):
    """serving_gap's answer for a site on `inherit` below a parent whose pin
    nobody read: not a reason to leave it alone, but no reading at all
    (domain_reading)."""

    def __new__(cls, parent):
        return Why.__new__(cls, "below %s, whose pin could not be read"
                           % parent, "unknown-above")


def serving_gap(dom, raw_pin, entry, upstream, default_pkg, handlers=None):
    """Why PHP Selector would not serve the domain WITHOUT the sync, or
    None — and with it, why the sync must leave it alone (and hand back a
    pin of its own there). The domain is judged by its own pin with ours
    undone: `was` where our pin stands, the raw pin otherwise.

    An admin's ea-php version that is no longer the default: see
    arrival_is_selectors. A domain on `inherit` runs the version the
    .htaccess cascade brings it — measured on a live box: a subdomain in
    public_html/sub under a main domain an admin pinned to ea-php81 ran
    PHP 8.1 with 66 extensions, and the mirror took its `inherit` for the
    Selector's and wrote alt-php82 over it: 8.2, 35 extensions, no PDO.
    The cascade is the Selector's when the pin it brings, as it would stand
    without the sync (nosync_pins), is the gateway value; anything else is
    MultiPHP's version reaching the domain."""
    standing_ours = entry.get("owner") == "selector" \
        and entry.get("version") == raw_pin
    if standing_ours:
        was = entry.get("was")
        if not arrival_is_selectors(was, default_pkg, handlers):
            return Why("set to %s in MultiPHP Manager, no longer the system "
                       "default" % was, "arrival-moved")
        own = was if isinstance(was, str) and was else "inherit"
    else:
        own = raw_pin
    if own != "inherit":
        return None
    parent = (upstream or {}).get(dom)
    if parent is not None:
        p_dom, p_pin = parent
        if p_pin is None:
            return UnknownAbove(p_dom)
        # the map is the one without the sync (nosync_pins): a pin of ours
        # there is one the parent arrived with, and runs as without it
        if is_gateway(p_pin, default_pkg):
            return None
        return Why("runs %s, inherited from %s" % (p_pin, p_dom), "cascade")
    return None


def domain_reading(vhost, account_current, isolated_versions, default_pkg,
                   record, raw_pins, coverage, upstream=None):
    """Read one domain: vhost is its whmapi entry, raw_pins the
    {domain: phpversion} map from /etc/userdatadomains (None when that file
    could not be read or yielded nothing), coverage the box's Coverage,
    upstream the account's upstream_pins (None: no domain is nested).

    The raw map is the only trustworthy pin source: whmapi RESOLVES
    `inherit` to the effective version, so a domain that merely inherits a
    mirrored parent's pin looks already-pinned in whmapi's view. And a
    domain with no pin still appears in the file with an empty version
    field, so a domain the map omits is a hole in the reading — a stale or
    half-written cache — not an unpinned domain: pin_read is False and
    raw_pin is None, never an assumed `inherit`."""
    dom = vhost["vhost"]
    pin_read = raw_pins is not None and dom in raw_pins
    raw_pin = raw_pins[dom] if pin_read else None
    # an account outside CageFS has no version: the Selector serves none of
    # its domains, and each is out of coverage for that (OUTSIDE_CAGEFS)
    outside = account_current is OUTSIDE_CAGEFS
    sel_cur = None if outside else isolated_versions.get(dom, account_current)
    fpm = bool(vhost.get("php_fpm"))
    target = None if outside else to_pkg(sel_cur)
    reported = vhost["version"]
    entry = effective_entry(record["domains"].get(dom, {}), raw_pin)
    if target == "inherit" and pin_read:
        target = native_target(entry, raw_pin, default_pkg)
    unroutable, served = None, False
    if fpm:
        inert = Why("fpm", "fpm")
    elif pin_read:
        # the box first: where the Selector serves nothing that is the
        # reason, whatever else holds for the domain. Judged on the box as
        # it is, whatever the mode of the pass makes of it below.
        box = coverage._replace(withdrawn=None)
        judged = target
        if coverage.withdrawn == RELEASING and from_pkg(raw_pin) is not None:
            # A release reads no Selector version (write_chunk), so its
            # target says nothing: the pin of ours standing is what it steps
            # aside from, and the question is whether that pin is served.
            judged = raw_pin
        gap = serving_gap(dom, raw_pin, entry, upstream, default_pkg,
                          coverage.handlers)
        if isinstance(gap, UnknownAbove) and not box.inert and not outside \
                and coverage.withdrawn != WITHDRAWING:
            # what the cascade brings it is unknown, and so is it: judged
            # as a pin nobody read, nothing written, claimed or handed back.
            # Found in review: judged out of coverage, the pin of ours on
            # an isolated website went back, and it ran the main domain's
            # 8.1 with the server-wide extensions. A withdrawal restores
            # what the domain arrived with whatever stands above it, and so
            # does a box, or an account, the Selector serves nothing on:
            # the box, or the account, decides that hand-back, not the
            # parent.
            return DomainReading(
                dom=dom, reported=reported, fpm=fpm,
                entry=effective_entry(record["domains"].get(dom, {}), None),
                pin_read=False, raw_pin=None, gateway=False,
                sel_cur=sel_cur, target=target, inert=gap, unroutable=None,
                served=False)
        inert = (box.inert or (OUTSIDE_CAGEFS if outside else None) or gap
                 or box.gap(reported, judged, default_pkg))
        if not inert:
            # Only once the domain is covered: a handler the Selector
            # cannot serve through is the older and larger reason to leave
            # it alone, and naming the web server's version support there
            # would send the admin after the wrong thing.
            #
            # The target and the pin ACTUALLY STANDING, never the resolved
            # default the coverage rule substitutes for `inherit`: the
            # default is cPanel's to route and a partial reading of the
            # table would otherwise hand back the whole fleet at once.
            unroutable = (box.route_gap(judged)
                          or box.route_gap(raw_pin))
            inert = unroutable
        # and only on what the Selector runs: a gateway value, a pin of
        # ours, or its own version. An admin's other version is served by
        # MultiPHP alone.
        served = not inert and (
            is_gateway(raw_pin, default_pkg) or raw_pin == target
            or (entry.get("owner") == "selector"
                and entry.get("version") == raw_pin))
        inert = coverage.withdrawn or inert
    else:
        inert = None  # nothing read, nothing judged
    return DomainReading(
        dom=dom, reported=reported, fpm=fpm,
        entry=entry,
        pin_read=pin_read, raw_pin=raw_pin,
        gateway=pin_read and is_gateway(raw_pin, default_pkg),
        sel_cur=sel_cur, target=target, inert=inert,
        unroutable=None if coverage.withdrawn else unroutable,
        served=served)


# Every verdict verdict_of returns, and nothing else — a test holds the two
# together. The drift telemetry counts by these names (clselectstatistics),
# so one missing there reads as zero across the fleet; --help explains each
# (VERDICT_LEGEND).
VERDICTS = (
    "out-of-coverage", "not-in-userdata", "owned-ok", "DRIFT(owned)",
    "owned-unrecorded", "UNEXPLAINED", "mirrored-ok", "mirrored-unrecorded",
    "stale-mirror", "selector (unmirrored)", "released", "unroutable",
)


def verdict_of(entry, raw_pin, pin_read, target, default_pkg, inert,
               unroutable=None, syncing=True):
    """State of one domain as (verdict, ownership) for the drift report.

    entry       its ownership record, or {} if it has none
    raw_pin     the pin in cPanel's store (`inherit` when it has none)
    pin_read    whether raw_pin was actually read, or is a fallback guess
    target      the pin the mirror would write for this domain
    default_pkg the MultiPHP system default
    inert       why the sync leaves the domain alone (domain_reading), or None
    syncing     whether selector-to-multiphp is on: a hand-back that stands
                reads differently once nothing will re-mirror it

    The verdicts, and what each one asserts:
      out-of-coverage       FPM, or a handler PHP Selector cannot serve
                            through: the sync does not act here
      released              the sync is off and the domain stands where we
                            handed it back to — the version it had before
                            syncing; nothing is pending
      owned-ok              a recorded MultiPHP pin, still standing
      DRIFT(owned)          a recorded MultiPHP pin that has since moved
      owned-unrecorded      an explicit foreign pin with no record, the
                            Selector's own version included — what the
                            next pass records as takeover-as-found
      UNEXPLAINED           the ledger says we wrote this pin and the store
                            contradicts it: the falsifiable failure signal
      mirrored-ok           the pin is the target, and the ledger says it is ours
      mirrored-unrecorded   the pin is the gateway's `inherit` of a native
                            account with nothing to prove it, or the target
                            with our claim on another version (a claim lost
                            between a write and its record), which the next
                            pass re-claims without a write
      stale-mirror          our pin still stands but the target moved past it:
                            the mirror write for the new version never landed
      unroutable            covered, and the web server has no handler for
                            the version the mirror would name: the pin
                            would take the domain off the Selector's one
                            version-agnostic handler onto a per-version
                            one that does not exist
      selector (unmirrored) a gateway value, the selector's to claim
      not-in-userdata       cPanel lists the domain, the pin map does not:
                            nothing can be judged and nothing is written

    A domain the pin map omits is unknown, not unpinned — the rule
    plan_mirror applies when it skips such a domain, so the report never
    contradicts what the next pass will do.
    """
    # `released` is ours too: the value we wrote on the way out. Without
    # it a domain released to the NAMED default reads as an admin's pin
    # once the default moves, which both contradicts the planner (it
    # re-mirrors) and inflates the owned-unrecorded bucket the baseline
    # and the drift telemetry rest on.
    #
    # Only a hand-back from what the Selector governed, though: one that
    # restored an admin's ea-php version, set while it was the default, is
    # the admin's once the default has moved (arrival_is_selectors), and
    # the planner records it so rather than re-mirroring it.
    ours = entry.get("owner") == "selector" \
        or (entry.get("reason") == "released"
            and entry.get("version") == raw_pin
            and arrival_is_selectors(entry.get("was"), default_pkg))
    gateway = is_gateway(raw_pin, default_pkg)
    if inert and not unroutable:
        # coverage suspends the sync for the domain; it does not transfer
        # the pin, so the ledger still says who owns it
        return "out-of-coverage", "%s (%s)" % (entry.get("owner") or
                                               "multiphp", inert)
    if not pin_read:
        # the planner skips this domain, so the report says why rather than
        # judging a pin nobody read
        return "not-in-userdata", entry.get("owner") or "?"
    if not syncing and entry.get("reason") == "released" \
            and entry.get("version") == raw_pin:
        # --disable handed the domain back and turned the sync off: the row
        # stands at the value it restored while the selector keeps moving.
        # Read as stale-mirror, this told the admin to run --reconcile,
        # which refuses while off. Nothing is pending — the domain stands
        # where it arrived, deliberately. With the sync ON the same row is
        # a pending re-mirror (a domain back from FPM) and reads as one
        # below.
        return "released", "multiphp (released)"
    if arrived_pin_stands(entry, raw_pin):
        # set in MultiPHP Manager, at the version the domain arrived with:
        # the next pass records it as MultiPHP's (plan_mirror), as without
        # the sync, whatever the Selector does meanwhile
        return "owned-unrecorded", "multiphp (unrecorded)"
    if entry.get("reason") in ("takeover", "takeover-as-found") \
            and not gateway:
        return ("owned-ok" if raw_pin == entry.get("version")
                else "DRIFT(owned)",
                "multiphp since %s" % (entry.get("since") or "?"))
    if ours and entry.get("version") != raw_pin and not gateway:
        if raw_pin != target:
            return "UNEXPLAINED", "?"
        if not unroutable:
            # the planner's agreement branch re-claims exactly this state:
            # reported as UNEXPLAINED, the daily snapshot raised the failure
            # signal for a domain the engine treats as healthy
            return "mirrored-unrecorded", "selector"
        # unroutable, the planner leaves it alone rather than re-claiming
        # it: it reads as below, like every domain with no handler
    if unroutable:
        # After the ownership verdicts, deliberately: an admin's pin stays
        # theirs to report as owned, and the reason column is what says
        # their domain is being served by nothing. Before the mirror
        # verdicts, because a pin that equals its target is NOT
        # mirrored-ok when the web server cannot serve it, and a gateway
        # value here is not an unrun mirror — it is one that will never
        # run while this version and this web server disagree.
        return "unroutable", "selector (%s)" % unroutable
    if raw_pin == target:  # including a native account, both `inherit`
        # ours only where the claim names this pin: on a gateway value the
        # stale claim above falls through to here, and read as mirrored-ok
        # it counted a claim the next pass has yet to make as healthy
        # (found by Bugbot)
        if ours and entry.get("version") == raw_pin:
            return "mirrored-ok", "selector"
        if from_pkg(raw_pin) is not None and not entry.get("restored"):
            # an alt-php no row of ours stands on: set in MultiPHP Manager,
            # which the next pass records as takeover-as-found (plan_mirror).
            # A restore's flagged row is the sync's own pin back from the
            # backup, which the next pass claims
            return "owned-unrecorded", "multiphp (unrecorded)"
        return "mirrored-unrecorded", "selector"
    if ours and entry.get("version") == raw_pin and not (
            gateway and entry.get("reason") in ("released", "step-aside")):
        return "stale-mirror", "selector"
    if gateway:
        # a hand-back's row on a gateway value too: one its document-root
        # group holds there reads as what it is, not as a stale mirror whose
        # legend sends the admin to a --mirror that changes nothing (found
        # in review)
        return "selector (unmirrored)", "selector"
    # what remains is an explicit pin that is not the target, not a gateway
    # value, not provably ours and not recorded — the state the planner
    # records as takeover-as-found, named the same way here. Calling it
    # UNEXPLAINED would drown the failure signal above in baseline
    # divergence: every legacy pin on a box no pass has run on is here.
    return "owned-unrecorded", "multiphp (unrecorded)"


def selector_claim(entry, target, now, arrived):
    """The ledger row that says a pin is ours.

    `arrived` carries no default on purpose. Three call sites in a row
    have shipped recording no predecessor at all — each one simply left
    the argument off, each was found by a CI failure rather than by
    review, and each cost a domain the version an admin had set. Every
    site that claims a pin has to say what that pin replaced, even when
    the honest answer is None.

    `was` is the pin the domain carried before our FIRST mirror, and it is
    what a hand-back restores. It is set once and then carried forward:
    a re-pin must not replace it with the mirror it is superseding, or the
    domain is eventually handed back to one of our own alt-php pins.

    `arrived` is the pin the domain ARRIVED with, named by the planner
    and never inferred here. After a missed echo the
    hook's mirror-confirm persists a row carrying the new target, so a
    first mirror and a re-pin leave the ledger in the same shape — neither
    ownership nor the recorded version can tell them apart, and guessing
    from either one recorded an alt-php of ours as the value to hand back
    to. That is an alt-php outside the cage: the exact failure the
    hand-back exists to prevent.

    The paths that claim a pin already equal to the target write nothing,
    and claim only a pin of ours: the planner's agreement branch re-claims
    a row of ours (an alt-php with none is MultiPHP's), and the event
    listener's mirror-confirm claims only our own write, its echo missed:
    its pending mark names what it replaced, and under a pass of ours
    still running (pass_running) it answers None and leaves the field to
    record_written, moments behind with the planner's answer.
    """
    row = {"owner": "selector", "version": target, "reason": "mirror",
           "since": since_of(entry, "selector", now)}
    was = entry.get("was")
    # `bare`, with `was` `inherit`: whether the domain had no phpversion
    # key (NoKey), or one set to `inherit` that cPanel's restore keeps. A
    # row from before the field has neither, read as no key
    # (step_aside_for_restore)
    bare = entry.get("bare")
    if entry.get("restored") and arrived == target \
            and from_pkg(arrived) is not None:
        # the sync's own pin, back from a backup over a domain a restore's
        # start handed back (step_aside_for_restore): what it arrived with
        # stays, or a --disable would leave this alt-php standing. A row
        # with none arrived on `inherit`, as far as anything can tell: the
        # start took its key for that (found in review: the backup's
        # alt-php became it)
        if was is None:
            was, bare = "inherit", True
    elif entry.get("reason") in ("released", "step-aside") \
            and arrived is not None and arrived != entry.get("version"):
        # The pin moved after the hand-back (a step-aside is one too): what
        # the domain carries now is what a later hand-back must restore,
        # and the row's older `was` is history. Found in review: an admin's
        # explicit default set while the sync was off went back to
        # `inherit` after a re-enable, and the domain followed the default.
        # A pin still at the released value keeps the row's `was` — what
        # we wrote is not always what the domain arrived with (an FPM
        # hand-back names the default).
        was, bare = arrived, isinstance(arrived, NoKey)
    if was is None:
        was, bare = arrived, isinstance(arrived, NoKey)
    if was is not None:
        row["was"] = was
        if was == "inherit" and bare is not None:
            row["bare"] = bool(bare)
    return row


def disowned(entry, raw_pin, now):
    """The ledger row a withdrawal leaves on a pin that needs no write.

    Where the value to restore is the one already standing — the version
    its document-root group carries without the sync (group_back), or a
    native account's `inherit` — there is nothing to write, but ownership
    still goes back: a withdrawal disowns every pin it decides about. Left
    claimed, no write could ever clear the row, so standing_pins would
    count it for ever and --withdraw could never come back clean.

    Both branches that can reach that state use this: the out-of-coverage
    one and PHP-FPM's, which has its own early exit and was missed the
    first time."""
    row = {"owner": "multiphp", "reason": "released",
           "version": raw_pin, "since": now}
    if entry.get("was") is not None:
        # what we WROTE is not always what the domain arrived with, so the
        # predecessor outlives the disowning exactly as record_released
        # carries it across a hand-back that did write
        row["was"] = entry["was"]
        if "bare" in entry:
            row["bare"] = entry["bare"]
    return row


def handback_target(entry, raw_pin, group_target):
    """The pin to write back for one domain, or None when there is nothing
    of ours to hand back.

    The mirror pin DESCRIBES what the Selector serves; it is not an
    instruction. Once the Selector no longer serves the domain the
    description has no referent, and left standing it becomes an
    instruction — cPanel serves that alt-php outside the user's CageFS,
    where it loads the bare package defaults instead of the user's
    Selector configuration (measured on a live box: 32 extensions against
    65, PDO among the missing). A stock ea-php is complete on its own; an
    alt-php deliberately is not, because its real configuration lives in
    the cage. So the domain goes back.

    Only a pin the ledger proves we wrote is withdrawn: an admin's own pin
    is theirs on the way out as much as on the way in. A `released` row is
    not proof HERE — the domain has already been handed back, so there is
    nothing left to withdraw. It is proof on the way back IN, which is how
    a hand-back survives a later change of the system default; see `ours`
    in plan_mirror.

    `group_target` is the value, decided for the whole document-root group
    by handback_by_group(); None there means the group keeps its pin.
    """
    if group_target is None:
        return None
    if entry.get("owner") == "selector" and entry.get("version") == raw_pin:
        return group_target
    return None


def handback_by_group(vhosts, readings, default_pkg, handlers, mode=None):
    """The pin each out-of-coverage domain goes back to, decided per
    document-root GROUP. Domains absent from the result keep their pin, and
    so do those of a group that has no one value to go back to (None).

    cPanel pins a whole group with one value, so the group has to decide
    together. Two consequences, both learned the hard way:

    A member the Selector still serves needs the mirror pin, and it wins.
    Withdrawing around it would take its pin with it, its next pass would
    put the pin straight back, and the pair would flap forever — an Apache
    rebuild every round, settling nowhere. Where the pin of ours must still
    go (PHP-FPM on a mate), settle_groups takes the whole group through the
    gateway, which serves that member as our pin did.

    Otherwise the group goes back to what its members would carry without
    the sync (group_back). PHP-FPM is what makes a mixed group ordinary: it
    is a per-domain toggle, so one member can leave coverage while the
    rest stay in it.

    mode: the coverage's `withdrawn` — None for a pass, RELEASING for a
    release, which steps aside for a PHP Selector change and must not move
    a site meanwhile, WITHDRAWING for a --disable (group_back)."""
    groups = {}
    for v in vhosts:
        root = v.get("documentroot")
        key = (v.get("account"), root) if root else (None, v["vhost"])
        groups.setdefault(key, []).append(v["vhost"])
    targets = {}
    for members in groups.values():
        rs = [readings[m] for m in members]
        if any(not r.pin_read or (not r.fpm and not r.inert) for r in rs):
            # Blocked by either: a member the Selector still serves, which
            # needs the mirror pin, or a member whose pin nobody read —
            # unknown is not unpinned, and cPanel's group write lands on it
            # regardless of why we left it alone. An FPM member is judged
            # as `inert` but its pin is no less unread for that.
            continue
        back = group_back(rs, default_pkg, handlers, mode)
        for m in members:
            targets[m] = back
    return targets


def group_back(rs, default_pkg, handlers, mode=None):
    """The pin a document-root group goes back to, from its members'
    readings (handback_by_group, settle_groups), or None when there is no
    one value to restore.

    A group has one .htaccess, so without the sync it serves one pin: the
    one value, among what each member would carry (what it arrived with
    where a pin of ours stands, its pin otherwise), that is not `inherit`.
    A member made later in the root, on `inherit`, serves that pin too —
    found in review: such a group went back to `inherit`, its admin's
    ea-php81 with it, and every pass then flipped it between that and the
    Selector's version. Values that disagree have no answer: a group still
    served is held, one out of coverage goes through the gateway. One with
    another's version on a member that is not ours is held. Nothing
    recorded (rows predating `was`) is `inherit` too.

    `inherit` and the default are not the same once the default moves:
    handing an explicitly pinned domain back as `inherit` made it follow
    the new default — an admin's ea-php83 serving 8.5 once the default
    moved, which is what the userland phpselector_domains tests catch. A
    named value stops being a gateway value when the default moves, so it
    could not be re-mirrored on its own; the `released` row record_released
    writes is what keeps it provably ours.

    An alt-php value is the Selector's own (arrival_is_selectors). Where a
    member is still served (DomainReading.served), the group goes through
    the gateway instead, which runs that member exactly as our pin did —
    measured: `inherit` serves what our pin serves, isolated websites
    included; and a value that would run it differently holds the group.
    The gateway is then the named default, not `inherit`: an explicit pin
    shields the group from a pin above it, as the alt-php did, where
    `inherit` would run it. Found in review: a release handed the tenant's
    own alt-php82 back to `inherit`, the site ran the admin's ea-php81 on
    the main domain above, and the pass ending the change left it there.
    With nothing served it goes back as it is: PHP-FPM or another handler
    keeps the version an admin set (found in review: a release moved such
    a pool to the default). A withdrawal restores every value as recorded.

    A value EasyApache no longer has (handlers, php.conf's table) is not
    restored: cPanel serves such domains the default. `inherit` takes the
    named default where a member runs PHP-FPM — cPanel refuses to build a
    pool for `inherit` — but only a default we have: a withdrawal runs
    under an unreadable one too, and naming nothing would set the domain's
    version to nothing; left `inherit`, cPanel refuses the write and the
    domain is reported as still standing. Non-strings are ledger
    corruption, not a pin, and degrade rather than raise out of a cPanel
    hook."""
    served = mode != WITHDRAWING and any(r.served for r in rs)
    values, shielded = set(), False
    for r in rs:
        if r.entry.get("owner") == "selector" \
                and r.entry.get("version") == r.raw_pin:
            value = r.entry.get("was")
        elif r.entry.get("reason") == "released" \
                and r.entry.get("version") == r.raw_pin \
                and r.entry.get("was") is not None:
            # a value a hand-back of ours left there (record_released),
            # standing as it was written: the member arrived with `was`
            # (found in review: read as a version of its own, it held its
            # group, and every --disable after a step-aside exited 2)
            value = r.entry.get("was")
        elif r.pin_read and r.raw_pin not in ("", "inherit") \
                and not is_gateway(r.raw_pin, default_pkg):
            # someone else's version: the group cannot go anywhere without
            # moving it, nor to it, which was never the sync's to restore
            return None
        else:
            value = r.raw_pin
        if not isinstance(value, str) or value in ("", "inherit"):
            continue
        if served and from_pkg(value) is not None:
            shielded = True
            continue
        if handlers is not None and value not in handlers:
            continue
        values.add(value)
    if len(values) > 1:
        if served:
            return None
        # nothing served in the group: a pin of ours there runs outside the
        # cage, and must go even where its origins disagree (rows of
        # different ages). The gateway is honest about restoring neither,
        # and no pass re-mirrors a group it does not serve.
        values = set()
    back = values.pop() if values else (
        default_pkg if shielded and default_pkg else "inherit")
    if served and not is_gateway(back, default_pkg):
        return None
    if back == "inherit" and any(r.fpm for r in rs) and default_pkg:
        back = default_pkg
    return back


def held_why(r, rs, others, stuck=False):
    """Why settle_groups holds one member of a document-root group: the
    mate whose pin the write would move, or the mates whose versions
    without the sync disagree. Named, so an admin can set the group to one
    version.

    stuck: the member is a pin of ours the hold leaves standing, which
    refuses every change of the account. A tenant can bring that about (a
    subdomain set to its own version, pointed at the folder of a domain the
    sync pins), so the reason names the step that frees the folder without
    changing what runs: `inherit`, not one version for both, which on the
    sync's version would make our pin an admin's (RESTATED) and leave the
    site on it after the change (found by the AI security scan)."""
    blocking = next((o for o in others if o.dom != r.dom), None)
    if blocking is not None:
        why = "shares its document root with %s (%s), which the write " \
              "would move" % (blocking.dom, blocking.raw_pin
                              if blocking.pin_read else "unread")
        if stuck and blocking.pin_read:
            why += ". To free it, set %s to inherit in MultiPHP Manager, " \
                   "so that PHP Selector serves the folder, or give %s a " \
                   "document root of its own" % (blocking.dom, blocking.dom)
        return Why(why, "docroot")
    if others:
        return Why("held with its document root's group", "docroot")
    return Why("shares its document root with %s, and without the sync they "
               "would carry different versions" % ", ".join(
                   "%s (%s)" % (o.dom, o.raw_pin) for o in rs
                   if o.dom != r.dom), "docroot")


def settle_groups(plan, releases, skips, vhosts, readings, default_pkg,
                  handlers, mode=None, carried=None):
    """Settle the plan's writes per document-root group: cPanel pins every
    domain sharing a document root together (get_impacted_domains), so a
    write planned for one moves the others whatever the plan says of them.
    Found in review: a subdomain made in the main domain's document root
    got the Selector's version, and the group write took the main domain
    off the ea-php81 its admin had set; and a member the Selector still
    serves kept the group's alt-php pin on a PHP-FPM member, pooled outside
    the cage.

    A group whose writes agree, and whose unwritten members already have
    that value, keeps them. Otherwise, where a pin of ours has to move (a
    member out of coverage still carries it, or a served member's names
    another version than its target) and nothing in the group is anyone
    else's or unread, the whole group goes back to what it would carry
    without the sync (group_back), which serves a member still served as
    our pin did. A member written there that is not ours goes in
    `carried`, with the pin it had: the write moved it, but the sync never
    owned it, and the callers record it as such (record_carried) — found
    in review, claimed as ours, it read as a stale mirror and a --disable
    could never hand it back. Anything else holds the group's writes: a
    write there would move a pin that is not ours to move.

    Returns the alt-php pins of ours a lasting hold leaves standing (not
    one over a mate nobody read, which may read next time), for a
    withdrawal to give up on (plan_mirror)."""
    groups = {}
    for v in vhosts:
        root = (v.get("documentroot") or "").rstrip("/")
        if root:
            groups.setdefault((v.get("account"), root), []).append(v["vhost"])
    planned = {d: t for t, doms in plan.items() for d in doms}
    held = set()

    def ours_standing(r):
        return r.pin_read and r.entry.get("owner") == "selector" \
            and r.entry.get("version") == r.raw_pin

    def must_move(r):
        if not ours_standing(r):
            return False
        if from_pkg(r.raw_pin) is None:
            # a step-aside of ours on a value the Selector serves the site
            # through: only a withdrawal restores what it arrived with
            # (found in review: never moved, it stood for good, and every
            # --disable exited 2)
            return mode == WITHDRAWING \
                and r.entry.get("reason") == "step-aside" \
                and r.entry.get("was") != r.raw_pin
        if r.fpm or r.inert:
            # out of coverage a pin of ours goes back, but one at what the
            # domain arrived with goes nowhere (disowned, nothing written):
            # found in review, counted as moving, it took the group through
            # the named default, and a daily pass moved a PHP-FPM pool
            return r.entry.get("was") != r.raw_pin
        return r.raw_pin != r.target

    for members in groups.values():
        if len(members) < 2:
            continue
        rs = [readings[m] for m in members]
        writes = {m: planned[m] for m in members if m in planned}
        values = set(writes.values())
        if len(values) <= 1 and all(
                r.dom in writes or (r.pin_read and (not values
                                                    or r.raw_pin in values))
                for r in rs) \
                and not any(must_move(r) and r.dom not in writes for r in rs):
            continue
        for m in writes:
            plan[writes[m]].remove(m)
            releases.discard(m)
        others = [r for r in rs if not r.pin_read
                  or not (r.gateway or ours_standing(r))]
        back = None
        if not others and any(must_move(r) for r in rs):
            back = group_back(rs, default_pkg, handlers, mode)
        if back is not None:
            for r in rs:
                if r.raw_pin != back:
                    plan.setdefault(back, []).append(r.dom)
                    if ours_standing(r):
                        releases.add(r.dom)
                    elif carried is not None:
                        carried[r.dom] = r.raw_pin
            continue
        # a mate nobody read may read next time; one that is someone
        # else's, or origins that disagree, will not
        lasting = all(o.pin_read for o in others)
        for r in rs:
            if r.dom in writes or must_move(r):
                skips.append((r.dom, held_why(r, rs, others,
                                             stuck=ours_standing(r))))
            if lasting and ours_standing(r) \
                    and from_pkg(r.raw_pin) is not None:
                held.add(r.dom)
    for target in [t for t, doms in plan.items() if not doms]:
        del plan[target]
    return held


def plan_mirror(vhosts, account_current, isolated_versions, default_pkg,
                record, raw_pins, coverage, releases=None,
                arrived=None, carried=None,
                release_targets=None,
                aliases=None, moved=None,
                ):
    """Plan a complete Selector -> MultiPHP mirror pass.

    vhosts            [{'vhost', 'version', 'php_fpm'}, ...] cPanel state
    account_current   selector account version ('8.2' or 'native')
    isolated_versions {domain: per-domain selector version}
    record            ownership record dict ({'domains': {...}}), mutated
                      in place with the non-write entries: FPM marks,
                      agreement claims, takeover-as-found
    raw_pins          {domain: raw userdata phpversion} or None — see
                      domain_reading(), which owns the reading rules
    coverage          the box's Coverage: a domain the Selector cannot
                      serve is skipped, and nothing is recorded for it.
                      Withdrawn (Coverage.withdrawn), every domain is, and
                      the plan can only hand back — the disable's pass
    releases          out: domains this plan is HANDING BACK rather than
                      mirroring. The write is the same call either way;
                      only what the caller records afterwards differs.
    arrived           out: {domain: the pin it ARRIVED with}, filled only
                      where nothing of ours already stands. A re-pin
                      replaces our own mirror and reports nothing — after
                      a missed echo the ledger row looks identical either
                      way, so the caller cannot work this out for itself.
    carried           out: {domain: its pin before}, for a domain written
                      only because it shares a document root with one the
                      plan hands back (settle_groups): neither a claim nor
                      a hand-back of ours (record_carried).
    release_targets   a release's reading of the account's Selector
                      versions, (account-current, {isolated domain:
                      version}), where write_chunk took one
                      (keep_what_a_release_moves)
    aliases           {an addon's subdomain name: the addon's}, from
                      /etc/userdatadomains: a row kept under the first
                      moves to the second (carry_addon_rows)
    moved             out: [(old name, new name)] for each row so moved,
                      for the caller to log once it has saved them

    Returns (plan, skips, record) where plan is {pin_value: [domains]}
    and skips is [(domain, why)]. The record is the POSITIVE LEDGER: the
    caller writes a `selector` entry for every planned pin that succeeds;
    this planner writes the non-write entries (re-claims of agreeing pins
    of ours, FPM marks, takeover-as-found). The invariant: a write is planned only for
    gateway values or pins the ledger proves we wrote — any other explicit
    pin is takeover-as-found, recorded and never touched.
    """
    plan, skips = {}, []
    now = time.strftime("%F %T")
    carried_rows = carry_addon_rows(record["domains"],
                                    {v["vhost"] for v in vhosts}, aliases)
    if moved is not None:
        moved.extend(carried_rows)
    # A pin set in MultiPHP Manager is MultiPHP's, also at the Selector's
    # version (arrived_pin_stands): a row of ours on one goes before
    # anything below reads the ledger, so nothing takes it for the sync's.
    # No write: it stands as it is (migrate_arrived_pins does the same at
    # an upgrade).
    for v in vhosts:
        dom = v["vhost"]
        pin = (raw_pins or {}).get(dom)
        if dom in record["domains"] and arrived_pin_stands(
                effective_entry(record["domains"][dom], pin), pin):
            record["domains"][dom] = the_domains_own(pin, now)
            skips.append((dom, "%s, set in MultiPHP Manager: MultiPHP's, "
                               "as without the sync" % pin))
    # read every domain first: a hand-back is decided per document-root
    # group, so a domain's verdict depends on its group-mates' readings.
    # Entries are per domain and independent, so reading ahead is safe.
    upstream = upstream_pins(vhosts, nosync_pins(raw_pins, record, default_pkg,
                                                 coverage.handlers))
    readings = {v["vhost"]: domain_reading(
        v, account_current, isolated_versions, default_pkg, record,
        raw_pins, coverage, upstream) for v in vhosts}
    for dom, r in readings.items():
        if r.inert is OUTSIDE_CAGEFS and r.entry.get("restored") \
                and from_pkg(r.raw_pin) is not None \
                and r.entry.get("held") == r.raw_pin:
            # the sync's own pin, back from the backup, on an account the
            # restore took out of CageFS (step_aside_for_restore): the
            # Selector cannot say so there, the pin the sync held as the
            # restore began does. Claimed, and recorded, so it goes back
            # below as every pin of ours on such an account, and a
            # hand-back that does not land keeps the proof for the next pass
            record["domains"][dom] = selector_claim(
                r.entry, r.raw_pin, now, arrived=r.raw_pin)
            readings[dom] = r._replace(entry=record["domains"][dom])
    handbacks = handback_by_group(vhosts, readings, default_pkg,
                                  coverage.handlers, mode=coverage.withdrawn)
    # A release leaves a pin the Selector serves that needs no write as it
    # is, row and all: it already follows the Selector's switch, and the
    # claim is what the pass ending the change re-pins from. A withdrawal
    # disowns it, and so does every pass where the Selector does not serve
    # it (below).
    disowning = coverage.withdrawn == WITHDRAWING
    for v in vhosts:
        r = readings[v["vhost"]]
        dom, entry = r.dom, r.entry
        if r.fpm:
            # FPM takes the domain out of Selector's reach, so our pin stops
            # describing anything and starts deciding what cPanel pools —
            # which is how enabling FPM, a one-click cPanel operation, came
            # to build an alt-php pool with none of the user's extensions.
            back = handback_target(entry, r.raw_pin, handbacks.get(dom))
            if back and back != r.raw_pin:
                plan.setdefault(back, []).append(dom)
                if releases is not None:
                    releases.add(dom)
                # the ledger is NOT touched here: the row is the proof that
                # the standing pin is ours, and it has to outlive a write
                # that does not land, or the pin is stranded unprovable.
                # record_released drops it once the write has landed.
                continue
            # nothing of ours here: the entry only marks the exit, so a
            # domain returning from FPM is provable rather than freezing as
            # takeover-as-found the first time the selector version moves.
            #
            # Not on a withdrawal, which decides nothing about pins it does
            # not hold: a marker left by one on a box that never mirrored
            # would make the ledger non-empty, and write_baseline refuses
            # the pre-sync picture once anything is recorded — `--disable`
            # on a fresh box would cost it its baseline for good.
            if back is not None and (disowning
                                     or from_pkg(r.raw_pin) is not None):
                # a pin of ours already at what it would go back to: the
                # alt-php its document-root group carries without the sync,
                # which PHP-FPM keeps running. Nothing to write, and nothing
                # of ours left to hand back, so the row goes back now (see
                # disowned):
                # left claimed, a release counted it as standing and moved
                # the pool to the default (found in review). The released
                # row still proves it ours if the domain comes back.
                record["domains"][dom] = disowned(entry, r.raw_pin, now)
            elif coverage.withdrawn is None:
                record["domains"].setdefault(dom, {
                    "owner": "multiphp", "reason": "fpm",
                    "version": r.reported, "since": now,
                })
            skips.append((dom, "fpm — out of coverage"))
            continue
        if not r.pin_read:
            # unknown is not unpinned (domain_reading): with no pin actually
            # read, assuming `inherit` would plan a write over whatever is
            # really there, so nothing is written and nothing is claimed.
            # Nor where what stands above it is unknown (r.inert says).
            skips.append((dom, r.inert or Why(
                "no pin on record — nothing to judge", "unknown")))
            continue
        if r.inert and coverage.withdrawn is None and r.gateway \
                and r.inert is not OUTSIDE_CAGEFS \
                and entry.get("reason") == "step-aside" \
                and entry.get("owner") == "selector" \
                and entry.get("version") == r.raw_pin \
                and not coverage.gap(r.reported, r.raw_pin, default_pkg):
            # a step-aside stays on the value the Selector serves the site
            # through where only the version it would follow cannot be
            # pinned (a handler of its own, no route): written back to what
            # it arrived with, the site went from the old version to the
            # new one, then to the old one with the server-wide extensions
            # (found in review). A withdrawal gives it back, and so does a
            # pass the gateway no longer serves the site through, as on an
            # account outside CageFS, which it serves through nothing
            skips.append((dom, "%s — stays on %s, which the Selector serves "
                               "it through" % (r.inert, r.raw_pin)))
            continue
        if r.inert:
            # a pin of ours goes back first: out of coverage it no longer
            # names what the Selector serves, and Apache would run that
            # alt-php outside the cage, without the user's configuration
            # `back == r.raw_pin` is the native account, mirrored TO
            # `inherit`: there is nothing to write, and nothing to record
            # either — the next pass reads the same state and skips again.
            back = handback_target(entry, r.raw_pin, handbacks.get(dom))
            if back and back != r.raw_pin:
                plan.setdefault(back, []).append(dom)
                if releases is not None:
                    releases.add(dom)
                continue
            if back is not None and (disowning or (
                    not r.served and from_pkg(r.raw_pin) is not None)):
                # nothing to write, but ownership still goes back (see
                # disowned): on a withdrawal, and for an alt-php version
                # the Selector does not serve, so a release has nothing of
                # ours there to step aside from (found in review: one moved
                # the domain's own alt-php82 on lsapi to the default's cgi). The
                # released row is still proof the pin was ours, so the
                # domain is re-mirrored if it comes back into coverage.
                # `back is not None` is what says the row is ours and its
                # group was decided: handback_target already applied both
                # tests, and a group it could not decide keeps its claim as
                # the retry proof.
                record["domains"][dom] = disowned(entry, r.raw_pin, now)
                skips.append((dom, "%s — %salready the version it arrived "
                                   "with" % (r.inert, "" if disowning
                                             else "out of coverage, ")))
                continue
            # coverage suspends the sync for the domain and decides nothing
            # about its pin: an entry recorded here would outlive the
            # handler change that brings the domain back, exactly as an
            # FPM-time takeover would (handle_event ignores such domains
            # for the same reason). A withdrawal is the exception above:
            # it is deliberate and permanent, not a handler configuration
            # that may come back.
            #
            # Residual, accepted, and the FPM skip's too: cPanel pins every
            # domain sharing a document root together, so a covered
            # group-mate's write moves this pin as well. It needs two
            # domains in one docroot whose targets sit on different
            # handlers — which the group's single pin cannot express in
            # the first place.
            skips.append((dom, "%s — %s" % (
                r.inert,
                "the web server cannot serve it" if r.unroutable
                else "nothing of ours to hand back" if coverage.withdrawn
                else "out of coverage")))
            continue
        # A takeover stands only while its pin does. Once the pin reads back
        # as a gateway value the domain has been handed back, and it rejoins
        # here rather than waiting for the event that says so: with the event
        # side off, or one event missed, the entry would otherwise exclude
        # the domain from the sync permanently.
        if entry.get("owner") == "multiphp" and \
                entry.get("reason") in ("takeover", "takeover-as-found"):
            if not r.gateway:
                # the pin as read, not entry["version"]: an out-of-band write
                # leaves the record stale, and every skip reason here names
                # what is actually on the box (--check reports the drift)
                skips.append((dom, "multiphp-owned @ %s" % r.raw_pin))
                continue
            # the entry goes now that the hand-back is decided, not when the
            # re-pin below is claimed: if the write lands and the claim does
            # not, a takeover left standing over a non-gateway pin skips the
            # domain for good. The event handler clears it the same way.
            record["domains"].pop(dom, None)
            entry = {}
        if entry.get("reason") == "fpm":
            # back in coverage, and a mark that exists only because of FPM
            # goes with it: left standing, record_written would read it as
            # an admin's pin arriving mid-call and refuse to claim our own
            # write, and the next Selector change would freeze the domain
            # as takeover-as-found
            record["domains"].pop(dom, None)
            entry = {}
        # ours either way: a pin we mirrored, or the value we wrote on the
        # way out. The second is how a hand-back survives the system
        # default moving out from under the version it had to name — but
        # only a hand-back from what the Selector governed: one that
        # restored an admin's ea-php version, set while it was the
        # default, is the admin's now (arrival_is_selectors), and falls
        # to the takeover-as-found below.
        ours = entry.get("owner") == "selector" \
            or (entry.get("reason") == "released"
                and arrival_is_selectors(entry.get("was"), default_pkg,
                                         coverage.handlers))
        if r.raw_pin == r.target:
            # agreement — (re)claim in the ledger, no API write: a pin of
            # ours, or the gateway's `inherit` on a native account.
            #
            # An alt-php pin with no row of ours is one set in MultiPHP
            # Manager (before the sync, by a restore or a transfer, or since
            # with the listener off), and MultiPHP's, as without the sync:
            # served with the Selector's settings only while the two agree,
            # it stays on its version when the Selector moves (found in
            # review: taken for the sync's own, it followed every later
            # Selector change, and with nothing below it, beside an admin's
            # other version in its document root, it held every change of
            # the account). Decided 2026-10-12.
            #
            # The question is whether the row is ours, not whether there is
            # one. An FPM exit leaves a row that only marks the exit, and
            # the takeover check above passes it through: it is not a claim,
            # nothing of ours ever stood on it. Where the row IS ours it
            # already carries its own predecessor — or carries none on
            # purpose, because mirror-confirm under a running pass cannot
            # tell an admin's pin from our own mirror, and our own mirror
            # must never become a hand-back target (an alt-php outside the
            # cage is the failure the hand-back exists to prevent).
            #
            # A released row is ours only while it still stands at the value
            # it released: one whose pin moved since is an admin's pin
            # arriving now, and the claim of `inherit` takes it as the new
            # predecessor (selector_claim). Except a restore's flagged row
            # (step_aside_for_restore): the pin is the sync's own, back from
            # the backup, and the claim keeps what the domain arrived with.
            standing_ours = entry.get("owner") == "selector" or (
                entry.get("reason") == "released"
                and entry.get("version") == r.raw_pin)
            if not standing_ours and not entry.get("restored") \
                    and from_pkg(r.raw_pin) is not None:
                record["domains"][dom] = {
                    "owner": "multiphp", "reason": "takeover-as-found",
                    "version": r.raw_pin, "since": now,
                }
                skips.append((dom, "takeover-as-found @ %s, the PHP "
                                   "Selector's version, set in MultiPHP "
                                   "Manager" % r.raw_pin))
                continue
            record["domains"][dom] = selector_claim(
                entry, r.target, now,
                arrived=None if standing_ours else r.raw_pin)
            skips.append((dom, "already %s" % r.raw_pin))
            continue
        proven = ours and entry.get("version") == r.raw_pin
        if r.gateway or proven:
            plan.setdefault(r.target, []).append(dom)
            if arrived is not None and not proven:
                # nothing of ours stands here, so the pin IS what the
                # domain arrived with. A re-pin (`proven`) replaces our own
                # mirror and has no predecessor to offer; after a missed
                # echo the two are indistinguishable from the ledger row
                # alone, which is why the caller is told rather than
                # left to infer.
                arrived[dom] = r.raw_pin
            elif arrived is not None and entry.get("was") is not None \
                    and entry["was"] != record["domains"].get(dom, {}).get("was"):
                # Except a re-pin over a pin of ours whose claim was lost
                # (the pass died between its write and its claim): what the
                # domain arrived with is then in the dead pass's mark,
                # where effective_entry found it, and the claim is built
                # from the raw row, which lacks it — or, on a row a
                # hand-back left, still carries the older value that
                # hand-back restored. Found in review: left unnamed it was
                # dropped, and the withdrawal handed an explicit default
                # back as `inherit`. Only a mark whose write landed is read
                # that way, so a stale one never outlives a pin an admin
                # set since.
                arrived[dom] = arrival_of(entry["was"], entry.get("bare"))
            continue
        # an explicit pin we cannot prove we wrote — never overwrite
        record["domains"][dom] = {
            "owner": "multiphp", "reason": "takeover-as-found",
            "version": r.raw_pin, "since": now,
        }
        # display only: the ledger's own reason field ("takeover-as-found")
        # is what other code tests, never this message. It was briefly
        # load-bearing — the fleet pass used to parse it back to decide a
        # snapshot-planned pass had reached a foreign verdict and must not
        # persist its planning — but that pass now plans from a reading
        # taken fresh per chunk, so there is nothing to re-derive.
        skips.append((dom, "takeover-as-found @ %s" % r.raw_pin))
    held = settle_groups(plan, releases if releases is not None else set(),
                         skips, vhosts, readings, default_pkg,
                         coverage.handlers, mode=coverage.withdrawn,
                         carried=carried)
    if coverage.withdrawn is None:
        # a release and a withdrawal only hand back, and no gateway value
        # reaches a site as anything but the Selector's
        settle_nesting(plan, releases if releases is not None else set(),
                       skips, vhosts, readings, default_pkg, coverage.handlers,
                       carried=carried)
        # the pass after a restore has made the first claim its flags are
        # for (step_aside_for_restore): one left on a row it did not claim
        # (PHP-FPM, out of coverage, held) would decide a claim long after
        # (found in review)
        for row in record["domains"].values():
            row.pop("restored", None)
            row.pop("held", None)
    if coverage.withdrawn == RELEASING:
        keep_what_a_release_moves(
            plan, releases if releases is not None else set(), skips, vhosts,
            readings, default_pkg, release_targets, carried=carried)
    if disowning:
        # a pin of ours the group holds cannot go back without moving a pin
        # that is not ours: the withdrawal gives it up, as named in its
        # skip line, or the hand-back could never complete (found in review:
        # --disable left `withdrawing` standing for good)
        for dom in held:
            record["domains"][dom] = disowned(readings[dom].entry,
                                              readings[dom].raw_pin, now)
            skips.append((dom, "left standing as MultiPHP's"))
    return plan, skips, record


def vhosts_by_account(vhosts):
    """{account: [its vhosts]}, in the listing's order."""
    by_account = {}
    for v in vhosts:
        by_account.setdefault(v.get("account"), []).append(v)
    return by_account


def document_root_groups(vhosts):
    """({domain: (account, document root)}, {(account, root): [domains]}),
    the roots without a trailing slash."""
    roots, groups = {}, {}
    for v in vhosts:
        root = (v.get("documentroot") or "").rstrip("/")
        if root:
            roots[v["vhost"]] = (v.get("account"), root)
            groups.setdefault((v.get("account"), root), []).append(v["vhost"])
    return roots, groups


def pin_source(dom, pins, roots, groups):
    """The domain whose pin `dom` runs through Apache's .htaccess cascade:
    itself where its own pin is explicit, else the nearest one above it
    with an explicit pin, a mate in its own document root first; None with
    none (it runs the default). A pin on the way that is unknown (None in
    `pins`) ends the walk there: that domain is the source, of an unknown
    pin."""
    if pins.get(dom) != "inherit":
        return dom
    account, path = roots[dom]
    while path:
        for mate in sorted(groups.get((account, path), ())):
            if mate != dom and pins.get(mate) != "inherit":
                return mate
        path = path.rpartition("/")[0]
    return None


def runs_on(dom, pins, roots, groups):
    """What `dom` runs on through Apache's .htaccess cascade (pin_source's
    pin): `inherit`, the default, with no explicit pin above it; None where
    the pin is unknown."""
    source = pin_source(dom, pins, roots, groups)
    return "inherit" if source is None else pins.get(source)


def runs_alike(was, now, own, target, default_pkg):
    """Whether a site runs the same on `was` as on `now` (runs_on): the same
    value, or values PHP Selector serves it through both times — a gateway
    value, its own pin of ours (`own`), or its own version (`target`, None
    when that is unknown). Unknown is never alike, unknown both times
    included (found in review: a release handed a pin back over a site
    nobody read, and the sites below it moved)."""
    if was is None or now is None:
        return False
    if was == now:
        return True

    def selectors(value):
        return is_gateway(value, default_pkg) or value == own \
            or (target is not None and value == target)
    return selectors(was) and selectors(now)


def settle_nesting(plan, releases, skips, vhosts, readings, default_pkg,
                   handlers, carried=None):
    """Hold, or hand back, a pin of ours that would reach a site running
    another version: a site on `inherit` runs the nearest explicit pin
    above it, one in its own document root or else in the nearest one
    holding it (Apache's .htaccess cascade). order_writes puts a site's own
    pin first, which is enough only where it gets one. Found in review:
    where it could not (its version without a php.conf row, on another
    handler, one the web server cannot route), the main domain's pin of
    ours reached the isolated website inside its document root for good,
    and the website ran the account's 8.1 with the server-wide extensions
    instead of its own 8.2.

    So after the plan (the writes that will land: hold_unservable drops
    the others), an alt-php pin of ours is the nearest pin only to sites
    that run that version through the Selector anyway; a site whose pin
    nobody read counts as one that does not, and an unread pin shields
    nothing. Otherwise its document-root group keeps what it has, and a pin
    of ours standing there goes back (group_back), which serves the group
    as the pin did. A gateway value reaches a site as the Selector's, and
    a pin set in MultiPHP Manager, the Selector's own version included
    (arrived_pin_stands), as it would without the sync, so neither is
    judged (found in review: judged, such a pin on the main domain went
    back, and the isolated website below it went from 8.2 to 7.4).
    Repeated until it holds: a pin held lets one further up reach the
    site."""
    roots, groups = document_root_groups(vhosts)

    def nearest(dom, after):
        """The domain whose explicit pin `dom` runs on `inherit`, or None."""
        account, path = roots[dom]
        while path:
            for mate in groups.get((account, path), ()):
                if mate != dom and after.get(mate) not in (None, "inherit"):
                    return mate
            path = path.rpartition("/")[0]
        return None

    settled = set()
    while True:
        planned = {d: t for t, doms in plan.items() for d in doms
                   if t == "inherit" or (handlers is not None and t in handlers)}
        after = {d: planned.get(d, r.raw_pin if r.pin_read else None)
                 for d, r in readings.items()}
        held = {}
        for n_dom in sorted(roots):
            if after.get(n_dom) not in (None, "inherit") \
                    or n_dom not in readings:
                continue
            p_dom = nearest(n_dom, after)
            if p_dom is None or roots[p_dom] in held or roots[p_dom] in settled:
                continue
            value, p = after[p_dom], readings[p_dom]
            ours = p_dom not in releases and p_dom not in (carried or {}) and (
                p_dom in planned or (p.entry.get("owner") == "selector"
                                     and p.entry.get("version") == p.raw_pin
                                     and p.entry.get("was") != p.raw_pin))
            n = readings[n_dom]
            if not ours or from_pkg(value) is None or (
                    n.pin_read and n.target == value):
                continue
            held[roots[p_dom]] = "its pin %s would reach %s, which runs %s" % (
                value, n_dom, (from_pkg(n.target) or n.target) if n.pin_read
                else "a pin nobody read")
        if not held:
            break
        for group, why in sorted(held.items()):
            settled.add(group)
            members = groups[group]
            for target in list(plan):
                for dom in [d for d in plan[target] if d in members]:
                    plan[target].remove(dom)
                    releases.discard(dom)
                    if carried is not None:
                        carried.pop(dom, None)
            rs = [readings[m] for m in members]
            ours = [r for r in rs if r.pin_read
                    and r.entry.get("owner") == "selector"
                    and r.entry.get("version") == r.raw_pin
                    and r.entry.get("was") != r.raw_pin
                    and from_pkg(r.raw_pin) is not None]
            others = [r for r in rs if not r.pin_read
                      or not (r.gateway or r in ours)]
            back = group_back(rs, default_pkg, handlers) \
                if ours and not others else None
            if back is not None:
                for r in rs:
                    if r.raw_pin != back:
                        plan.setdefault(back, []).append(r.dom)
                        if r in ours:
                            releases.add(r.dom)
                        elif carried is not None:
                            carried[r.dom] = r.raw_pin
                why = "handed back: " + why
            skips.extend((m, why) for m in members)
    for target in [t for t, doms in plan.items() if not doms]:
        del plan[target]


def the_domains_own(raw_pin, now):
    """The row of a pin set in MultiPHP Manager that a row of ours stood
    on (arrived_pin_stands): the domain's own as found (takeover-as-found),
    never written over again, as without the sync. Its pin rejoins the
    sync only as a gateway value, as any takeover's does."""
    return {"owner": "multiphp", "reason": "takeover-as-found",
            "version": raw_pin, "since": now}


def keep_what_a_release_moves(plan, releases, skips, vhosts, readings,
                              default_pkg, targets, carried=None):
    """Take out of a release each document-root group whose hand-back
    would change what a site runs before PHP Selector switches. A site on
    `inherit` runs the nearest explicit pin above it (Apache's .htaccess
    cascade), so a hand-back changes what runs below it too. Found in
    review: a pin the domain arrived with went back to the gateway, and
    the isolated website below the main domain went from the main domain's
    8.2 to its own 8.0 (such a pin is MultiPHP's: arrived_pin_stands). A
    pin the sync wrote is held the same way, and that stops the change (in
    a box where settle_nesting has run there is none).

    Judged per site: what it runs before (its own pin, or the cascade) and
    after the plan. A gateway value, and a site's own pin of ours, run as
    the Selector's; an alt-php the cascade brings runs as the Selector's
    only where it is the site's own version, which is what `targets`, the
    account's Selector versions, tells (write_chunk reads them where a site
    on `inherit` runs an alt-php; None: unknown, so such a change is
    held). Repeated until it holds, like settle_nesting."""
    roots, groups = document_root_groups(vhosts)
    before = {d: r.raw_pin if r.pin_read else None
              for d, r in readings.items()}

    def same(dom, was, now):
        r = readings[dom]
        # its own pin of ours is its own version, needing no reading
        own = before.get(dom) if r.pin_read \
            and r.entry.get("owner") == "selector" \
            and r.entry.get("version") == r.raw_pin else None
        target = None
        if targets is not None and targets[0] is not None:
            target = to_pkg(targets[1].get(dom, targets[0]))
        return runs_alike(was, now, own, target or own, default_pkg)

    while True:
        planned = {d: t for t, doms in plan.items() for d in doms}
        after = dict(before, **planned)
        held = {}
        for dom in sorted(roots):
            if dom not in readings or after.get(dom) != "inherit":
                continue
            if same(dom, runs_on(dom, before, roots, groups),
                    runs_on(dom, after, roots, groups)):
                continue
            account, path = roots[dom]
            while path and (account, path) not in held:
                moved = [m for m in groups.get((account, path), ())
                         if m in planned]
                if moved:
                    held[(account, path)] = Why(
                        "kept: going back, it would change what %s runs "
                        "(%s, then %s)"
                        % (dom, runs_on(dom, before, roots, groups) or "unread",
                           runs_on(dom, after, roots, groups) or "unread"),
                        "cascade")
                    break
                path = path.rpartition("/")[0]
        if not held:
            break
        for group, why in sorted(held.items()):
            for target in list(plan):
                for dom in [d for d in plan[target] if d in groups[group]]:
                    plan[target].remove(dom)
                    releases.discard(dom)
                    if carried is not None:
                        carried.pop(dom, None)
            skips.extend((m, why) for m in groups[group])
    for target in [t for t, doms in plan.items() if not doms]:
        del plan[target]


def inherits_an_alt_php(vhosts, raw_pins):
    """Whether a site on `inherit` runs an alt-php through the cascade: the
    one case a release reads the Selector for (keep_what_a_release_moves)."""
    roots, groups = {}, {}
    for v in vhosts:
        root = (v.get("documentroot") or "").rstrip("/")
        if root:
            roots[v["vhost"]] = (v.get("account"), root)
            groups.setdefault((v.get("account"), root), []).append(v["vhost"])
    for dom, (account, path) in roots.items():
        if (raw_pins or {}).get(dom) != "inherit":
            continue
        while path:
            pins = [(raw_pins or {}).get(m) for m in sorted(groups[(account,
                                                                   path)])
                    if m != dom and (raw_pins or {}).get(m) != "inherit"] \
                if (account, path) in groups else []
            if pins:
                if from_pkg(pins[0]) is not None:
                    return True
                break
            path = path.rpartition("/")[0]
    return False


# --------------------------------------------------------------------------
# I/O layer
# --------------------------------------------------------------------------

def log(line):
    # event payloads reach these lines, and a newline in a domain name or
    # actor would forge log entries in the record the drift analysis rests on
    line = str(line).replace("\r", " ").replace("\n", " ")
    try:
        fd = os.open(LOG_PATH, os.O_WRONLY | os.O_APPEND | os.O_CREAT,
                     STATE_MODE)
        # UTF-8 regardless of locale: cPanel's reasons are not ASCII, and
        # a root shell's LANG must not turn a log line into the exception
        # that aborts the pass between a write and its ledger entry
        with os.fdopen(fd, "a", encoding="utf-8", errors="replace") as f:
            f.write("%s %s\n" % (time.strftime("%F %T"), line))
    except (OSError, ValueError):
        pass


# The daily report's raw material (CLOS-7904; multiphp_sync_report): one
# line per failure, where the sync meets it. A day's file stops growing at
# REPORTS_DAY_CAP, and a line never reaches REPORT_LINE_MAX, so a single
# O_APPEND write keeps it whole with no lock.
REPORTS_DAY_CAP = 1 << 20
REPORT_LINE_MAX = 4096
# a cPanel hook run longer than this is recorded: cPanel holds the admin's
# or the tenant's request open for all of it
SLOW_HOOK = 2.0
# how much of one string a record keeps: a traceback's end, any other's
# start
REPORT_TEXT_MAX = 1500
# how many days of records are kept, and the files they are (a day's
# records, its cap mark, the events it sent)
REPORTS_KEEP_DAYS = 7
REPORT_DAY_FILE = re.compile(r"^(?:(\d{4}-\d{2}-\d{2})\.(?:jsonl|capped)"
                             r"|sent-(\d{4}-\d{2}-\d{2})\.json)\Z")
# the part of a word a cut at either end leaves (remember)
CUT_TAIL = re.compile(r"[^\s'\"(),;]*\Z")
CUT_HEAD = re.compile(r"\A[^\s'\"(),;]*")
# the failures nothing repeats at will. Any other kind stops at half the
# day's cap: a tenant can loop the door into a refusal, and must not crowd
# these out
ALERT_KINDS = ("crash", "write-failed", "handback-failed")


def reports_dir():
    """Where remember() writes: inside the state directory, so a sandbox and
    a box's removal take it along."""
    return os.path.join(STATE_DIR, "_reports")


def prune_reports(now=None):
    """Drop the day files of _reports/ older than REPORTS_KEEP_DAYS."""
    now = time.time() if now is None else now
    oldest = time.strftime("%Y-%m-%d", time.localtime(
        now - REPORTS_KEEP_DAYS * 86400))
    try:
        names = os.listdir(reports_dir())
    except OSError:
        return
    for name in names:
        found = REPORT_DAY_FILE.match(name)
        if found and (found.group(1) or found.group(2)) < oldest:
            with contextlib.suppress(OSError):
                os.unlink(os.path.join(reports_dir(), name))


def remember(kind, code, **detail):
    """Note one failure for the daily report: what went wrong (`kind`), why
    (a short `code`), and what the sync knew then (`detail`). The detail
    may name domains and accounts: it stays on this server, and the report
    scrubs whatever it sends.

    Called on failure branches, and once per cPanel call that writes, which
    restarts Apache: a path that works costs nothing more. Never raises,
    prints or blocks: a record that cannot be written is dropped, the
    failure being in the log already. Nothing is made where the sync has
    no state directory. (Not `record`: that names a ledger record all over
    this module.)"""
    try:
        fitted = {}
        for key, value in detail.items():
            if isinstance(value, str) and len(value) > REPORT_TEXT_MAX:
                # without the part of a word the cut left: what was left of
                # a domain has no TLD for the report's Scrubber to know it
                # by (found in the final review)
                value = ("…" + CUT_HEAD.sub("", value[-REPORT_TEXT_MAX:])
                         if key == "tb"
                         else CUT_TAIL.sub("", value[:REPORT_TEXT_MAX]) + "…")
            fitted[key] = value
        stamp = int(time.time())
        line = json.dumps({"t": stamp, "kind": kind, "code": str(code),
                           "detail": fitted}, sort_keys=True, default=str)
        if len(line.encode("utf-8", "replace")) >= REPORT_LINE_MAX:
            line = json.dumps({"t": stamp, "kind": kind,
                               "code": str(code)[:200],
                               "detail": {"truncated": True}}, sort_keys=True)
        directory = reports_dir()
        if not os.path.isdir(directory):
            if not os.path.isdir(STATE_DIR):
                return
            try:
                os.mkdir(directory, 0o700)
            except FileExistsError:
                pass
        day = time.strftime("%Y-%m-%d")
        fd = os.open(os.path.join(directory, day + ".jsonl"),
                     os.O_WRONLY | os.O_APPEND | os.O_CREAT, STATE_MODE)
        try:
            if not os.fstat(fd).st_size:
                # the day's first record: the days past keeping go, as
                # the report drops them, which does not run while the
                # sync is off (found in the final review)
                prune_reports()
            cap = REPORTS_DAY_CAP if kind in ALERT_KINDS \
                else REPORTS_DAY_CAP // 2
            if os.fstat(fd).st_size >= cap:
                # once a day: the report says the day was cut short
                try:
                    os.close(os.open(os.path.join(directory, day + ".capped"),
                                     os.O_WRONLY | os.O_CREAT | os.O_EXCL,
                                     STATE_MODE))
                except OSError:
                    pass
                return
            os.write(fd, (line + "\n").encode("utf-8", "replace"))
        finally:
            os.close(fd)
    except Exception:  # pylint: disable=broad-except
        pass


# the inputs this process has already recorded as unread (unreadable)
_unread = set()
# set while reads are no pass's (not_a_pass)
_not_a_pass = []


def unreadable(code, why):
    """Record that an input of the sync could not be read: the Selector,
    cPanel's listing, the system default, the web server, an ownership
    record (`code`). Once per process: a fleet pass meets the same failure
    once per account, and the report counts the passes."""
    if not _not_a_pass and code not in _unread:
        _unread.add(code)
        remember("unreadable", code, why=str(why))


@contextmanager
def not_a_pass():
    """Reads that are no pass's, the daily report's: an input they cannot
    read is not recorded (unreadable), or the next report would count a
    pass that never ran (found by Bugbot)."""
    _not_a_pass.append(True)
    try:
        yield
    finally:
        _not_a_pass.pop()


def read_conf():
    """The switches file as it stands, for its writers. Whether the sync
    may act is load_conf()."""
    # both directions default OFF: an unreadable or absent config must
    # leave the sync dormant, never writing on a half-installed system
    conf = {"selector_to_multiphp": "off", "multiphp_to_selector": "off"}
    try:
        with open(CONF_PATH) as f:
            for line in f:
                if "=" in line:
                    key, val = line.strip().split("=", 1)
                    conf[key.strip()] = val.strip()
    except (OSError, ValueError):  # ValueError: undecodable bytes
        pass
    return conf


def load_conf():
    return effective_conf(read_conf())


def effective_conf(conf):
    """`conf`, except that a sync the remote flag turned on reads off the
    moment the flag is off for this server. Every write path reads the
    switches through here, so a kill holds before apply_flag has turned
    the switches off. An administrator's sync never reads the flag; one
    without `enabled_by` predates it and is theirs."""
    if conf.get("enabled_by") == "remote" and not flag_on():
        conf = dict(conf, selector_to_multiphp="off",
                    multiphp_to_selector="off")
    return conf


DIRECTION_KEYS = {
    "selector-to-multiphp": ["selector_to_multiphp"],
    "multiphp-to-selector": ["multiphp_to_selector"],
    "all": ["selector_to_multiphp", "multiphp_to_selector"],
}


def direction_keys(direction):
    """The conf keys a CLI direction names, or a refusal: a typo must never
    enable — or withdraw — both directions."""
    keys = DIRECTION_KEYS.get(direction)
    if not keys:
        sys.exit("unknown direction %r — use selector-to-multiphp, "
                 "multiphp-to-selector or all" % direction)
    return keys


def conf_lock_path():
    """Serializes writers of the switches. `_`-prefixed like every engine
    file: `sync.conf` is itself a valid account name, whose record lock is
    `sync.conf.lock`."""
    return os.path.join(os.path.dirname(CONF_PATH), "_sync.conf.lock")


def set_conf(direction, value, by=None):
    """Write the switches.

    `by` names who — "admin" for the CLI, "remote" for the remote flag —
    and is kept as `enabled_by` when turning on (the flag only turns off a
    sync it turned on) and `disabled_by` when turning off (the flag never
    turns on one an admin turned off). An enable clears `disabled_by`, and
    the last direction off clears `enabled_by`: either would be a lie about
    the box as it now is. A reader treats an absent one as the admin's, and
    a direction an admin turns off makes the one left on theirs too.

    Under the lock, both sides of the flag: its own change is made only
    while flag_action() still asks for it (FlagSuperseded), and an admin's
    marks the flag only once the switches say so — a mark wakes the flag's
    units, which must find the switches the admin's already."""
    keys = direction_keys(direction)
    ensure_state_dir()
    # A read-modify-write, so under a lock — two admins turning different
    # directions at once would otherwise each save the other's old value —
    # of the file as it stands: the flag's view must not be written back.
    with path_lock(conf_lock_path()):
        conf = read_conf()
        if by == "remote" and flag_action(
                conf, os.path.exists(CONF_PATH), flag_on(),
                os.path.exists(FLAG_OPT_OUT)) != (
                    "enable" if value == "on" else "disable"):
            raise FlagSuperseded()
        for key in keys:
            conf[key] = value
        if conf["selector_to_multiphp"] == "on":
            # mirroring again: nothing is being handed back any more
            with contextlib.suppress(FileNotFoundError):
                os.unlink(WITHDRAW_PENDING)
        on = "on" in (conf["selector_to_multiphp"],
                      conf["multiphp_to_selector"])
        if value == "on":
            conf.pop("disabled_by", None)
            conf["enabled_by"] = one_line(by or "admin")
        else:
            if by:
                conf["disabled_by"] = one_line(by)
            if not on:
                conf.pop("enabled_by", None)
            elif by == "admin":
                conf["enabled_by"] = "admin"
        write_conf(conf)
        if conf["selector_to_multiphp"] == "on":
            # mirroring again: a hand-back the flag's kill left unfinished
            # has nothing more to do, and with `disabled_by` gone nothing
            # would retry it (found in the final review: the mark stayed,
            # and the daily report called it stuck every day)
            with contextlib.suppress(FileNotFoundError):
                os.unlink(FLAG_WITHDRAW_PENDING)
        # inside the lock: published after it, an older writer's copy could
        # land over a newer one's
        publish_state(effective_conf(conf))
        if by == "admin" and value == "on":
            admin_flag_on()
        elif by == "admin" and not on:
            admin_flag_off()
    # The switches only, spelled the way --enable/--disable accept them, so
    # the confirmation names what the reader would type. `disabled_by` is
    # stored beside them but is not one: listed here it read as a third
    # direction.
    print("syncing is now:")
    for key in sorted(DIRECTION_KEYS["all"]):
        print("  %-22s %s" % (key.replace("_", "-"), conf.get(key, "off")))
    print(owner_line(conf))


class FlagSuperseded(Exception):
    """The remote flag's switch change, no longer asked for by the time it
    is made: an admin's command, or the flag, changed since apply_flag
    decided."""


def one_line(value):
    """`enabled_by` and `disabled_by` are the conf values that are not fixed
    literals, and the file is parsed line by line: a newline in one would
    write a SECOND line, the obvious one to forge being
    `selector_to_multiphp=on`. Scrubbed where written, not trusted from
    every caller."""
    return str(value).replace("\r", " ").replace("\n", " ")


def write_conf(conf):
    """Replace the switches file; callers hold conf_lock_path(). Atomic,
    like save_json: a file truncated by a crash reads as both switches off,
    and an enabled sync would go silently dormant with its pins standing.
    Through a tmp file of its own, never one two writers could share."""
    fd, tmp = tempfile.mkstemp(dir=os.path.dirname(CONF_PATH),
                               prefix="_sync.conf.")
    try:
        with os.fdopen(fd, "w") as f:
            for key, val in conf.items():
                f.write("%s=%s\n" % (key, val))
            f.flush()
            os.fsync(f.fileno())
        replace_durably(tmp, CONF_PATH)
    except BaseException:
        try:
            os.unlink(tmp)
        except OSError:
            pass
        raise


def owner_line(conf):
    """Who decided the switches as they now stand."""
    if "on" in (conf["selector_to_multiphp"], conf["multiphp_to_selector"]):
        if conf.get("enabled_by") == "remote":
            return "turned on by CloudLinux's rollout (%s flag)" % FLAG_NAME
        return "turned on by an administrator: the rollout leaves it alone"
    if conf.get("disabled_by") == "remote":
        return "turned off by CloudLinux's rollout (%s flag)" % FLAG_NAME
    return "turned off by an administrator: the rollout leaves it alone"


def publish_state(conf):
    """Write the world-readable copy of the one switch a tenant may read:
    "on" or "off" for selector-to-multiphp, and nothing else — but
    "withdrawing" while it is off and a hand-back is under way or due
    (withdrawal_due: --disable still walking, or a kill of the remote flag
    --apply-flag has yet to apply), when a tenant's PHP Selector change has
    to hand its account back first (release). Every reader but that one
    takes it for "off". Found in review: an install republishing in the
    kill's window wrote "off".

    Never fails the switch it follows. A copy that could not be written is
    removed instead, so tenant-side readers fall back to "off", the
    classic reading, rather than keep an "on" the switch no longer says."""
    if conf.get("selector_to_multiphp") == "on":
        value = "on"
    else:
        value = "withdrawing" if withdrawal_due() else "off"
    directory = os.path.dirname(PUBLIC_STATE_PATH)
    try:
        os.makedirs(directory, exist_ok=True)
        os.chmod(directory, 0o755)
        fd, tmp = tempfile.mkstemp(dir=directory, prefix=".mirroring.")
        try:
            with os.fdopen(fd, "w") as f:
                f.write(value + "\n")
            os.chmod(tmp, 0o644)
            os.replace(tmp, PUBLIC_STATE_PATH)
        except BaseException:
            if os.path.exists(tmp):
                os.unlink(tmp)
            raise
    except OSError as e:
        log("PUBLIC-STATE could not be written (%s): %s"
            % (PUBLIC_STATE_PATH, e))
        try:
            os.unlink(PUBLIC_STATE_PATH)
        except FileNotFoundError:
            pass
        except OSError as e:
            log("PUBLIC-STATE could not be removed either: %s" % e)


def republish_state():
    """The public copy as the switches say, or no copy without them.

    No sync.conf reads as both switches off, and so does no copy: a box that
    never set a switch gets no new file, and a copy the switches no longer
    back (the state wiped under it) is removed rather than left saying on —
    its directory with it, since a directory without the copy is how a
    tenant tells a copy that was lost (public_copy_lost; found in review:
    after a wiped state every tenant's change asked the door for nothing)."""
    if os.path.exists(CONF_PATH):
        # under the switches' own lock, as set_conf publishes: read outside
        # it, an install racing a --disable could publish the `on` it read
        # just before the switch went off (found in review)
        with path_lock(conf_lock_path()):
            publish_state(load_conf())
        return
    for remove, path in ((os.unlink, PUBLIC_STATE_PATH),
                         (os.rmdir, os.path.dirname(PUBLIC_STATE_PATH))):
        try:
            remove(path)
        except FileNotFoundError:
            pass
        except OSError as e:
            log("PUBLIC-STATE could not be removed: %s" % e)
            return


def refresh_triggers():
    """Bring what runs the sync by itself in line with the switches: set up
    while either direction is on, removed once both are off.

    Called after every switch change, and by the package on every install
    and upgrade — so a box nobody turned the sync on for carries none of
    it, and an upgrade brings an enabled box's set up to date. Where there
    is nothing to do it creates nothing but its lock in /run: on a box that
    never enabled the sync, this finds no switch on and no trigger to
    remove, and writes no state and no log.

    Serialised, with the switches read inside the lock: two switch changes
    racing each other each refresh after their own write, and whichever
    refreshes last now applies what the file says then, not what it said
    when that caller first looked (found in review).

    It also stamps the records written before records were stamped
    (stamp_records), and hands MultiPHP the pins set in MultiPHP
    Manager that an older sync took for its own
    (migrate_arrived_pins)."""
    with triggers_lock():
        stamp_records()
        conf = load_conf()
        if "on" in (conf["selector_to_multiphp"],
                    conf["multiphp_to_selector"]):
            install_triggers()
        else:
            remove_triggers()
        migrate_arrived_pins()


def migrate_arrived_pins():
    """Hand MultiPHP every pin set in MultiPHP Manager that a row of ours
    stands on (arrived_pin_stands): one an older sync took for its own
    without writing it, as 7.11.51 did with every alt-php pin equal to the
    account's PHP Selector version. No write: the pin stays as it is, and
    its row says MultiPHP's (the_domains_own), as each account's next pass
    would say (plan_mirror). A pin the sync has moved since stays its own,
    so a --disable still restores what the domain arrived with. Run on
    every install, upgrade and switch change (refresh_triggers): a box the
    sync never ran on has no record, and nothing is read there. A record
    that cannot be used or saved is logged and skipped, for its account's
    next pass, and stops neither the others nor the refresh."""
    try:
        users = [u for u in sorted(state_accounts())
                 if os.path.exists(record_path(u))]
    except OSError:
        return  # no state: the sync never ran here
    if not users:
        return
    _, raw_pins = load_userdatadomains()
    if not raw_pins:
        return  # nothing read: each account's next pass does it
    now = time.strftime("%F %T")
    for user in users:
        handed = []
        try:
            with updated_record(user) as rec:
                for dom, entry in sorted(rec["domains"].items()):
                    pin = raw_pins.get(dom)
                    row = effective_entry(entry, pin)
                    # a hand-back's row is MultiPHP's already, and reads as
                    # `released` while the sync is off (verdict_of)
                    if row.get("owner") == "selector" \
                            and arrived_pin_stands(row, pin):
                        rec["domains"][dom] = the_domains_own(pin, now)
                        handed.append(dom)
        except RecordUnusable as e:
            log("RECORD %s — %s" % (user, e.note()))
            continue
        except OSError as e:
            log("RECORD %s could not be saved: %s" % (user, e))
            continue
        for dom in handed:
            log("RECORD %s: %s stands on %s, set in MultiPHP Manager: "
                "MultiPHP's, as without the sync" % (user, dom, raw_pins[dom]))


@contextmanager
def triggers_lock():
    """Exclusive flock on TRIGGERS_LOCK. Never nested: remove_triggers runs
    inside it from refresh_triggers, and the package removal takes it
    around its own call."""
    try:
        fd = os.open(TRIGGERS_LOCK,
                     os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
    except OSError as e:
        # The refresh runs unserialised then, as it did before the lock:
        # failing it would leave an upgrade's triggers unrefreshed and a
        # removal's hooks registered, for want of a lock file (found in
        # review). Logged only where the sync has a log to write to.
        if os.path.exists(CONF_PATH):
            log("TRIGGERS could not take %s (%s): refreshing without it"
                % (TRIGGERS_LOCK, e))
        yield
        return
    with os.fdopen(fd, "r+") as lock_file:
        fcntl.flock(lock_file, fcntl.LOCK_EX)
        try:
            yield
        finally:
            fcntl.flock(lock_file, fcntl.LOCK_UN)


def install_triggers():
    install_check_cron()
    install_hooks()
    install_easyapache_hook()
    arm_catchup_timer()


def remove_triggers(package_removal=False):
    """Also the package removal's call, whatever the switches say."""
    remove_check_cron()
    remove_hooks(package_removal=package_removal)
    remove_easyapache_hook()
    disarm_catchup_timer()


def easyapache_hook_path():
    """Where the EasyApache hook goes on this box: the universal-hooks
    tree of the package manager that has one (cagefs picks the same way),
    or None where cPanel's universal hooks are not installed at all."""
    for root, sub in UNIVERSAL_HOOK_DIRS:
        if os.path.isdir(root):
            return os.path.join(root, sub, EASYAPACHE_HOOK_DIR,
                                EASYAPACHE_HOOK_NAME)
    return None


def install_easyapache_hook():
    """The symlink cPanel's package manager runs after an ea-* transaction
    (handle_easyapache_change). One already in place is left as it is."""
    path = easyapache_hook_path()
    if path is None:
        return
    try:
        if os.readlink(path) == EASYAPACHE_HOOK_SCRIPT:
            return
    except OSError:
        pass
    try:
        os.makedirs(os.path.dirname(path), exist_ok=True)
        tmp = "%s.%d.tmp" % (path, os.getpid())
        os.symlink(EASYAPACHE_HOOK_SCRIPT, tmp)
        os.replace(tmp, path)
    except OSError as e:
        log("TRIGGERS could not install the EasyApache hook %s: %s"
            % (path, e))
        return
    log("TRIGGERS installed the EasyApache hook: %s" % path)


def remove_easyapache_hook():
    path = easyapache_hook_path()
    if path is None:
        return
    try:
        os.unlink(path)
    except FileNotFoundError:
        return
    except OSError as e:
        log("TRIGGERS could not remove the EasyApache hook %s: %s"
            % (path, e))
        return
    log("TRIGGERS removed the EasyApache hook: %s" % path)


def registered_hooks(quiet=False):
    """{(category, event, stage)} cPanel runs HOOK_SCRIPT for, or None when
    it cannot say (logged unless `quiet`, as a listing that could not even
    run is: found in review)."""
    out = run([MANAGE_HOOKS, "list", "--output=JSON"], quiet=quiet)
    try:
        listing = json.loads(out.stdout)
        return {(category, event, entry.get("stage"))
                for category, events in listing.items()
                for event, entries in (events or {}).items()
                for entry in entries or ()
                if entry.get("hook") == HOOK_SCRIPT}
    except (ValueError, AttributeError, TypeError):
        if not quiet:
            log("TRIGGERS could not list cPanel's hooks (rc=%s): %s"
                % (out.returncode, out.stderr.strip()[:200]))
        return None


def _hook_where(category, event, stage="post"):
    return ["--manual", "--category", category, "--event", event,
            "--stage", stage]


def install_hooks():
    """Register what is missing of the listener, and restart cpsrvd when
    anything was: long-lived WHM workers cache the hook registry, and
    without the restart events keep flowing past a new registration. What
    is registered already is left as it is, so an upgrade of an enabled
    box restarts nothing."""
    if not os.path.exists(MANAGE_HOOKS):
        return  # not cPanel: nothing to hook into
    registered = registered_hooks()
    added = []
    for category, event, weight, escalate, stage in SYNC_HOOKS:
        if registered is not None and (category, event, stage) in registered:
            continue
        if registered is None:
            # what is there cannot be told, and a raw add is not
            # idempotent: delete first, so a re-run stacks no duplicate
            run([MANAGE_HOOKS, "delete", "script", HOOK_SCRIPT]
                + _hook_where(category, event, stage))
        cmd = [MANAGE_HOOKS, "add", "script", HOOK_SCRIPT] \
            + _hook_where(category, event, stage)
        if weight is not None:
            cmd += ["--weight", str(weight)]
        if escalate:
            cmd.append("--escalateprivs")
        res = run(cmd)
        if res.returncode == 0:
            added.append(event)
        else:
            log("TRIGGERS could not register the %s hook: %s"
                % (event, (res.stderr or res.stdout).strip()[:200]))
    if added:
        run([RESTART_CPSRVD])
        log("TRIGGERS registered the cPanel hooks for %s and restarted "
            "cpsrvd" % ", ".join(added))


def remove_hooks(package_removal=False):
    """Unregister the listener, and restart cpsrvd only when something was
    unregistered: a WHM worker that still has it cached keeps invoking the
    removed script, and every MultiPHP change surfaces a hook error."""
    if not os.path.exists(MANAGE_HOOKS):
        return
    # Hooks are registered only while a direction is on, so a box that
    # never set a switch has none. It is still asked, for a state wiped
    # under hooks that stand; but where cPanel cannot answer there,
    # deleting blindly on every install and upgrade would be noise, and
    # the log line alone would start a log on a box that never used the
    # sync (found in review).
    # The package's removal is the exception: the script the hooks call
    # goes with it, so a wiped state under standing hooks must not leave
    # them registered there (found in review).
    ever_switched = package_removal or os.path.exists(CONF_PATH)
    registered = registered_hooks(quiet=not ever_switched)
    if registered is None:
        if not ever_switched:
            return
        # what is there cannot be told: ask for each one this registers
        registered = {(category, event, stage)
                      for category, event, _, _, stage in SYNC_HOOKS}
    removed = []
    for category, event, stage in sorted(registered):
        res = run([MANAGE_HOOKS, "delete", "script", HOOK_SCRIPT]
                  + _hook_where(category, event, stage))
        if res.returncode == 0:
            removed.append(event)
    if removed:
        run([RESTART_CPSRVD])
        log("TRIGGERS unregistered the cPanel hooks for %s and restarted "
            "cpsrvd" % ", ".join(removed))


def arm_catchup_timer():
    """The boot catch-up: a convergence pass a reboot interrupted finishes
    5 minutes after the next boot (--reconcile: idempotent, and it holds
    the fleet lock). `enable`, deliberately not `enable --now`: OnBootSec
    has long elapsed on a box that has been up a while, so starting it here
    would fire a fleet pass at once. Armed from the next boot on."""
    if not os.path.exists(SYSTEMCTL):
        return
    if run([SYSTEMCTL, "is-enabled", CATCHUP_TIMER]).stdout.strip() == "enabled":
        return
    res = run([SYSTEMCTL, "enable", CATCHUP_TIMER])
    if res.returncode == 0:
        log("TRIGGERS armed the boot catch-up (%s)" % CATCHUP_TIMER)
    else:
        log("TRIGGERS could not arm the boot catch-up (%s): %s"
            % (CATCHUP_TIMER, res.stderr.strip()[:200]))


def disarm_catchup_timer():
    if not os.path.exists(SYSTEMCTL):
        return
    if run([SYSTEMCTL, "is-enabled", CATCHUP_TIMER]).stdout.strip() != "enabled":
        return
    run([SYSTEMCTL, "disable", "--now", CATCHUP_TIMER])
    log("TRIGGERS disarmed the boot catch-up (%s)" % CATCHUP_TIMER)


def install_check_cron():
    """The daily run (--daily: a reconcile, then the drift check), at a
    random time to spread the fleet's load. One already in place keeps its
    time, and a check-only one from before is replaced."""
    try:
        with open(CHECK_CRON_PATH) as f:
            if CHECK_CRON_COMMAND in f.read():
                return
    except OSError:
        pass
    # a dot-file: cron skips those, so it never runs a half-written one.
    # And one of its own: two installs at once (--enable during an
    # upgrade's --refresh-triggers) would otherwise write into the same file
    # and rename it from under each other
    fd, tmp = tempfile.mkstemp(
        dir=os.path.dirname(CHECK_CRON_PATH),
        prefix="." + os.path.basename(CHECK_CRON_PATH) + ".")
    try:
        with os.fdopen(fd, "w") as f:
            f.write("# CloudLinux MultiPHP <-> PHP Selector sync: the daily "
                    "run (a reconcile, then the drift check).\n# Present "
                    "while syncing is on; removed by "
                    "`cloudlinux-multiphp-sync --disable`.\n")
            f.write("%d %d * * * root %s\n" % (random.randint(0, 59),
                                               random.randint(0, 23),
                                               CHECK_CRON_COMMAND))
            f.flush()
            os.fsync(f.fileno())
        os.chmod(tmp, 0o644)
        replace_durably(tmp, CHECK_CRON_PATH)
    except BaseException:
        try:
            os.unlink(tmp)
        except OSError:
            pass
        raise
    log("TRIGGERS installed the daily run: %s" % CHECK_CRON_PATH)


def remove_check_cron():
    try:
        os.unlink(CHECK_CRON_PATH)
    except FileNotFoundError:
        return
    log("TRIGGERS removed the daily run: %s" % CHECK_CRON_PATH)


def ensure_state_dir():
    """The state says who owns which domain and whether the sync may write
    at all, so it is root-only. Modes are set explicitly rather than left to
    the caller's umask, because a tenant-readable record or kill switch
    would expose what root decided, and a writable one would steer it."""
    os.makedirs(STATE_DIR, mode=0o700, exist_ok=True)
    os.chmod(STATE_DIR, 0o700)  # exist_ok leaves an older 0755 dir as it is


def open_private(path, mode):
    """open() that creates with STATE_MODE instead of 0666 & ~umask.

    "r+" creates the file if it is missing but never truncates it, which is
    what the intents journal needs: it is rewritten in place under a lock."""
    flags = {"w": os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
             "r+": os.O_RDWR | os.O_CREAT}[mode]
    return os.fdopen(os.open(path, flags, STATE_MODE), mode)


def record_path(user):
    return os.path.join(STATE_DIR, "%s.json" % user)


class RecordUnusable(Exception):
    """An account's ownership record exists and cannot be used.

    Nothing may replace it. The record is not an index over the box that
    a pass could rebuild: it is the only proof of which pins are ours, and
    read as empty it was saved over by the next pass — every pin of ours
    then read as found, an admin's to keep. So the account is left alone,
    and the file as it is, until an administrator repairs or removes it
    (removed, the account starts afresh, as one the sync never touched)."""

    def __init__(self, user, path, why):
        Exception.__init__(self, "%s: %s" % (path, why))
        self.user, self.path, self.why = user, path, why

    def note(self):
        return ("its ownership record %s is unusable (%s): the sync leaves "
                "this account alone until the file is repaired or removed"
                % (self.path, self.why))


def load_record(user, quiet=False):
    """The account's ownership record; an empty one when it has none.
    Raises RecordUnusable when the file exists and cannot be used, which
    is logged, but for a `quiet` reader (owned_pins: a tenant can loop
    it, and a line per call would push the audit lines out of the
    rotation)."""
    path = record_path(user)
    try:
        with open(path) as f:
            record = json.load(f)
        entries = record.get("domains")
        if isinstance(entries, dict) and all(
                isinstance(e, dict) for e in entries.values()):
            if left_by_a_namesake(user, record):
                if not quiet:
                    log("RECORD %s: the one a deleted account of that name "
                        "left is not this account's" % user)
                return {"domains": {}}
            return record
        # valid JSON of the wrong shape (an older schema, a hand edit) is
        # no more usable than truncated JSON
        raise ValueError("not a map of ownership entries")
    except FileNotFoundError:
        # the absence of a record is the normal cold-start state, not a
        # fault — one removed between a look and this read included
        # (prune_records drops the records of deleted accounts)
        return {"domains": {}}
    except (OSError, ValueError, AttributeError) as e:
        # ValueError covers undecodable bytes too
        unusable = RecordUnusable(user, path, e)
        if not quiet:
            log("WARN %s — %s" % (user, unusable.note()))
            unreadable("record", e)
        raise unusable


def ledger_entries(user):
    """The account's ledger entries, or None when its record is unusable:
    a listener then leaves the account alone, as a pass does (load_record
    has logged why)."""
    try:
        return load_record(user)["domains"]
    except RecordUnusable:
        return None


def record_lock_path(user):
    return os.path.join(STATE_DIR, "%s.lock" % user)


# The pass files join the account and their name with "@", which
# ACCOUNT_NAME never allows: joined with "." instead, `bob`'s pass lock
# was the record lock of an account named `bob.pass`.
def pass_lock_path(user):
    """Serializes mirror passes for one account, whatever triggered them.
    A separate file from record_lock_path: mirror() takes that one, and
    flock on the same path through a second descriptor would deadlock."""
    return os.path.join(STATE_DIR, "%s@pass.lock" % user)


def pass_stamp_path(user):
    """When the account's last paced pass ran. The tenant door paces
    itself off this, so back-to-back tenant changes cannot drive one
    Apache configuration rebuild after another."""
    return os.path.join(STATE_DIR, "%s@pass.stamp" % user)


def release_stamp_path(user):
    """When a tenant's last hand-back ran: its releases are paced off this,
    apart from its passes, so a release does not delay the pass that ends
    its change, and a loop of releases is paced all the same (found in
    review: off the pass's stamp, which releases never move, it was not)."""
    return os.path.join(STATE_DIR, "%s@release.stamp" % user)


def pass_request_path(user):
    """Left behind by a trigger that could not take the pass lock: the
    pass holding it re-runs on seeing this, so a change that lands
    mid-pass is deferred rather than dropped."""
    return os.path.join(STATE_DIR, "%s@pass.requested" % user)


def new_pending_path(user):
    """Touched by every new domain of the account, removed by the pass
    that waits for them to settle (settle)."""
    return os.path.join(STATE_DIR, "%s@new.pending" % user)


def modify_pending_path(user):
    """What the start of WHM's Modify Account noted for its end: the
    account's main domain (handle_modify_start)."""
    return os.path.join(STATE_DIR, "%s@modify" % user)


def modify_held_path(user):
    """Stands once a pass was held while the account was being modified
    (modifying): its end runs the pass then (handle_modify)."""
    return os.path.join(STATE_DIR, "%s@modify.held" % user)


def restoring_path(user):
    """Stands while the account is being restored, from its restore's
    start (handle_restore_start) to its end (handle_restore): the process
    restoring it, and when that began (restoring)."""
    return os.path.join(STATE_DIR, "%s@restoring" % user)


def leave_request(user, reason,
                  why="a pass is already running, requested a re-run"):
    """Leave the marker the pass holding the account's lock serves on its
    way out (see guarded_mirror), or the pass ending a change in flight
    (see begin_change). Logged by the trigger that leaves it and no other:
    until that pass takes it, the one marker stands for every trigger after
    it too — found in review, a caged tenant's loop logged a line per
    concurrent call."""
    try:
        fd = os.open(pass_request_path(user),
                     os.O_WRONLY | os.O_CREAT | os.O_EXCL, STATE_MODE)
    except FileExistsError:
        return
    except OSError as e:
        log("PASS-REQUEST could not be recorded: %s" % e)
        return
    os.close(fd)
    log("PASS-DEFERRED user=%s reason=%s — %s" % (user, reason, why))


def changes_dir(user):
    """The account's PHP Selector changes in flight, a file each."""
    return os.path.join(STATE_DIR, "%s@changes" % user)


def change_stamp_path(user):
    """Touched whenever one of the account's changes begins or ends: a
    fleet chunk whose Selector reading is older plans the account again
    (write_chunk)."""
    return os.path.join(STATE_DIR, "%s@change.stamp" % user)


def door_lock_path(user):
    """Held by the one tenant step on the account the door runs at a time
    (proxyexec_mirror), so its waiting processes stay bounded."""
    return os.path.join(STATE_DIR, "%s@door.lock" % user)


def _stamp_change(user):
    try:
        with open_private(change_stamp_path(user), "w"):
            pass  # the mtime is the record, not the content
    except OSError as e:
        log("CHANGE-STAMP could not be recorded for %s: %s" % (user, e))


def fs_clock():
    """Now, by the clock file times are set from. That is the kernel's
    coarse clock, which can trail time.time() by a tick, so a stamp touched
    just after a time.time() reading could compare as older than it. On
    one clock, a stamp touched after this compares as no older."""
    ensure_state_dir()
    fd, path = tempfile.mkstemp(dir=STATE_DIR, prefix="_clock.")
    try:
        return os.fstat(fd).st_mtime
    finally:
        os.close(fd)
        os.unlink(path)


def changed_since(user, when):
    """Whether one of the account's changes began or ended at `when` or
    later, `when` being an fs_clock() reading."""
    try:
        return os.path.getmtime(change_stamp_path(user)) >= when
    except OSError:
        return False


def begin_change(user, token, capped=False, owner=None):
    """Record that a PHP Selector change is in flight on the account. Until
    it ends (end_change) no pass writes the account: CageFS gives the
    account's extensions to its SELECTED version only, so a pin written for
    the version it is leaving serves that version with the server-wide set
    from the switch until the next pass. Passes that would have run leave a
    request, and the pass ending the last change serves it.

    Each caller names its change, so two changes on one account end
    separately and the last one's pass sees the final version. False when
    it could not be recorded or the token is malformed: the change must not
    go ahead then. capped: a tenant's change, through the door, refused
    while MAX_CHANGES are already in flight. Root's never are — found in
    review, a tenant filling the cap vetoed the admin's changes on the
    account, a box-wide deny-all included. That refusal is not logged, as a
    tenant can loop the door into it. owner: the process that began the
    change, which it lasts as long as (pending_changes)."""
    if not CHANGE_TOKEN.match(token or ""):
        return False
    if capped and len(pending_changes(user)) >= MAX_CHANGES:
        return False
    try:
        ensure_state_dir()
        os.makedirs(changes_dir(user), mode=0o700, exist_ok=True)
        started = process_started(owner) if owner else None
        with open_private(os.path.join(changes_dir(user), token), "w") as f:
            # the mtime is when it began, or when its hand-back ended
            if started is not None:
                json.dump({"pid": int(owner), "started": started}, f)
    except OSError as e:
        log("CHANGE could not be recorded for %s: %s" % (user, e))
        return False
    _stamp_change(user)
    return True


def refresh_change(user, token):
    """Count the change's time from now: its hand-back has just landed,
    and the switch it waits for comes after (CHANGE_TTL)."""
    with contextlib.suppress(OSError):
        os.utime(os.path.join(changes_dir(user), token), None)


def change_exists(user, token):
    """Whether this change is in flight."""
    return bool(CHANGE_TOKEN.match(token or "")) and \
        os.path.exists(os.path.join(changes_dir(user), token))


def end_change(user, token):
    """The change is over. True when it was in flight."""
    if not CHANGE_TOKEN.match(token or ""):
        return False
    try:
        os.unlink(os.path.join(changes_dir(user), token))
    except OSError:
        return False
    _stamp_change(user)
    return True


def pending_changes(user):
    """The account's changes in flight, removing the ones whose caller
    never ended them. A change naming the process that began it lasts while
    that process does, CHANGE_OWNED_TTL at most; any other is over
    CHANGE_TTL after it began. One stamped further ahead than its limit is
    over too: a clock stepped back must not hold the account for the length
    of the skew."""
    try:
        names = os.listdir(changes_dir(user))
    except OSError:
        return []
    pending = []
    now = time.time()
    for name in sorted(names):
        path = os.path.join(changes_dir(user), name)
        try:
            age = now - os.path.getmtime(path)
        except OSError:
            continue
        if CHANGE_TOKEN.match(name):
            owner = change_owner(path)
            if owner is None and abs(age) < CHANGE_TTL:
                pending.append(name)
                continue
            if owner is not None and abs(age) < CHANGE_OWNED_TTL \
                    and process_started(owner[0]) == owner[1]:
                pending.append(name)
                continue
        log("CHANGE expired user=%s — its caller never ended it" % user)
        try:
            os.unlink(path)
        except OSError:
            pass
    return pending


def change_owner(path):
    """(pid, its start time) of the process a change's file names, or None
    for one that names none."""
    try:
        with open(path) as f:
            content = f.read()
        if not content:
            return None
        mark = json.loads(content)
        return int(mark["pid"]), str(mark["started"])
    except (OSError, ValueError, KeyError, TypeError, AttributeError):
        return None


def process_started(pid):
    """When the process `pid` started (field 22 of /proc/<pid>/stat), or
    None when there is no such process: with the pid, the process itself,
    which a reused pid is not."""
    try:
        with open("/proc/%d/stat" % int(pid)) as f:
            stat = f.read()
        # the command name is in parentheses and may hold spaces
        return stat.rsplit(")", 1)[1].split()[19]
    except (OSError, ValueError, IndexError, TypeError):
        return None


def pass_running(user):
    """Whether a mirror pass for this account is mid-flight.

    The hook's one way to ask "could this event be my own write?". Our
    whmapi write raises the cPanel hook synchronously from inside
    guarded_mirror, which holds this lock for the whole pass — that is
    exactly why guarded_mirror takes it non-blockingly, since a pass
    reached from inside our own write would otherwise wait on a lock its
    own caller holds. So a free lock here is positive evidence, not merely
    an absence of evidence: no write of ours can be in flight.

    It answers a different question from consume_intents, which is why both
    are asked. The intent proves a specific write was ours; losing one
    only costs the shortcut. This proves no write of ours exists to have
    an intent, and it cannot be lost or expire.

    A shared probe, released before returning: an exclusive one would be
    the same exclusion the holder uses, and either way the window is the
    few microseconds of an open and two flocks. A trigger that loses that
    race leaves a request, which the pass this event goes on to run
    consumes.

    Unreadable state answers True. "A pass may be running" is what makes
    the caller decline to guess, which is the safe side of this question.
    """
    try:
        ensure_state_dir()
        with open_private(pass_lock_path(user), "r+") as lock_file:
            try:
                fcntl.flock(lock_file, fcntl.LOCK_SH | fcntl.LOCK_NB)
            except OSError:  # EWOULDBLOCK — a pass holds it
                return True
            fcntl.flock(lock_file, fcntl.LOCK_UN)
            return False
    except OSError as e:
        log("WARN pass lock for %s unreadable, assuming a pass is "
            "running: %s" % (user, e))
        return True


def pool_dir(user):
    """Where the account's FPM pool copies live (see snapshot_fpm_pools)."""
    return os.path.join(FPM_POOL_DIR, user)


def pool_path(user, dom):
    return os.path.join(pool_dir(user), "%s.yaml" % dom)


def pace_sleep(user, stamp=None):
    """Wait out DOOR_PACE since the account's last pass, or since what
    `stamp` dates (a tenant's last hand-back, release_stamp_path). Returns
    how long ago that was, or None when there is none on record."""
    try:
        since = time.time() - os.path.getmtime(stamp or pass_stamp_path(user))
    except OSError:
        return None  # no pass on record to pace
    if since < DOOR_PACE:
        # a stamp from the future (a clock stepped back) must not sleep the
        # whole skew while holding the pass lock
        time.sleep(DOOR_PACE - max(since, 0.0))
    return since


def guarded_mirror(user, reason, pace=False, vhosts=None, coverage=None,
                   default_pkg=None, after_change=None):
    """One mirror pass per account at a time, whatever triggered it.

    mirror() has to release the record lock before its whmapi write: that
    write raises our own hook synchronously and the hook needs the same
    lock. Two overlapping passes therefore read state independently and
    can write in the wrong order, leaving the older pin standing and the
    site on the previous PHP version. This is the lock that makes passes
    mutually exclusive, and it is never held across an external command.

    Non-blocking on purpose: a pass reached from inside our own write (a
    gateway return, an FPM return) would otherwise wait on a lock its own
    caller holds. A trigger that cannot take it leaves a request and the
    holder re-runs, so the newer state still reaches MultiPHP.

    pace: the tenant door and the tenant-reachable CLI paths only. The
    fleet pass needs no throttle of its own — it writes a whole chunk of
    accounts per call rather than one account at a time — and an admin's
    change must not wait on a tenant's.

    While a PHP Selector change is in flight on the account (begin_change)
    the pass writes nothing: it leaves a request and returns.

    after_change: the change this pass ends. When the change is in flight
    the pass waits for the lock instead of deferring, since it is the pass
    the change's deferred triggers are waiting for, and only then ends it:
    ended before the wait, a tenant's change gave its slot under
    MAX_CHANGES back while its process still waited (found in review). A
    token nobody began is a plain pass. It runs only when no other change
    is still in flight: the last one to end runs it, so it sees the version
    the account ends up on.
    """
    in_flight = after_change is not None and change_exists(user, after_change)
    lock = (path_lock_wait(pass_lock_path(user), CHANGE_LOCK_WAIT)
            if in_flight else path_lock_nb(pass_lock_path(user)))
    with lock as acquired:
        request = pass_request_path(user)
        if after_change is not None:
            end_change(user, after_change)
        if not acquired:
            # the marker is the file's existence, not content
            leave_request(user, reason)
            return False
        if restoring(user) or modifying(user):
            # its restore converges it at its end (handle_restore): a pass in
            # between would pin what the restore has yet to bring back. So
            # does a modification of the account in WHM (handle_modify).
            # Asked under the lock, which the restore's start holds while it
            # marks the account: asked before, a pass could pin the account
            # right after its start had handed it back (found in review).
            # A change this pass ends has ended above. A request is the
            # restore's end's to serve, so it goes, and a tenant's pass is
            # held quietly, as the door refuses (found in review: a line per
            # door call, and a detached root pass per call once a request
            # stood).
            with contextlib.suppress(OSError):
                os.unlink(request)
            if not restoring(user):
                mark_modify_held(user)
            if not pace:
                log("PASS-HELD user=%s — being %s (reason=%s)"
                    % (user, "restored" if restoring(user) else "modified",
                       reason))
            return False
        if pending_changes(user):
            if not in_flight:
                leave_request(user, reason,
                              "a PHP Selector change is in flight; its end "
                              "runs the pass")
            elif not pace:
                # not for a tenant's: the door can be looped, and its
                # passes are paced only once they run
                log("CHANGE-END user=%s — another change is still in flight, "
                    "its end runs the pass" % user)
            return False

        def one_pass(vhosts, coverage):
            # the pace spares Apache back-to-back rebuilds, and a pass with
            # the direction off rebuilds nothing: mirror() says so and
            # returns. Pacing it anyway held a tenant's second Selector
            # change for up to DOOR_PACE on every box, sync on or off.
            quiet = False
            if pace and load_conf()["selector_to_multiphp"] == "on":
                since = pace_sleep(user)
                # inside a burst a no-op pass leaves no line (NOOP_TRACE_GAP)
                quiet = since is not None and 0 <= since < NOOP_TRACE_GAP
            wrote = mirror(user, reason=reason, vhosts=vhosts,
                           coverage=coverage, default_pkg=default_pkg,
                           trace_noop=not quiet)
            try:
                with open_private(pass_stamp_path(user), "w"):
                    pass  # the mtime is the record, not the content
            except OSError as e:
                log("PASS-STAMP could not be recorded: %s" % e)
            return wrote

        if vhosts is None and coverage is None:
            # A request left before this pass began is a change this pass
            # reads afresh, so it is consumed here rather than re-run for.
            # The follow-up cap's hand-off leaves one for the detached pass
            # it starts, which mirrored the change, then took the leftover
            # marker for a change that arrived mid-pass and ran again — on
            # the tenant door sleeping DOOR_PACE first, with the lock held
            # (found by Bugbot). A pass handed a reading keeps it: that
            # reading may predate the request.
            try:
                os.unlink(request)
            except OSError:
                pass  # none was left, or one that cannot go: as before
        wrote = one_pass(vhosts, coverage)
        for _ in range(PASS_FOLLOWUPS):
            if not os.path.exists(request):
                break
            try:
                os.unlink(request)
            except OSError:
                break
            log("PASS re-running user=%s for a change that arrived mid-pass"
                % user)
            # the request exists because state moved: re-read it rather
            # than replan from the reading that went stale — passing no
            # vhost list and no coverage makes the pass read both
            wrote = one_pass(None, None) or wrote
    # The cap bounds the work THIS process does, never the change itself:
    # the caller that left the marker has already returned and nothing
    # else consumes it, so dropping it would leave the last Selector
    # change unmirrored and the site serving the old pin. Looked for AFTER
    # the release, and dispatched there too: a requester that failed the
    # lock a moment before the release writes its marker after any look
    # taken inside, and a detached pass started while this one still held
    # the lock would defer, re-leave the marker and exit — reproducing the
    # drop this exists to prevent. The pass keeps the throttle this one
    # had, or a tenant's change loop would find in the cap a way around
    # the door's pacing.
    if os.path.exists(request):
        log("PASS follow-up cap reached with a change still outstanding "
            "user=%s — dispatching a detached pass" % user)
        spawn_mirror(user, reason, paced=pace)
    return wrote


@contextmanager
def path_lock_nb(path):
    """path_lock that never waits: yields True when the lock was taken,
    False when another holder has it."""
    ensure_state_dir()
    with open_private(path, "r+") as lock_file:
        try:
            fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except OSError:  # EWOULDBLOCK — someone else is mid-pass
            yield False
            return
        try:
            yield True
        finally:
            fcntl.flock(lock_file, fcntl.LOCK_UN)


@contextmanager
def path_lock_wait(path, timeout):
    """path_lock that gives up after `timeout` seconds: yields True when
    the lock was taken, False when its holder kept it that long. Polled,
    since flock has no timeout of its own."""
    ensure_state_dir()
    deadline = time.time() + timeout
    with open_private(path, "r+") as lock_file:
        while True:
            try:
                fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
                break
            except OSError:  # EWOULDBLOCK — a pass holds it
                if time.time() >= deadline:
                    yield False
                    return
                time.sleep(0.1)
        try:
            yield True
        finally:
            fcntl.flock(lock_file, fcntl.LOCK_UN)


@contextmanager
def path_lock(path):
    """Exclusive flock on a dedicated lock file (created root-only)."""
    ensure_state_dir()  # hook callers reach this without going through main()
    with open_private(path, "r+") as lock_file:
        fcntl.flock(lock_file, fcntl.LOCK_EX)
        try:
            yield
        finally:
            fcntl.flock(lock_file, fcntl.LOCK_UN)


@contextmanager
def record_lock(user):
    """Serializes read-modify-write cycles on a user's record. Concurrent
    writers are the norm, not the exception (our own hook runs inside our
    own write, and a tenant's pass can overlap an admin's event), and a lost
    takeover entry would let the mirror overwrite
    an admin's pin. NOTE: never call mirror() while holding this lock — the
    mirror takes it itself."""
    with path_lock(record_lock_path(user)):
        yield


def save_json(path, data):
    """Atomic replace — a crash mid-write must never leave a truncated
    file. The tmp path is per-target: concurrent writers of the same
    target must serialize themselves (records hold record_lock)."""
    tmp = path + ".tmp"
    with open_private(tmp, "w") as f:
        json.dump(data, f, indent=1)
        f.flush()
        os.fsync(f.fileno())
    replace_durably(tmp, path)


def replace_durably(tmp, path):
    """os.replace, then fsync the directory. The content is on disk by now,
    but the rename is what makes it the file, and until the directory entry
    is too a crash can bring back the old file — or, on a first write, no
    file at all. A directory the filesystem will not fsync costs only that
    guarantee: the replace itself has happened."""
    os.replace(tmp, path)
    try:
        fd = os.open(os.path.dirname(path) or ".", os.O_RDONLY)
        try:
            os.fsync(fd)
        finally:
            os.close(fd)
    except OSError:
        pass


def save_record(user, record):
    """Callers must hold record_lock(user) — a lost concurrent update here
    means a lost takeover entry, which is a pin the mirror may overwrite.
    The record is stamped with the account's creation (account_started)
    and uid (account_uid), which tell it from a deleted namesake's
    (left_by_a_namesake, forget_account)."""
    for key, value in (("started", account_started), ("uid", account_uid)):
        if key not in record:
            known = value(user)
            if known is not None:
                record[key] = known
    save_json(record_path(user), record)


def account_started(user):
    """When cPanel created the account (STARTDATE in its users file, which a
    restore brings back from the backup), or None when that is unknown."""
    try:
        with open(os.path.join(CPANEL_USERS_DIR, user)) as f:
            return int(float(next(line.split("=", 1)[1] for line in f
                                  if line.startswith("STARTDATE="))))
    except (OSError, StopIteration, ValueError):
        return None


def account_uid(user):
    """The account's uid, or None when it has no system user (yet)."""
    try:
        return pwd.getpwnam(user).pw_uid
    except KeyError:
        return None


def left_by_a_namesake(user, record):
    """Whether the record was a deleted account's of the same name, read
    on any load: stamped with another uid AND another creation. Found in
    review: an account re-created while the sync was off kept a deleted
    one's record, so a hand-back wrote the deleted account's admin version
    over the new one's domain. Either stamp alone is not enough: STARTDATE
    moves with WHM's Modify Multiple Accounts and with a restore of a
    backup made elsewhere, and a live account lost its ledger, every pin of
    ours with it (found in review); a uid is the next account's to take.
    A record without both stamps (written before them) is the account's,
    and so is one whose account cannot be told."""
    started, uid = record.get("started"), record.get("uid")
    if not isinstance(started, int) or not isinstance(uid, int):
        return False
    now_started, now_uid = account_started(user), account_uid(user)
    if now_started is None or now_uid is None:
        return False
    return started != now_started and uid != now_uid


def held_for_a_namesake(user, hold):
    """Whether a hold on the account (a modification's note, a restore's
    mark) was written for a deleted account of the same name: for another
    uid than the account has. forget_account and forget_namesake_holds
    drop those as the account is made, but only a hook of a sync with its
    mirror on sees that (found by Bugbot: made with the mirror off, the
    deleted account's note, its process still running, held every pass,
    prune and release of the new one). A restore into an existing account
    keeps its uid. A hold that names none (written before the account
    existed), or an account that cannot be told, goes by its process and
    age alone."""
    uid = hold.get("uid") if isinstance(hold, dict) else None
    return uid is not None and account_uid(user) not in (None, uid)


def load_hold(path):
    """A hold's content as written, or None where it cannot be read."""
    try:
        with open(path) as f:
            return json.load(f)
    except (OSError, ValueError):
        return None


def stamp_records():
    """Stamp every record written before records were stamped (save_record),
    as its account's now: an unstamped one is trusted as the account's,
    whichever account has the name (left_by_a_namesake), and a converged
    account's is never saved again. One whose account is gone goes
    instead. Found in review: a deleted account's unstamped record was the
    next namesake's; a pass between the new account's creation and its
    Accounts::Create hook acted on its rows, then saved it stamped as the
    new account's. Run on every install and upgrade (refresh_triggers)."""
    try:
        users = state_accounts()
    except OSError:
        return  # no state: the sync never ran here
    for user in sorted(users):
        try:
            stamp_record(user)
        except OSError as e:
            # one record that cannot be saved (a full disk) stops neither the
            # others nor what runs after this (refresh_triggers): found in
            # review, a --disable then never reached its hand-back
            log("RECORD %s could not be stamped: %s" % (user, e))


def stamp_record(user):
    """stamp_records for one account."""
    path = record_path(user)
    if not os.path.exists(path):
        return
    gone = account_uid(user) is None and account_started(user) is None
    if gone and (restoring(user) or modifying(user)):
        # an account restored as new has no system user yet, and one being
        # renamed has none under its old name
        return
    with record_lock(user):
        try:
            with open(path) as f:
                record = json.load(f)
        except (OSError, ValueError):
            return  # unusable: nothing may write it (load_record)
        if not isinstance(record, dict) \
                or not isinstance(record.get("domains"), dict) \
                or ("started" in record and "uid" in record):
            return
        if not gone:
            save_record(user, record)
            return
        with contextlib.suppress(OSError):
            os.unlink(path)
    log("RECORD %s: the account is gone, and its record, written before "
        "records were stamped, with it" % user)


def restamp_record(user):
    """A restore's end (handle_restore, or restoring for one that died
    before it): a record the account kept, not a deleted namesake's
    (left_by_a_namesake), takes the account's stamps as they are now,
    where save_record writes only those it lacks. Found by
    Bugbot: made anew from its backup, the account has another uid, and
    the record it kept kept the old one; a later STARTDATE change (WHM's
    Modify Multiple Accounts, another archive's restore) made both stamps
    differ, and the live account's rows went as a deleted namesake's."""
    path = record_path(user)
    if not os.path.exists(path):
        return
    with record_lock(user):
        try:
            with open(path) as f:
                record = json.load(f)
        except (OSError, ValueError):
            return  # unusable: nothing may write it (load_record)
        rows = record.get("domains") if isinstance(record, dict) else None
        if not isinstance(rows, dict) \
                or not all(isinstance(e, dict) for e in rows.values()) \
                or left_by_a_namesake(user, record):
            return
        now = {"started": account_started(user), "uid": account_uid(user)}
        if None in now.values() \
                or all(record.get(key) == now[key] for key in now):
            return
        record.update(now)
        try:
            save_json(path, record)
        except OSError as e:
            log("RECORD %s could not be stamped: %s" % (user, e))

def stamped_before(user, path, record, started):
    """Whether the record predates the account created at `started`, at its
    creation (forget_account): a new account has no record of its own yet,
    so one stamped with another creation is a deleted namesake's whatever
    its uid, and so is an unstamped one written before it. Found in review:
    a pass between the account's creation and its Accounts::Create hook
    re-saved the old record with a fresh date."""
    stamp = record.get("started")
    if isinstance(stamp, int):
        return stamp != started
    try:
        return os.path.getmtime(path) < started
    except OSError:
        return False


def renamed_to(user, record):
    """The account a record under `user` proves, renamed away from that
    name before the record could follow it (finish_rename): the one of
    another name that has both the record's uid and its creation, which a
    rename keeps. None for any other record."""
    started, uid = record.get("started"), record.get("uid")
    if not isinstance(started, int) or not isinstance(uid, int):
        return None
    try:
        name = pwd.getpwuid(uid).pw_name
    except KeyError:
        return None
    if name == user or not ACCOUNT_NAME.match(name) \
            or account_started(name) != started:
        return None
    return name


@contextmanager
def updated_record(user):
    """Locked read-modify-write: yields the record, then persists it
    atomically. Nothing external may run inside the block — see
    record_lock. A record that reads as none because an account renamed
    away from the name left it goes on to that account first, rather than
    under the save below (own_record)."""
    with record_lock(user):
        record = own_record(user)
        before = json.dumps(record, sort_keys=True)
        yield record
        # a block that changed nothing must not cost an fsync: the
        # ownership guards are evaluated in here, so an event can
        # legitimately reach this point and leave every entry as it
        # found it
        if json.dumps(record, sort_keys=True) != before:
            save_record(user, record)


def own_record(user):
    """Under record_lock(user), for a read the account's rows are saved
    from: its record, once one an account renamed away from the name left
    has gone on to that account (hand_on_renamed_record). Every such save
    reads through here: updated_record, the account's pass and the fleet
    pass (found by Bugbot: the two passes read the record directly, and a
    pass of a new account of the old name still saved over it). A hand-on
    that cannot be written leaves the record unusable for now, so nothing
    is saved over it: a pass then leaves the account to the next one."""
    record = load_record(user)
    try:
        handed_on = not record["domains"] and hand_on_renamed_record(user)
    except OSError as e:
        raise RecordUnusable(
            user, record_path(user),
            "it is a renamed account's, and could not go on to it: %s" % e
        ) from e
    return load_record(user) if handed_on else record


def hand_on_renamed_record(user):
    """Under record_lock(user): a record a deleted namesake's stamps mark
    (left_by_a_namesake) that an account renamed away from the name left
    before it could follow (renamed_to) goes on to that account, the old
    rows winning, as forget_account hands it on. Found in the final review:
    a pass of a new account of the old name, before its Accounts::Create
    hook, read it as none and saved over it, and the renamed account's pins
    read as an admin's from then on (own_record). Whether it went."""
    try:
        with open(record_path(user)) as f:
            record = json.load(f)
    except (OSError, ValueError):
        return False
    rows = record.get("domains") if isinstance(record, dict) else None
    if not isinstance(rows, dict) or not rows \
            or not all(isinstance(e, dict) for e in rows.values()) \
            or not left_by_a_namesake(user, record):
        return False
    heir = renamed_to(user, record)
    if heir is None:
        return False
    with record_lock(heir):
        try:
            kept = load_record(heir)
        except RecordUnusable:
            return False
        kept["domains"].update(rows)
        save_record(heir, kept)
    with contextlib.suppress(OSError):
        os.unlink(record_path(user))
    log("RENAME %s -> %s: a new account took the old name before the "
        "record moved; it goes on to the renamed account" % (user, heir))
    return True


def load_intents(f):
    """Intents read off a locked handle. Anything an entry cannot be used
    for — corrupt JSON, a wrong shape, a field of the wrong type — is
    treated as no intent: losing an echo costs one redundant
    classification, while a traceback here would kill the hook cPanel is
    waiting on, and consume_intents is the first thing it calls."""
    f.seek(0)
    try:
        data = json.load(f)
        return [e for e in data
                if isinstance(e, dict)
                and isinstance(e.get("vhost"), str)
                and isinstance(e.get("version"), str)
                and isinstance(e.get("ts"), (int, float))]
    except (ValueError, TypeError):
        return []


def write_intents(f, data):
    f.seek(0)
    f.truncate()
    json.dump(data, f)


def add_intents(entries):
    # opened create-but-never-truncate: the journal may only be rewritten
    # under the lock (a "w" open would clobber it under a concurrent
    # consume_intents' feet). Expired entries are pruned on every write.
    ensure_state_dir()
    with open_private(INTENTS_PATH, "r+") as f:
        fcntl.flock(f, fcntl.LOCK_EX)
        now = time.time()
        data = [e for e in load_intents(f) if now - e["ts"] < INTENT_TTL]
        write_intents(f, data + list(entries))


def drop_intents(entries):
    """Retract intents whose write did not happen — a stale intent would
    swallow a real admin write of the same value as an echo."""
    pairs = {(e["vhost"], e["version"]) for e in entries}
    try:
        f = open(INTENTS_PATH, "r+")
    except OSError:
        return
    with f:
        fcntl.flock(f, fcntl.LOCK_EX)
        write_intents(f, [e for e in load_intents(f)
                          if (e["vhost"], e["version"]) not in pairs])


def consume_intents(vhosts, version):
    """The names in `vhosts` whose write of `version` was our own mirror
    echo, each one's entry removed. One read and one write of the journal
    for the whole event: per name, a bulk event read and rewrote it once
    per domain (found in review: our own write of 4,000 domains in one
    call spent 56 s of it in the hook cPanel holds open)."""
    try:
        f = open(INTENTS_PATH, "r+")
    except OSError:
        return set()
    with f:
        fcntl.flock(f, fcntl.LOCK_EX)
        wanted, ours, kept = set(vhosts), set(), []
        now = time.time()
        for entry in load_intents(f):
            if entry["vhost"] in wanted and entry["vhost"] not in ours \
                    and entry["version"] == version \
                    and now - entry["ts"] < INTENT_TTL:
                ours.add(entry["vhost"])
            else:
                kept.append(entry)
        if ours:
            write_intents(f, kept)
        return ours


def run(cmd, timeout=WHMAPI_TIMEOUT, env=None, quiet=False):
    """subprocess.run that always answers, on a known environment (and
    says so in the log when the child could not run, unless `quiet`).

    The event handler runs inside a cPanel request, so a wedged whmapi1 or
    selectorctl has to surface as a failed call rather than as a panel that
    never responds.

    These children run as root, and this process's environment is not
    trustworthy — a dispatch entry serves an in-cage caller's request, and
    what reaches the root child is proxyexec's whitelist of the caller's
    variables plus LSAPI_* imported from the caller's process; nothing
    scrubs it, so this pinning IS the defence. Our own interpreter ignores
    it (`-I`), but
    the selector CLIs are started
    `-sbb`, which drops the user site directory and not PYTHONPATH, so an
    inherited one would run a tenant's `sitecustomize` as root. Output is
    decoded as UTF-8 rather than by locale, because a stripped environment
    has none and cPanel's API messages are not ASCII."""
    try:
        return subprocess.run(cmd, capture_output=True, text=True,
                              encoding="utf-8", errors="replace",
                              timeout=timeout,
                              env=dict(SAFE_ENV, **(env or {})))
    except (OSError, subprocess.SubprocessError) as e:
        if not quiet:
            log("WARN %s failed to run: %s" % (cmd[0], e))
        # a timeout's own text is the whole argv, which names the domains a
        # call was for: what a caller passes on (a write's reason, sent to
        # Sentry) says only what happened (found in the final review)
        why = ("%s timed out after %s seconds"
               % (os.path.basename(str(cmd[0])), e.timeout)
               if isinstance(e, subprocess.TimeoutExpired) else str(e))
        return subprocess.CompletedProcess(cmd, 1, stdout="", stderr=why)


def whmapi(function, **params):
    cmd = [WHMAPI1, function, "--output=json"]
    cmd += ["%s=%s" % (k, v) for k, v in params.items()]
    out = run(cmd)
    try:
        return json.loads(out.stdout)
    except ValueError:
        # run() leaves the failure that produced no output in stderr (a
        # timeout, a missing binary); without it the log reads
        # "unparseable: " with nothing to diagnose
        return {"metadata": {"result": 0,
                             "reason": "unparseable: %s %s"
                             % (out.stdout[:200], out.stderr[:200])}}


def vhosts_of(user):
    vhosts = all_vhosts()
    if vhosts is None:
        return None
    return [v for v in vhosts if v.get("account") == user]


def all_vhosts():
    """Every vhost cPanel knows, or None when it did not answer.

    None is not []: a box with no vhosts is a real answer, and a failed
    or unparseable php_get_vhost_versions is not — read naively, a fleet
    report built on the non-answer would overwrite the standing drift
    evidence with an empty box, and a mirror pass would log a no-op that
    never was."""
    res = whmapi("php_get_vhost_versions")
    if res.get("metadata", {}).get("result") != 1:
        unreadable("listing", (res.get("metadata") or {}).get("reason"))
        return None
    # `"data": null` is a failure shape too, and .get's default only covers
    # a MISSING key — so coalesce before chaining. A success that carries no
    # versions list is malformed, i.e. another non-answer: None, not [].
    return (res.get("data") or {}).get("versions")


def php_conf_handlers():
    """{package: handler} for every row of cPanel's php.conf, or None when
    the file could not be read.

    A pin for a package without a row leaves Apache with no handler for
    the domain the moment the pin lands, so every write path holds such
    pins until the rows exist (cagefs writes them when it integrates a
    version with MultiPHP). The handler itself decides whether PHP
    Selector serves through it (Coverage).

    php.conf's `default:` row names the system default version rather than
    a handler, so it is left out: every value here has to be a handler, or
    the next reader asks Coverage about one and is answered with a version
    name."""
    try:
        with open(PHP_CONF) as f:
            rows = {}
            for line in f:
                if ":" in line and not line.lstrip().startswith("#"):
                    pkg, handler = line.split(":", 1)
                    if pkg.strip() != "default":
                        rows[pkg.strip()] = handler.strip()
            return rows
    except OSError as e:
        log("WARN php.conf unreadable: %s" % e)
        unreadable("web-server", e)
        return None


class _RoutesUnknown(object):
    """LiteSpeed is installed and what it can route to is not known."""

    def __repr__(self):
        return "<lsws routes unknown>"


ROUTES_UNKNOWN = _RoutesUnknown()


def lsws_handlers_from_log(path=None):
    """The packages LiteSpeed last built a PHP handler for, or None when
    the log holds no table.

    The LAST table in the file, not every match: a config load re-logs the
    whole set, so an upgrade that adds a version must not be read through
    the table that preceded it. One table is the lines within
    LSWS_TABLE_WINDOW of the newest — not a contiguous run, which a
    graceful restart's second worker interleaves (measured: reading it as
    a run returned one handler out of nineteen on a live box).

    A line whose timestamp cannot be read is dropped once any can be: it
    cannot be placed in a table, and guessing it into the newest one would
    admit a version an older LiteSpeed served and this one does not.

    The file is the web server's, not ours, so only a well-formed package
    name is taken from it (LSWS_HANDLER_RE) — a value read from here is
    compared against a pin, never interpolated into a path or a command.
    Its worst case is bounded in both directions: a forged line can add a
    package, which restores exactly today's behaviour for that package,
    or drop one, which withholds a mirror. Neither reaches past the
    domains whose pins the sync already owns."""
    if path is None:
        # read now, not when the module loaded: a default bound then
        # ignored the tests' redirect, so they read the host's live log
        path = LSWS_LOG
    seen, starts, ends = [], [], []
    try:
        # binary: a text stream may only seek to a cookie IT produced, and
        # this log carries request data, so an offset landing mid-character
        # must not decide whether the scan runs at all
        with open(path, "rb") as f:
            f.seek(0, os.SEEK_END)
            size = f.tell()
            f.seek(max(0, size - LSWS_LOG_TAIL))
            if size > LSWS_LOG_TAIL:
                f.readline()  # drop the partial line the seek landed in
            for raw in f:
                line = raw.decode("utf-8", "replace")
                found = LSWS_HANDLER_RE.match(line)
                if found and lsws_binary_ok(found.group(1), found.group(2)):
                    seen.append((_lsws_stamp(line), found.group(1)))
                elif LSWS_TABLE_END_RE.match(line):
                    ends.append(_lsws_stamp(line))
                elif LSWS_TABLE_START_RE.match(line):
                    starts.append(_lsws_stamp(line))
    except OSError as e:
        log("WARN LiteSpeed log unreadable: %s" % e)
        return None
    if not seen:
        return None
    stamps = [when for when, _ in seen if when is not None]
    if not stamps:
        # a log we do not recognise the shape of: no table can be placed
        return None
    newest = max(stamps)
    table = {pkg for when, pkg in seen
             if when is not None and newest - when <= LSWS_TABLE_WINDOW}
    for marks, why in ((starts, "its start is before the log tail"),
                       (ends, "it is still being written")):
        if not any(when is not None
                   and abs(when - newest) <= LSWS_TABLE_WINDOW
                   for when in marks):
            log("WARN LiteSpeed handler table ignored — %s" % why)
            return None
    return table


def lsws_binary_ok(pkg, binary):
    """The handler line names the binary that package installs, or it is
    not that package's row. A second, independent thing a forged line has
    to get right, and the one place the two halves of the row are checked
    against each other at all."""
    root = ("/opt/alt/php%s/" if pkg.startswith("alt-php")
            else "/opt/cpanel/ea-php%s/") % pkg.rsplit("php", 1)[1]
    return binary.startswith(root) and binary.endswith("/lsphp")


def _lsws_cached_routes():
    """The last table we stored, or None. Anything the file cannot be used
    for is no table: a corrupt copy must read as "not known" and withhold
    the mirror, never as a table that happens to be empty."""
    try:
        with open(LSWS_ROUTES_PATH) as f:
            handlers = json.load(f).get("handlers")
    except (OSError, ValueError, AttributeError):
        return None
    if not isinstance(handlers, list):
        return None
    packages = {h for h in handlers if isinstance(h, str)}
    return packages or None


def _lsws_stamp(line):
    """The line's log timestamp as seconds, or None when it has none."""
    found = LSWS_TS_RE.match(line)
    if not found:
        return None
    try:
        return time.mktime(time.strptime(found.group(1), "%Y-%m-%d %H:%M:%S"))
    except (ValueError, OverflowError):
        return None


def lsws_routes():
    """What the web server can route a vhost to: a set of packages,
    ROUTES_UNKNOWN when LiteSpeed is installed and that could not be
    learned, or None when it is not installed and the question does not
    arise.

    Not installed is read from LSWS_BIN rather than from any "LiteSpeed is
    running" signal: the only one of those available to us is a pid file
    in the world-writable temporary directory (see Coverage), and this
    must not be forgeable into the permissive answer. A box that carries
    the server at all is judged by its table, which is also the honest
    answer for one that can be switched back to it between passes — a pin
    written while Apache serves is still standing when LiteSpeed does."""
    if not os.path.exists(LSWS_BIN):
        return None
    cached = _lsws_cached_routes()
    found = lsws_handlers_from_log()
    if found:
        # only when it actually moved: read_coverage runs on the dry run
        # too, which promises to mutate nothing, and the table changes
        # only when LiteSpeed itself does
        if found != cached:
            try:
                ensure_state_dir()
                save_json(LSWS_ROUTES_PATH, {"handlers": sorted(found),
                                             "seen": time.strftime("%F %T")})
            except OSError as e:
                log("WARN LiteSpeed handler table not cached: %s" % e)
        return found
    if cached:
        return cached
    log("WARN LiteSpeed is installed and its PHP handler list could not be "
        "read (%s); no version will be mirrored until it can" % LSWS_LOG)
    unreadable("web-server", "LiteSpeed's PHP handler list")
    return ROUTES_UNKNOWN


def web_server_facts():
    """(suEXEC loaded, suPHP loaded), or None when the web server could
    not be read at all.

    Apache's own answer, read the way lve-utils reads it (`httpd -M`,
    matching `suexec_module` / `suphp_module` — see
    cldetectlib.detect_suEXEC_suPHP, which PHP Selector's usage statistics
    rest on), but through this module's run(): that pins SAFE_ENV for a
    root child, and bounds a wedged httpd inside the cPanel request this
    can run in. cldetectlib's own reader has neither, and it reports a
    failed httpd as "no modules" — which here would read as a definitive
    "no suEXEC" and suspend the sync on a box mid-rebuild. Empty is
    therefore no answer: an Apache that lists nothing does not exist.

    Nothing outside this listing is consulted, and in particular no
    LiteSpeed signal: see Coverage for why."""
    out = run([HTTPD, "-M"], timeout=HTTPD_TIMEOUT)
    modules = [word for word in
               (out.stdout.split() if out.returncode == 0 else [])
               if word.endswith("_module")]
    if not modules:
        log("WARN no Apache module list from %s (rc=%s): %s"
            % (HTTPD, out.returncode, out.stderr.strip()[:120]))
        unreadable("web-server", "rc=%s: %s" % (out.returncode,
                                                out.stderr.strip()[:120]))
        return None
    return "suexec_module" in modules, "suphp_module" in modules


def read_coverage():
    """The box's Coverage for one pass — one `httpd -M` and one php.conf
    read, however many accounts the pass judges — or None when the web
    server did not answer."""
    facts = web_server_facts()
    if facts is None:
        return None
    return Coverage(*facts, handlers=php_conf_handlers(),
                    routes=lsws_routes())


def system_default():
    # "data": null is how WHM reports some failures, and .get's default
    # only covers a MISSING key — so coalesce before chaining. An empty
    # default reads as "unknown", which every guard already refuses to act
    # on (selector_suspended).
    res = whmapi("php_get_system_default_version")
    version = (res.get("data") or {}).get("version", "")
    if not version:
        unreadable("default", (res.get("metadata") or {}).get("reason"))
    return version


USERDATADOMAINS = "/etc/userdatadomains"


def load_userdatadomains():
    """(alias_map, raw_pins) from /etc/userdatadomains (root-readable).

    raw_pins is None when the file could not be read OR yielded nothing.
    An empty map would be far worse than no map: every domain would look
    like `inherit`, every pin would look claimable, and one pass over a
    file caught mid-rewrite would steamroll every admin pin on the box."""
    try:
        with open(USERDATADOMAINS) as f:
            aliases, raw_pins = parse_userdatadomains(f.read().splitlines())
    except (OSError, UnicodeDecodeError) as e:
        log("WARN userdatadomains unreadable: %s" % e)
        unreadable("listing", e)
        return {}, None  # raw_pins None -> planner falls back to whmapi view
    if not raw_pins:
        log("WARN userdatadomains listed no versions — ignoring it this pass")
        unreadable("listing", "userdatadomains listed no versions")
        return aliases, None
    return aliases, raw_pins


def load_userdata_listing():
    """(aliases, raw_pins, vhosts) from one read of /etc/userdatadomains,
    vhosts as cPanel's listing gives them to an event's routing and the
    document-root walk ({"vhost", "account", "documentroot"}, parked
    domains and addons' own subdomains left out). For a hook that must not ask cPanel for its whole
    listing inside the request it serves (rejudge_parent_pins; found in
    review). vhosts is None when the file could not be read."""
    try:
        with open(USERDATADOMAINS) as f:
            lines = f.read().splitlines()
    except (OSError, UnicodeDecodeError) as e:
        log("WARN userdatadomains unreadable: %s" % e)
        unreadable("listing", e)
        return {}, None, None
    aliases, raw_pins = parse_userdatadomains(lines)
    vhosts = []
    for line in lines:
        if ": " not in line:
            continue
        name, rest = line.split(": ", 1)
        fields = rest.split("==")
        if len(fields) < USERDATA_FIELDS or fields[2] == "parked" \
                or name in aliases:
            # nor an addon's own subdomain: cPanel lists the addon, and
            # listed twice an event on it logged the subdomain as a
            # document-root sibling the event had not named (found in review)
            continue
        vhosts.append({"vhost": name, "account": fields[0],
                       "documentroot": fields[4]})
    return aliases, raw_pins or None, vhosts


def isolated_websites(user):
    """Domains of the user with per-website isolation enabled, or None when
    that cannot be determined.

    None is not the same answer as []: an isolated domain judged against the
    account version looks like a foreign pin, so a transient failure here
    would read as a takeover of the tenant's own domain."""
    try:
        from clcagefslib.webisolation.config import load_user_config
    except ImportError:
        return []  # isolation is not installed: nothing is isolated
    try:
        websites = list(load_user_config(user).enabled_websites)
    except Exception as e:
        log("WARN isolation state unavailable for %s: %s" % (user, e))
        return None
    if not websites and isolation_mounted(user):
        # cagefs reads a config it cannot parse as isolating nothing, while
        # the jail keeps the mounts it wrote at the last change: the
        # websites still run isolated. The bulk reader answers this as
        # unknown (PhpManager._website_versions); read as nothing here, the
        # account's own pass re-pinned its isolated websites to the
        # account version (found by Bugbot)
        log("WARN isolation config of %s lists nothing while its isolation "
            "mounts stand" % user)
        return None
    return websites


def isolation_mounted(user):
    """Whether cagefs still has isolation mounts written for the user — a
    second opinion on an empty isolation config only, so where it cannot be
    asked the config's answer stands (as PhpManager._isolation_mounted)."""
    try:
        from clcagefslib.webisolation.jail_utils import get_jail_config_path
    except ImportError:
        return False
    try:
        return get_jail_config_path(user).exists()
    except Exception:
        return False


def all_selector_versions(with_websites=False, user=None):
    """Every account's selector state in ONE call, or None when the
    selector did not answer at all.

    Returns {account: version} by default, and {account: (version,
    {website: version})} with with_websites — the isolated websites cost a
    CLI process each when asked separately (1.31s measured), which is the
    whole cost of a fleet walk on a box that isolates anything.

    The per-account query costs a CLI process each (0.4s measured), so a
    fleet walk of a few hundred accounts takes minutes — for a command an
    admin runs interactively. This form builds one version->users map for
    the whole box instead, and answers in well under a second.

    An account the answer does not cover is absent from the map, never
    defaulted: callers must treat that as unanswered. `native` mirrors as
    `inherit`, so an account wrongly read as native would plan an unpin of
    every domain the ledger proves we wrote. None (no answer at all) is
    likewise not {} (every account unanswered) — the first is a reading
    the caller must refuse to record, the second is a real finding. The
    same distinction holds per account for the websites: an account whose
    isolation set is unknown is answered as unanswered, not as isolating
    nothing.

    user narrows the question to one account, which is what a single
    account's own websites cost one call instead of one process each.
    """
    argv = [CL_SELECTOR, "get", "--json", "--interpreter", "php",
            "--get-current-version"]
    if user is not None:
        argv += ["--user", user]
    if with_websites:
        argv.append("--with-websites")
    out = run(argv, timeout=WHMAPI_TIMEOUT)
    try:
        if out.returncode != 0:
            raise ValueError("rc=%s" % out.returncode)
        users = json.loads(out.stdout)["users"]
        if not isinstance(users, dict):
            raise ValueError("no user map in the answer")
        if not with_websites:
            return dict((u, (d or {}).get("version") or None)
                        for u, d in users.items())
        state = {}
        for u, d in users.items():
            version = (d or {}).get("version") or None
            sites = (d or {}).get("websites")
            # an isolated website we cannot read is not "same as the
            # account": it has its own version, which is why it is
            # isolated, so nothing about this account may be judged. An
            # isolation set we were not told about at all is the same
            # refusal: {} means nothing is isolated, no map means no answer
            if not isinstance(sites, dict) or not all(sites.values()):
                version, sites = None, {}
            state[u] = (version, sites)
        return state
    except (ValueError, KeyError, AttributeError, TypeError) as e:
        log("WARN no fleet selector state (rc=%s): %s: %s"
            % (out.returncode, e, out.stderr.strip()[:120]))
        unreadable("selector", "%s: %s" % (e, out.stderr.strip()[:120]))
        return None


def selector_state(user):
    """(account-current, {isolated domain: per-domain current}), or
    (None, {}) when selectorctl did not answer, or (OUTSIDE_CAGEFS, {})
    when its answer is that the account is outside CageFS.

    An unanswered query must never read as `native`: `native` mirrors as
    `inherit`, so the pass would plan an unpin of every domain the ledger
    proves it wrote. selectorctl reports failures on stderr with a non-zero
    status and an empty stdout, which is exactly what a real `native`
    account does not look like (it prints `native`). Its refusal for an
    account outside CageFS is one line naming the account, and the one
    failure that is an answer: no warning, as on a box in CageFS's
    "Disable All" mode most accounts are outside it."""
    out = run([SELECTORCTL, "--user-current", "--user=%s" % user],
              timeout=SELECTOR_TIMEOUT)
    fields = out.stdout.split()
    if out.returncode != 0 or not fields:
        if out.returncode != 0 and not fields and (
                "ERROR:User %s not in CageFS" % user
                in (line.strip() for line in out.stderr.splitlines())):
            return OUTSIDE_CAGEFS, {}
        log("WARN no selector state for %s (rc=%s): %s"
            % (user, out.returncode, out.stderr.strip()[:120]))
        unreadable("selector", "rc=%s: %s" % (out.returncode,
                                              out.stderr.strip()[:120]))
        return None, {}
    account_current = fields[0]
    websites = isolated_websites(user)
    if websites is None:
        unreadable("selector", "isolated websites unknown")
        return None, {}
    if not websites:
        return account_current, {}
    # every isolated website in one call: asked one at a time they cost a
    # CLI process each, and this runs on the path a tenant's own version
    # change waits for. An account the narrowed answer refuses is refused
    # here too — an isolated domain read as the account's version would
    # overwrite the pin isolation exists to keep.
    state = all_selector_versions(with_websites=True, user=user)
    if not state or state.get(user, (None, {}))[0] is None:
        log("WARN no isolated website versions for %s" % user)
        unreadable("selector", "no isolated website versions")
        return None, {}
    return account_current, state[user][1]


def fleet_reading_of(user, vhosts, raw_pins, state):
    """`state`, the fleet reading of the account (all_selector_versions), or
    the account's own reading where a `native` there cannot be trusted.

    Found live on the review box: the fleet reading runs as root outside
    the cages and reads `native` for an account whose cage has no
    cl.selector directory, which CageFS rebuilds from the account's
    ~/.cl.selector/defaults.cfg only when it next enters its cage. The
    account's own reading enters the cage (selectorctl re-runs itself
    there), so it rebuilds the directory and answers with the real
    selection. native mirrors as inherit: trusted, the misreading unpins
    every mirror pin of ours on the account. So a `native` is confirmed
    where one of the account's domains is pinned to an alternative; a
    native account on the gateway, which a native reading leaves as it is,
    costs nothing."""
    if state is None or state[0] != "native":
        return state
    if not any(str((raw_pins or {}).get(v.get("vhost")) or "")
               .startswith("alt-php") for v in vhosts):
        return state
    return selector_state(user)


# --------------------------------------------------------------------------
# Selector -> MultiPHP: the mirror pass
# --------------------------------------------------------------------------

def written_of(doms, target):
    """Which of a failed batch's domains actually carry the pin now.

    cPanel writes each vhost of a `php_set_vhost_versions` batch separately
    but reports the whole call as failed if any one of them errored, and it
    refreshes the userdata cache before returning either way. Claiming none
    of them would leave real mirror pins unrecorded, and the next selector
    change would then read them as foreign and freeze those domains out of
    the sync.

    This covers the partial write only. A batch whose domain SET fails
    validation — one domain that no longer exists — is refused before
    anything is written, and this read then correctly reports nothing;
    apply_batch is what isolates the offender by splitting the batch."""
    _, pins = load_userdatadomains()
    if pins is None:
        return []
    return [d for d in doms if pins.get(d) == target]


def write_batch(target, doms, reason, owner, pins):
    """Set every domain in `doms` to `target` with ONE cPanel call, and
    return the ones that carry the pin afterwards.

    `owner` maps domain -> account. A single account's pass supplies the
    same account for every domain; the fleet pass supplies many, because
    php_set_vhost_versions takes one version and any number of vhosts,
    whoever owns them (measured: 72 vhosts across 72 accounts in one
    call). One version per call is the API's shape, not a choice —
    `vhost` is multivalued there and `version` is a scalar.

    `pins` is the pin map the pass planned from. It is read again right
    before the call, and a domain whose pin has moved since is left for
    the next pass, which judges it from what is there now: an admin pin
    set in between was otherwise overwritten and then claimed as ours. A
    re-read that fails holds the whole call: no reading is not "nothing
    moved". What remains is a write landing during our own call. The listener
    records that one as the admin's, and record_written keeps it; with
    multiphp-to-selector off nothing observes it.

    `pins` also supplies the audit line's old value, so the line names the
    value the decision was actually made against. (Not to be confused with
    the ledger's `was`, which is the pin a domain ARRIVED with; this is
    simply what each write is replacing, whoever put it there.)

    The intents go in before the call and the unwritten ones come back
    out after it: an intent left behind would swallow a later admin write
    of the same value as our own echo. They go in only while a direction
    is on. The hooks go with the last one (refresh_triggers), so with both
    off no event retires an intent - which is how --disable's hand-back
    used to leave one standing for INTENT_TTL.
    """
    _, now = load_userdatadomains()
    if pins is not None and now is None:
        log("MIRROR-HELD %d domain(s) -> %s: the pin map could not be read "
            "back before the write — left for the next pass (%s)"
            % (len(doms), target, ", ".join(sorted(doms)[:5])))
        return set()
    if pins is not None:
        moved = [d for d in doms if now.get(d) != pins.get(d)]
        for dom in moved:
            log("MIRROR-HELD user=%s domain=%s: its pin moved from %r to %r "
                "after the pass read it — left for the next pass"
                % (owner.get(dom), dom, pins.get(dom), now.get(dom)))
        doms = [d for d in doms if d not in moved]
    if not doms:
        return set()
    intents = []
    conf = load_conf()
    if "on" in (conf["selector_to_multiphp"], conf["multiphp_to_selector"]):
        intents = [{"vhost": d, "version": target, "ts": time.time()}
                   for d in doms]
        add_intents(intents)
    written = apply_batch(target, list(doms), reason, owner)
    for dom in doms:
        # the audit line's old value: absent from the map is not "no pin",
        # and a domain present with an empty version has one — say which
        old = (pins or {}).get(dom)
        old = "unread" if old is None else (old or "none")
        log("MIRROR user=%s domain=%s %s -> %s result=%s reason=%s"
            % (owner.get(dom), dom, old, target,
               "OK" if dom in written else "FAIL", reason))
        print("mirror: %s -> %s [%s]"
              % (dom, target, "OK" if dom in written else "FAILED"))
    missed = [i for i in intents if i["vhost"] not in written]
    if missed:
        drop_intents(missed)
    return written


def write_failure(why):
    """The daily report's code for the reason cPanel gave for a write it
    refused. cPanel's own text, so read by keyword; an unknown one is
    `other`, never guessed."""
    text = str(why or "").lower()
    if REJECTED_DOMAIN.lower() in text:
        return "rejected-domain"
    if "inherit-php-fpm" in text:
        return "fpm-inherit-missing"
    if "lock" in text:
        return "lock"
    if "timed out" in text or "timeout" in text:
        return "timeout"
    return "other"


def apply_batch(target, doms, reason, owner):
    """One php_set_vhost_versions call, with the two failure shapes.

    cPanel rejects a call two different ways, and they need different
    answers:

      * it wrote some and not others — the store is the authority, so
        written_of() re-reads /etc/userdatadomains and reports what
        actually landed (this is why the batch may span accounts: that
        read is global).
      * it wrote NOTHING because the domain set failed validation — a
        domain that no longer exists takes the whole call down before any
        write (measured: `Failed to find the domain(s)` out of
        Cpanel::PHP::Config::_get_php_conf, with both valid vhosts in the
        same call left untouched). One stale domain must not cost the
        fleet its convergence, so the batch is split in half and retried
        until the offender is alone.
      * it wrote NOTHING for a reason that is not about the domain set —
        the package is not installed, cPanel holds a lock, whmapi1 ran
        into its timeout. Every half would fail the same way, so the
        batch is given up for this round and retried whole by the next
        pass; halving would cost 2n-1 calls to learn nothing.

    The message is consulted only to tell those two apart (REJECTED_DOMAIN);
    the offender itself is found by halving, not parsed out, so nothing
    depends on the wording beyond that one word. Halving isolates an
    offender in log2(n) extra calls, per offender — k of them cost roughly
    k*log2(n/k) — so a chunk where most domains are stale is expensive.
    Still the right trade, because a healthy box has none: this domain
    list came from cPanel's own listing, read at the head of the chunk.
    """
    params = {"version": target}
    for i, dom in enumerate(doms):
        params["vhost-%d" % i] = dom
    res = whmapi("php_set_vhost_versions", **params)
    meta = res.get("metadata", {}) or {}
    if meta.get("result") == 1:
        # each call that writes rebuilds and restarts Apache: the daily
        # report counts them
        remember("write", "ok", target=target, domains=len(doms))
        return set(doms)
    why = meta.get("reason")
    log("MIRROR-FAIL -> %s (%d domains): %s" % (target, len(doms), why))
    print("mirror: batch %s failed: %s" % (target, why))
    written = set(written_of(doms, target))
    if written:
        remember("write", "partial", target=target, domains=len(written))
        remember("write-failed", write_failure(why), target=target,
                 domains=len(doms) - len(written), reason=why)
        return written
    if len(doms) == 1:
        # alone and still refused: this domain is the offender
        log("MIRROR-REJECT domain=%s user=%s -> %s: %s"
            % (doms[0], owner.get(doms[0]), target, why))
        remember("write-failed", write_failure(why), target=target,
                 domains=1, reason=why, user=owner.get(doms[0]), doms=doms)
        return set()
    if REJECTED_DOMAIN not in (why or ""):
        log("MIRROR-FAIL -> %s: batch-wide, %d domains left for the next "
            "pass" % (target, len(doms)))
        remember("write-failed", write_failure(why), target=target,
                 domains=len(doms), reason=why)
        return set()
    half = len(doms) // 2
    log("MIRROR-SPLIT -> %s: nothing written, retrying %d + %d"
        % (target, half, len(doms) - half))
    return (apply_batch(target, doms[:half], reason, owner)
            | apply_batch(target, doms[half:], reason, owner))


def record_released(user, doms, target, mode=None):
    """Record that a hand-back LANDED: the domain is MultiPHP's again, and
    the value it now carries is one WE wrote. mode: the coverage's
    `withdrawn` for the pass that wrote it (Coverage.withdrawn).

    After the write, never before. The `selector` row is the proof that the
    standing pin is ours, and dropping it at planning time stranded every
    withdrawal that failed or was held — unprovable, never retried, filed
    as an admin's decision the first time the selector version moved. Kept
    until the write lands, a failed one is simply re-planned next pass.

    The row is not bookkeeping for its own sake. A group with an FPM member
    has to be handed back to the NAMED default, and a named version stops
    being a gateway value the moment the system default moves; without this
    row such a domain would freeze as takeover-as-found. It also keeps the
    FPM branch from minting a `multiphp` row of its own over a pin that was
    ours.
    """
    now = time.strftime("%F %T")
    try:
        with updated_record(user) as rec:
            for dom in doms:
                entry = rec["domains"].get(dom, {})
                if entry.get("owner") == "multiphp" \
                        and entry.get("reason") != "released":
                    # an admin pinned the domain while our withdrawal was
                    # in flight. Their decision stands, exactly as
                    # record_written refuses to launder one in the other
                    # direction.
                    log("HANDBACK-OVERRODE user=%s domain=%s: an admin "
                        "pinned %s while the write was in flight; the "
                        "ledger keeps the admin's entry"
                        % (user, dom, entry.get("version")))
                    continue
                log("HANDBACK user=%s domain=%s -> %s (out of coverage, pin "
                    "returned to MultiPHP)" % (user, dom, target))
                row = {"owner": "multiphp", "reason": "released",
                       "version": target, "since": now}
                # the predecessor outlives the hand-back: what we WROTE is
                # not always what the domain arrived with (an FPM hand-back
                # names the default where `inherit` was), so re-deriving it
                # on the way back would record a domain that arrived
                # unpinned as having arrived on that default, and freeze it
                # there. A pin of ours whose claim was lost carries it in
                # its pending mark (effective_entry), which is newer than
                # the row's own: on a row an earlier hand-back left, the
                # row still names what that one restored, and the round
                # trip after this one handed back `inherit` where the
                # admin had since pinned the default (found in review).
                was, bare = entry.get("was"), entry.get("bare")
                pending = entry.get("pending")
                if isinstance(pending, dict) \
                        and isinstance(pending.get("was"), str):
                    was, bare = pending["was"], pending.get("bare")
                if was is not None:
                    row["was"] = was
                    if bare is not None:
                        row["bare"] = bare
                if mode != WITHDRAWING and isinstance(was, str) \
                        and from_pkg(was) is not None and target != was:
                    # an alt-php the domain arrived with, stepped aside to
                    # a value PHP Selector serves through (the named
                    # default, group_back): the value standing is still
                    # ours, until a pass re-pins it or a --disable restores
                    # what it arrived with. Found in review: released, the
                    # withdrawal found nothing to hand back where the new
                    # version could not be pinned, and the sync's ea-php83
                    # stayed. Not on a withdrawal, which gives back all it
                    # can: what it writes that is not what the domain
                    # arrived with is MultiPHP's (found in review: kept the
                    # sync's, a group whose arrivals disagree held every
                    # --disable after it, naming a pin on `inherit`).
                    row = dict(row, owner="selector", reason="step-aside")
                rec["domains"][dom] = row
    except RecordUnusable as e:
        # usable when the pass planned, and not since: the hand-backs stand
        # as written, and no release can go into this record
        log("HANDBACK-UNRECORDED user=%s domains=%s -> %s: %s"
            % (user, ",".join(sorted(doms)), target, e.note()))


def record_carried(user, doms, target, carried, default_pkg):
    """Record a write that LANDED on a domain the sync does not own, made
    only because it shares a document root with one it handed back
    (settle_groups, `carried`: {domain: its pin before}). cPanel writes
    such a group together, and its one .htaccess already ran that value.

    It is not a claim: the next pass treats it as anyone's pin. Onto a
    gateway value it is a hand-back's row, keeping the pin the domain had,
    so the Selector's re-mirror still knows what to hand back to; onto any
    other version it is MultiPHP's, as found. Found in review: claimed as
    ours, such a domain read as a stale mirror, and a --disable could never
    finish handing it back. `default_pkg` is the pass's own: read again
    per write, a reading that failed mid-pass recorded the mate as found
    (found in review)."""
    now = time.strftime("%F %T")
    try:
        with updated_record(user) as rec:
            for dom in doms:
                if is_gateway(target, default_pkg):
                    row = {"owner": "multiphp", "reason": "released",
                           "version": target, "since": now}
                    was = carried.get(dom)
                    if isinstance(was, str) and was:
                        row["was"] = was
                        if was == "inherit":
                            row["bare"] = isinstance(was, NoKey)
                else:
                    row = {"owner": "multiphp", "reason": "takeover-as-found",
                           "version": target, "since": now}
                rec["domains"][dom] = row
                log("HANDBACK user=%s domain=%s -> %s (shares its document "
                    "root with a domain handed back)" % (user, dom, target))
    except RecordUnusable as e:
        log("HANDBACK-UNRECORDED user=%s domains=%s -> %s: %s"
            % (user, ",".join(sorted(doms)), target, e.note()))


def document_roots(vhosts):
    """{domain: (account, document root)}, the root without a trailing
    slash."""
    roots = {}
    for v in vhosts:
        root = (v.get("documentroot") or "").rstrip("/")
        if root:
            roots[v["vhost"]] = (v.get("account"), root)
    return roots


def over_bare(doms, bare, roots):
    """The domains in `doms` whose document root holds a site in `bare`:
    one on `inherit` whose own pin did not land. A pin written above it
    would reach it (settle_nesting), so the write waits for the next pass
    (found in review: the website ran the main domain's version from the
    moment that pin landed)."""
    return [d for d in doms if d in roots and any(
        roots[n][0] == roots[d][0] and roots[n][1].startswith(roots[d][1] + "/")
        for n in bare if n in roots)]


def under_unlanded(doms, unlanded, roots):
    """The domains in `doms` whose document root lies inside that of a site
    in `unlanded`: one this pass meant to write and did not. Gone back to
    `inherit`, such a domain would run that site's standing pin instead of
    the one planned above it, so the hand-back waits for the next pass and
    the domain keeps the pin it has (order_writes writes the site above
    first)."""
    return [d for d in doms if d in roots and any(
        roots[n][0] == roots[d][0] and roots[d][1].startswith(roots[n][1] + "/")
        for n in unlanded if n in roots)]


def inherit_levels(runs, roots):
    """`runs` of (value, domains), each going back to `inherit` split into
    one call per level of nesting, the shallowest first: a domain's level
    is the number of document roots among its run's, of its account, that
    hold its own."""
    out = []
    for target, doms in runs:
        if target != "inherit":
            out.append((target, doms))
            continue
        held_by = {}
        for dom in doms:
            if dom in roots:
                held_by.setdefault(roots[dom][0], set()).add(roots[dom][1])
        levels = {}
        for dom in doms:
            level = 0
            if dom in roots:
                account, root = roots[dom]
                level = sum(1 for r in held_by[account]
                            if root.startswith(r + "/"))
            levels.setdefault(level, []).append(dom)
        out.extend((target, levels[n]) for n in sorted(levels))
    return out


def order_writes(plan, vhosts):
    """The plan's writes, one cPanel call per value, in an order that never
    shows a site anything but what it ran before or what it runs after.

    A site on `inherit` runs the nearest explicit pin above its document
    root (Apache's .htaccess cascade). Found live: the pass ending an
    isolation change pinned the main domain to the account's alt-php81
    before the isolated website inside its root, which stood on `inherit`
    after the release, and for 1.1 s the website ran 8.1 with the
    server-wide extensions instead of its own 8.2. So a site going onto a
    version of its own is written before a site above it, and one going
    back to `inherit` after.

    One call per value where those constraints allow it, as before; where
    they cannot be met that way (they cross between two values), one site
    at a time: the explicit pins deepest first, then the hand-backs to
    `inherit` shallowest first.

    Either way, hand-backs to `inherit` one inside another go in calls of
    their own, the shallowest first (inherit_levels). cPanel writes the
    sites of one call in an order of its own: found live, one call handing
    back the main domain and the isolated website inside its document root
    wrote the website first, and for a request it ran the main domain's
    alt-php81 with the server-wide extensions."""
    roots = document_roots(vhosts)
    target_of = {d: t for t, doms in plan.items() for d in doms}
    before = {t: set() for t in plan}   # value -> values written before it
    for child, c_target in target_of.items():
        for parent, p_target in target_of.items():
            if c_target == p_target or child not in roots \
                    or parent not in roots:
                continue
            (c_account, c_root), (p_account, p_root) = \
                roots[child], roots[parent]
            if c_account != p_account or not c_root.startswith(p_root + "/"):
                continue
            if c_target == "inherit":
                before[c_target].add(p_target)
            else:
                before[p_target].add(c_target)
    order, done = [], set()
    while len(order) < len(plan):
        ready = sorted(t for t in plan if t not in done and before[t] <= done)
        if not ready:
            break
        order.append(ready[0])
        done.add(ready[0])
    if len(order) == len(plan):
        return inherit_levels([(t, plan[t]) for t in order], roots)

    def key(dom):
        depth = roots.get(dom, (None, ""))[1].count("/")
        last = target_of[dom] == "inherit"
        return (last, depth if last else -depth, target_of[dom], dom)
    runs = []
    for dom in sorted(target_of, key=key):
        if runs and runs[-1][0] == target_of[dom]:
            runs[-1][1].append(dom)
        else:
            runs.append((target_of[dom], [dom]))
    return inherit_levels(runs, roots)


def record_written(user, doms, target, arrived=None):
    """Positive ledger: record what we wrote — the proof that lets a
    future pass re-pin these domains.

    `arrived` is the planner's map of domains whose standing pin is the
    one they ARRIVED with — NOT the pin map the pass planned from. The two
    differ on a re-pin, where the pin being replaced is our own mirror, and
    passing the wrong one records an alt-php as the value to hand back to:
    an alt-php served outside the cage. selector_claim no longer guards
    against that, because the planner is the only place that can tell the
    two apart, so this call site is where the rule lives."""
    now = time.strftime("%F %T")
    try:
        with updated_record(user) as rec:
            for dom in doms:
                entry = rec["domains"].get(dom, {})
                if entry.get("owner") == "multiphp" \
                        and entry.get("reason") != "released":
                    # plan_mirror never plans a domain an admin owns, so an
                    # owner here arrived AFTER planning: an admin pinned the
                    # domain while our call was in flight, and our write
                    # has just overridden it. Never launder that into a
                    # claim — keep the admin's entry, and --check reports
                    # the drift.
                    log("MIRROR-OVERRODE user=%s domain=%s: an admin pinned "
                        "%s while the write was in flight; the store now "
                        "holds %s and the ledger keeps the admin's entry"
                        % (user, dom, entry.get("version"), target))
                    # without our pending mark: the pin is the admin's
                    rec["domains"][dom] = dict(
                        (k, v) for k, v in entry.items() if k != "pending")
                    continue
                rec["domains"][dom] = selector_claim(
                    entry, target, now, (arrived or {}).get(dom))
    except RecordUnusable as e:
        # usable when the pass planned, and not since: the pins stand as
        # written, and no claim can go into this record
        log("MIRROR-UNCLAIMED user=%s domains=%s -> %s: %s"
            % (user, ",".join(sorted(doms)), target, e.note()))


def record_pending(user, plan, releases, arrived, carried=()):
    """Mark every write the plan claims as pending, with what it replaces:
    under the record lock, before the write (see effective_entry). Found in
    review: the claim was recorded only once the write had landed, so a pass
    that died in between left a pin of ours with no row to prove it.

    Hand-backs are not marked. Their row is replaced only once they land
    (record_released), and one that landed unrecorded already stands at the
    value the domain arrived with. Nor is a member written only with its
    group (`carried`): a mark would make it ours. False when the record is unusable (it
    was usable when the pass planned): nothing is then written for the
    account."""
    now = time.strftime("%F %T")
    try:
        with updated_record(user) as rec:
            for target, doms in plan.items():
                for dom in doms:
                    if dom in releases or dom in carried:
                        continue
                    entry = rec["domains"].get(dom, {})
                    claim = selector_claim(entry, target, now,
                                           (arrived or {}).get(dom))
                    mark = dict(entry)
                    mark["pending"] = {"version": target,
                                       "was": claim.get("was"), "since": now}
                    if "bare" in claim:
                        mark["pending"]["bare"] = claim["bare"]
                    rec["domains"][dom] = mark
    except RecordUnusable as e:
        log("MIRROR-SKIP user=%s — %s" % (user, e.note()))
        return False
    return True


def drop_pending(user, doms):
    """A write that did not land leaves no mark behind."""
    if not doms:
        return
    try:
        with updated_record(user) as rec:
            for dom in doms:
                entry = rec["domains"].get(dom)
                if not entry or "pending" not in entry:
                    continue
                entry = dict((k, v) for k, v in entry.items() if k != "pending")
                if entry:
                    rec["domains"][dom] = entry
                else:
                    del rec["domains"][dom]
    except RecordUnusable:
        pass  # nothing may write it (logged by load_record)


def mirror(user, reason="manual", vhosts=None, dry_run=False, coverage=None,
           default_pkg=None, selector=None, raw_pins=None, trace_noop=True,
           aliases=None):
    """Complete Selector -> MultiPHP pass for one account. Returns True
    when at least one pin was written.

    vhosts: the account's whmapi entries, passed by reconcile() which
    already holds the box-wide list; fetched here otherwise.
    coverage: the box's Coverage (read_coverage), likewise passed by
    reconcile() so the fleet reads Apache and php.conf once; read here
    otherwise.
    default_pkg: read once by the fleet pass. A change to it mid-pass
    fires its own event and its own convergence, so a pass may judge from
    the default it started with.
    selector / raw_pins: the same hoisting, and a DRY RUN only — a preview
    changes nothing, so one reading of the box serves every account. The
    fleet's writing path is write_chunk, which takes both fresh per chunk;
    a single-account writing pass fetches them here itself.
    dry_run: print what the pass would write; change nothing, not even
    ledger records, and ignore the kill switch — the preview exists to be
    read before enabling.
    trace_noop: False inside a burst of the tenant door's passes
    (guarded_mirror). The state lines of a pass that changes nothing — a
    suspension, an unreadable reading, no change to make — are then left
    out: the burst's first pass said it, and a tenant looping the door must
    not repeat it into the log every DOOR_PACE (found in review). Every
    write, hold and hand-back is still logged."""
    say = log if trace_noop else (lambda line: None)
    if not dry_run and load_conf()["selector_to_multiphp"] != "on":
        print("selector-to-multiphp syncing is off — no changes made")
        log("mirror %s: skipped — selector-to-multiphp is off" % user)
        return False
    if default_pkg is None:
        default_pkg = system_default()
    if selector_suspended(default_pkg) and not (coverage and
                                                coverage.withdrawn):
        # A withdrawal is exempt, here as in _reconcile_pass: the guard is
        # for the gateway rule, which a withdrawal never applies. Without
        # the exemption HERE too, the fleet preview — which walks accounts
        # through this function — printed a successful EMPTY plan on the
        # same boxes the pass had just been fixed to finish, so an
        # operator reading `--disable --dry-run` saw nothing to hand back
        # while every pin was still standing. Only a caller that supplies
        # a withdrawn coverage is exempt; a withdrawal always does.
        say("mirror %s: suspended — the selector is disabled by the system "
            "default (%r)" % (user, default_pkg))
        return False
    if coverage is None:
        coverage = read_coverage()
    if coverage is None:
        # a preview that changed nothing must say why; the hook and the
        # tenant door get the log line, as the suspension above does
        if dry_run:
            print(NO_WEB_SERVER)
        say("mirror %s: aborted — %s" % (user, NO_WEB_SERVER))
        return False
    if coverage.inert:
        # The pass still runs, and on such a box plan_mirror can only plan
        # hand-backs: every domain reads inert, so nothing is mirrored and
        # the only writes are pins of ours going back. Returning here
        # instead would leave exactly the server-wide case — a box that
        # lost suEXEC after mirroring — as the one that never recovers.
        # The withdrawal reaches this branch too, and says what it is once
        # for the walk (_reconcile_pass): this banner would say of the box
        # something that is not true there.
        if dry_run and not coverage.withdrawn:
            print(INERT_BANNER % coverage.inert)
        say("mirror %s: suspended — %s; handing back any pin of ours"
            % (user, coverage.inert))
    account_current, isolated = (selector if selector is not None
                                 else selector_state(user))
    if account_current is None:
        if not coverage.withdrawn:
            say("mirror %s: aborted — no selector state to mirror" % user)
            return False
        # a withdrawal reads no selector version (see write_chunk); this
        # is the preview path, and it must be readable on a box where
        # that reading fails
        account_current, isolated = "native", {}
    if raw_pins is None:
        aliases, raw_pins = load_userdatadomains()
    if vhosts is None:
        vhosts = vhosts_of(user)
    if vhosts is None:
        say("mirror %s: aborted — no vhost list from cPanel" % user)
        return False
    if not dry_run:
        snapshot_fpm_pools(user, vhosts)
    if dry_run:
        try:
            record = load_record(user)
        except RecordUnusable as e:
            print("skip:   every domain of %s (%s)" % (user, e.note()))
            return False
        moved = []
        plan, skips, _ = plan_mirror(
            vhosts, account_current, isolated, default_pkg,
            record, raw_pins=raw_pins, coverage=coverage, aliases=aliases,
            moved=moved)
        plan = hold_unservable(plan, user, coverage.handlers)
        for old, new in moved:
            print("would carry: the row of %s to %s, the addon parked on it"
                  % (old, new))
        for dom, why in skips:
            print("skip:   %s (%s)" % (dom, why))
        for target, doms in sorted(plan.items()):
            for dom in doms:
                print("would set: %s -> %s" % (dom, target))
        return False
    # Plan and persist the non-write ledger mutations under the lock, but
    # NEVER run an external command while holding it: php_set_vhost_versions
    # raises our own hook synchronously, and on an echo miss the handler
    # needs this very lock — holding it across the write would deadlock.
    # Every read the plan needs is therefore taken before the lock.
    releases, arrived, carried = set(), {}, {}
    with record_lock(user):
        try:
            record = own_record(user)
        except RecordUnusable as e:
            print("skip:   every domain of %s (%s)" % (user, e.note()))
            log("mirror %s: skipped — %s" % (user, e.note()))
            return False
        before, moved = json.dumps(record, sort_keys=True), []
        plan, skips, record = plan_mirror(
            vhosts, account_current, isolated, default_pkg, record,
            raw_pins=raw_pins, coverage=coverage, releases=releases,
            arrived=arrived, carried=carried, aliases=aliases, moved=moved)
        # only when the planning actually recorded something, as the fleet
        # pass does: since an inert box now runs the pass rather than
        # returning early, an unconditional save would create — and fsync —
        # a record for every account on a box where nothing can happen
        if json.dumps(record, sort_keys=True) != before:
            save_record(user, record)
            log_carried(moved)
    plan = hold_unservable(plan, user, coverage.handlers)
    for dom, why in skips:
        print("skip:   %s (%s)" % (dom, why))
    if not plan:
        # a pass that writes nothing must still leave a trace — an invisible
        # no-op is indistinguishable from a dispatch that never arrived —
        # except inside a burst of the tenant door's (guarded_mirror), where
        # the first one already says so
        say("MIRROR-PASS user=%s skipped=%d writes=0 reason=%s"
            % (user, len(skips), reason))
        return False
    if not record_pending(user, plan, releases, arrived, carried):
        return False
    wrote = False
    owner = dict.fromkeys(
        (d for doms in plan.values() for d in doms), user)
    roots, bare, unlanded, claims = document_roots(vhosts), set(), set(), {}
    for target, doms in order_writes(plan, vhosts):
        held = over_bare(doms, bare, roots) \
            if from_pkg(target) is not None else []
        if held:
            log("MIRROR-HOLD user=%s -> %s: %s, above a site whose own pin "
                "did not land" % (user, target, ",".join(held)))
        below = under_unlanded(doms, unlanded, roots) \
            if target == "inherit" else []
        if below:
            log("MIRROR-HOLD user=%s -> inherit: %s, below a site whose own "
                "write did not land" % (user, ",".join(below)))
        held += below
        doms = [d for d in doms if d not in held]
        written = write_batch(target, doms, reason, owner, raw_pins) \
            if doms else []
        unlanded.update(d for d in doms + held if d not in written)
        drop_pending(user, [d for d in doms + held if d not in written
                            and d not in releases and d not in carried])
        if from_pkg(target) is not None:
            bare.update(d for d in doms if d not in written
                        and (raw_pins or {}).get(d) == "inherit")
        if written:
            wrote = True
            record_landed(user, written, target, releases, arrived, carried,
                          default_pkg)
            claims.update((d, target) for d in written
                          if d not in releases and d not in carried)
    if back_at_arrival(user, claims, roots):
        # guarded_mirror serves it at once, as a request left mid-pass
        leave_request(user, reason, REJUDGE_BELOW)
    return wrote


# leave_request's reason for the pass back_at_arrival asks for
REJUDGE_BELOW = ("a pin of the sync's is back at what its domain arrived "
                 "with; the sites below it are judged again")


def back_at_arrival(user, claims, roots):
    """Whether a pin of ours this pass wrote (claims: {domain: value}) is
    back at the alt-php its domain arrived with, which makes it MultiPHP's
    from the next pass (arrived_pin_stands), with another site of the
    account in or below its document root. From then on such a
    site runs that pin on `inherit`, as without the sync, but the pass
    judged it by what stood there before: the named default of a step-aside,
    or another alt-php of ours, each read as the Selector's (nosync_pins).
    So the next pass judges it again. Found by a sequence fuzzer: an
    isolation turned off took the main domain back to its alt-php81, and
    the website below it on `inherit` kept the sync's pin of its own 8.0
    until the daily run, which then moved it to 8.1."""
    if not claims:
        return False
    try:
        entries = load_record(user)["domains"]
    except RecordUnusable:
        return False  # its pins stand as written: nothing can be judged
    for dom, target in claims.items():
        row = entries.get(dom) or {}
        if from_pkg(target) is None or row.get("owner") != "selector" \
                or not row.get("version") == row.get("was") == target \
                or dom not in roots:
            continue
        account, root = roots[dom]
        if any(other != dom and o_account == account
               and (o_root == root or o_root.startswith(root + "/"))
               for other, (o_account, o_root) in roots.items()):
            return True
    return False


def record_landed(user, written, target, releases, arrived, carried,
                  default_pkg, mode=None):
    """Record the writes of one cPanel call that landed for one account:
    claims, hand-backs (`releases`) and group-mates written with them
    (`carried`, judged by the pass's `default_pkg`). mode: the coverage's
    `withdrawn` (record_released)."""
    claimed = [d for d in written if d not in releases and d not in carried]
    freed = [d for d in written if d in releases]
    moved = [d for d in written if d in carried]
    if claimed:
        record_written(user, claimed, target, arrived)
    if freed:
        record_released(user, freed, target, mode)
    if moved:
        record_carried(user, moved, target, carried, default_pkg)


def snapshot_fpm_pools(user, vhosts):
    """Keep a copy of every FPM domain's pool configuration.

    Disabling PHP-FPM makes cPanel delete the domain's pool yaml,
    destroying custom tuning (workers, limits). The copy under
    _fpm-pools/ lets an operator restore that tuning; the sync itself
    never writes it back. Refreshed whenever a pass sees the domain on
    FPM, kept after the domain leaves it."""
    for v in vhosts:
        if not v.get("php_fpm"):
            continue
        dom = v["vhost"]
        # The name is interpolated into both paths below and the write is
        # root-owned, so it is checked before it becomes a path component —
        # the reason the account namespace has ACCOUNT_NAME ("the character
        # set keeps a name from becoming a path"). Defence in depth: cPanel
        # validates its own vhost names, and this only bites if it hands us
        # one it should not.
        if "/" in dom or dom in ("", ".", ".."):
            log("FPM-POOL snapshot skipped, unusable domain name: %r" % dom)
            continue
        # The snapshot is operator convenience — the sync never writes a
        # pool back — so no failure here may stop the pass that follows:
        # inside a reconcile that would abort every remaining account.
        # Anything can fail (a full disk, a pool yaml that is not UTF-8),
        # so this catches broadly and records what was lost.
        try:
            try:
                with open(FPM_POOL_SRC % (user, dom)) as f:
                    content = f.read()
            except OSError:
                continue
            dst = pool_path(user, dom)
            try:
                with open(dst) as f:
                    if f.read() == content:
                        continue
            except OSError:
                pass
            os.makedirs(os.path.dirname(dst), mode=0o700, exist_ok=True)
            with open_private(dst, "w") as f:
                f.write(content)
            log("FPM-POOL snapshot saved: %s" % dst)
        except Exception as e:
            log("FPM-POOL snapshot failed for %s/%s: %s" % (user, dom, e))


def hold_unservable(plan, user, handlers):
    """Drop planned pins whose package has no handler row in php.conf —
    Apache could not serve them (see php_conf_handlers). Unpinning to
    `inherit` restores the default chain and needs no row. `handlers` is
    Coverage.handlers — the php.conf rows, None if the file was unreadable
    (then every non-inherit pin is held); the caller reads it, so a fleet
    pass reads php.conf once rather than per account."""
    targets = [t for t in plan if t != "inherit"]
    if not targets:
        return plan
    for target in targets:
        if handlers is None or target not in handlers:
            doms = plan.pop(target)
            log("MIRROR-HOLD user=%s -> %s: no php.conf handler (%s)"
                % (user, target, ",".join(doms)))
            print("hold:   %s -> %s (no php.conf handler)"
                  % (",".join(doms), target))
    return plan


# --------------------------------------------------------------------------
# Stepping aside for a PHP Selector change
# --------------------------------------------------------------------------
#
# CageFS gives an account's PHP Selector extensions to its SELECTED version
# only; every other alt-php version loads the server-wide set. A pin of
# ours left on the version an account is leaving therefore serves that
# version with the server-wide set from the moment PHP Selector switches
# until the next pin lands (measured: 33 extensions against 66, PDO
# missing, for about a second — and for good when the write failed). So a
# change goes: release (hand our pins back to a value the Selector serves
# through, and hold the account's passes off), the switch, then the pass
# that ends the change (guarded_mirror's after_change) writes the new
# version. Every step serves exactly what the site would serve without the
# sync.

def standing_of_ours(user, vhosts=None, adopted=True):
    """The account's domains that still carry an alt-php pin of ours: the
    pins a PHP Selector change would strand on the version the account is
    leaving. None when that cannot be told, because the record is unusable.

    Read from the ledger and the pin map, with no external command, so the
    common case of nothing standing costs a tenant's change nothing more.
    A pin nobody read counts when the ledger claims an alt-php there,
    since unknown is not handed back. Given `vhosts` (cPanel's listing),
    only domains cPanel still lists count: the ledger keeps a removed
    domain's row until the next fleet pass prunes it, and that row must not
    stop the account's changes until then. adopted=False leaves out a pin
    the domain arrived with (`was` equal to it), set in MultiPHP Manager:
    the planning that read it has made it MultiPHP's (arrived_pin_stands),
    and it stops no change (left_standing)."""
    try:
        entries = load_record(user)["domains"]
    except RecordUnusable:
        return None
    if not entries:
        return []
    aliases, raw_pins = load_userdatadomains()
    listed = None if vhosts is None else {v["vhost"] for v in vhosts}
    if listed is not None:
        # an addon's row still under the subdomain it was made on is the
        # addon's (carry_addon_rows): a release must count its pin
        carry_addon_rows(entries, listed, aliases)
    standing = []
    for dom, entry in sorted(entries.items()):
        if listed is not None and dom not in listed:
            continue
        raw_pin = (raw_pins or {}).get(dom)
        if raw_pin is None:
            claims = [entry.get("version")] \
                if entry.get("owner") == "selector" else []
            pending = entry.get("pending")
            if isinstance(pending, dict):
                claims.append(pending.get("version"))
            if any(isinstance(c, str) and from_pkg(c) for c in claims):
                standing.append(dom)
            continue
        row = effective_entry(entry, raw_pin)
        if row.get("owner") == "selector" and row.get("version") == raw_pin \
                and from_pkg(raw_pin) and (adopted or row.get("was") != raw_pin):
            standing.append(dom)
        elif entry.get("restored") and from_pkg(raw_pin):
            # an alt-php back from a backup over a domain a restore's start
            # handed back may be the sync's own pin: until the claim its
            # flag is for (handle_restore), a change must not go ahead
            # under it (found in review)
            standing.append(dom)
    return standing


def held_from_changes(user):
    """Why a PHP Selector change of the account must wait, or None: the
    sync cannot tell its own pins there yet. Found in review: WHM's Modify
    Account renames the domains before its end carries their rows
    (modifying), and a restore brings the sync's own pins back from its
    backup, which only its end tells from an admin's (restored flags); a
    change let through left them on the version the account had left."""
    if modifying(user):
        return Why("the account is being modified in WHM; try again once it "
                   "ends", "modifying")
    if restoring(user) and restored_flags(user):
        return Why("the account is being restored, and the sync's own "
                   "versions come back with it; try again once it ends",
                   "restoring")
    return None


def release_held(users, reason, pace=False, withdrawn=RELEASING, whole=True,
                 written=None):
    """Hand every alt-php pin of ours on `users` back, in one cPanel call
    per value; the caller holds each account's pass lock. Returns
    {account: why} for the accounts whose pins could not all be handed
    back. written: out, a list the number of accounts whose hand-backs
    were written is appended to (settle_for_lsws).

    whole: an account is handed back whole or not at all, as a change that
    cannot go ahead must not cost two Apache rebuilds (write_chunk). Not
    for a restore, which is never refused: one document-root group that
    cannot move held every hand-back of its account (found in review).

    withdrawn: RELEASING hands back to values PHP Selector serves through
    (handback_by_group), for a change. WITHDRAWING hands back exactly as a
    --disable still walking the fleet would, for a change made while that
    walk has yet to reach the account (release).

    A suspended Selector (an alt-php system default) serves nothing, so a
    release has nothing to step aside from: `inherit` would run that
    default instead of our pin. An unreadable default is not that: no
    answer is not "suspended" (found in review: a whmapi timeout let the
    change through with every pin of ours standing). pace: a tenant's
    change, which waits out DOOR_PACE before anything that reads cPanel or
    writes, and only when there is something to hand back: nothing
    standing costs no external command."""
    unusable = Why("its ownership record is unusable", "record-unusable")
    candidates, stuck = [], {}
    for user in users:
        why = withdrawn == RELEASING and held_from_changes(user)
        if why:
            stuck[user] = why
            continue
        standing = standing_of_ours(user)
        if standing is None:
            stuck[user] = unusable
        elif standing:
            candidates.append(user)
    if not candidates:
        return stuck
    if pace:
        for user in candidates:
            pace_sleep(user, release_stamp_path(user))
            try:
                with open_private(release_stamp_path(user), "w"):
                    pass
            except OSError:
                pass  # unpaced is the old behaviour, not a refusal
    releasing = withdrawn == RELEASING
    default_pkg = system_default()
    if releasing and not default_pkg:
        stuck.update(dict.fromkeys(candidates, Why(
            "the system default PHP version could not be read",
            "default-unreadable")))
        return stuck
    if releasing and selector_suspended(default_pkg):
        if not pace:  # a tenant's can be looped through the door
            log("RELEASE nothing to hand back — the selector is disabled by "
                "the system default (%r)" % default_pkg)
        return stuck
    vhosts = all_vhosts()
    if vhosts is None:
        stuck.update(dict.fromkeys(candidates, Why("no vhost list from cPanel",
                                                   "no-listing")))
        return stuck
    by_user = {user: [v for v in vhosts if v.get("account") == user]
               for user in candidates}
    candidates = [user for user in candidates
                  if standing_of_ours(user, by_user[user])]
    if not candidates:
        return stuck
    coverage = read_coverage()
    if coverage is None:
        if releasing:
            # A change judges which sites the Selector serves (a group's
            # shield, an alt-php arrival through the gateway), which an
            # unread module list cannot answer: taken for "neither suEXEC
            # nor suPHP", every site counted as unserved, and a pin of ours
            # went back to the alt-php its domain arrived with (found in
            # the final review). Refused, as a pass aborts.
            stuck.update(dict.fromkeys(candidates, Why(
                NO_WEB_SERVER, "web-server-unreadable")))
            return stuck
        # A withdrawal's walk for these accounts. It needs no coverage
        # facts, only php.conf's handler table, so an Apache that will not
        # list its modules does not stop it.
        coverage = Coverage(False, False, php_conf_handlers())
    refused = {}
    wrote, _ = write_chunk(candidates, by_user, default_pkg,
                           coverage._replace(withdrawn=withdrawn), reason,
                           held=True, refused=refused if whole else None)
    if written is not None:
        written.append(wrote)
    for user in candidates:
        if user in refused:
            # planned and left as it is: a pin of ours would have stayed
            # (a document-root group it cannot move), so nothing was
            # handed back for a change that cannot go ahead
            stuck[user] = refused[user]
            continue
        standing = standing_of_ours(user, by_user[user], adopted=False)
        if standing is None:
            stuck[user] = unusable
        elif standing:
            stuck[user] = Why("a pin of the sync's still stands on %s%s" % (
                ", ".join(standing[:5]),
                " and %d more" % (len(standing) - 5) if len(standing) > 5
                else ""), "handback-failed")
    return stuck


def _refused(user, why, quiet):
    """Say why a change must not go ahead: on stdout for the client to
    carry to its caller, and in the log for root's (quiet: a tenant's,
    which the door can loop). The daily report counts either by why's code
    (remember)."""
    print("RELEASE-REFUSED: %s" % why)
    if not quiet:
        log("RELEASE-REFUSED user=%s — %s" % (user, why))
    remember("change-refused", getattr(why, "code", "other"), user=user,
             why=str(why))


def settle_for_lsws(written, users=()):
    """After a release's hand-backs (`written`, release_held's counts),
    wait until LiteSpeed serves them (LSWS_HTACCESS_SETTLE), so the switch
    the release steps aside for comes after. One that wrote nothing waits
    out a hand-back another writer landed on `users` moments before (a
    release ahead of it, the --disable walk, a pass): found in the final
    review, it returned at once and its switch came first. Where LiteSpeed
    is installed, read from LSWS_BIN as lsws_routes does: whether it is the
    server that runs cannot be read unforgeably, and a box running Apache
    only waits."""
    if not os.path.exists(LSWS_BIN):
        return
    if any(written):
        time.sleep(LSWS_HTACCESS_SETTLE)
        return
    landed = last_handback(users)
    if landed is not None:
        # a row's `since` is to the second: the margin covers the fraction
        wait = LSWS_HTACCESS_SETTLE + 1 - (time.time() - landed)
        if wait > 0:
            time.sleep(wait)


def last_handback(users):
    """When the newest hand-back on `users` landed, as its row says
    (record_released, record_carried: `since`), or None."""
    newest = None
    for user in users:
        try:
            rows = load_record(user)["domains"]
        except RecordUnusable:
            continue
        for row in rows.values():
            if not isinstance(row, dict) or row.get("reason") != "released":
                continue
            try:
                landed = time.mktime(time.strptime(
                    str(row.get("since")), "%Y-%m-%d %H:%M:%S"))
            except (ValueError, OverflowError):
                continue
            newest = landed if newest is None else max(newest, landed)
    return newest


def release(user, token, reason="selector-change", pace=False, door=False,
            owner=None):
    """Step aside for a PHP Selector change on one account: record the
    change (begin_change), wait for a pass that is still writing, and hand
    every alt-php pin of ours back. True when the change may go ahead; the
    caller then switches and ends the change with the pass that writes the
    new version (guarded_mirror's after_change), which also puts back what
    a refused release had handed back. A refusal writes nothing more
    itself: a re-pin there named the version the account is leaving while
    another change of its own was released and not yet switched (found in
    review).

    While the mirror is off nothing re-pins, so no change is recorded; but
    while a hand-back is under way or due (withdrawal_due) the account is
    handed back first, as that walk would, or its pins of ours would strand
    on the version it is leaving.

    door: a tenant's, through the door, under MAX_CHANGES, and quiet: a
    refusal is not logged, and a release that writes nothing never is.
    owner: the process the change lasts as long as (begin_change)."""
    if load_conf()["selector_to_multiphp"] != "on":
        if not withdrawal_due():
            return True  # nothing of ours is in the way, and nothing writes
        withdrawn, recorded = WITHDRAWING, False
    else:
        if not begin_change(user, token, capped=door, owner=owner):
            _refused(user, Why(
                "the change could not be recorded"
                + (" (%d already in flight)" % MAX_CHANGES if door else ""),
                "change-cap" if door else "change-unrecorded"), quiet=door)
            return False
        withdrawn, recorded = RELEASING, True
    written = []
    with path_lock_wait(pass_lock_path(user), CHANGE_LOCK_WAIT) as acquired:
        stuck = (release_held([user], reason, pace, withdrawn, written=written)
                 if acquired
                 else {user: Why("a pass held the account for %ds"
                                 % CHANGE_LOCK_WAIT, "pass-held")})
    if stuck:
        if recorded:
            end_change(user, token)
        _refused(user, stuck[user], quiet=door)
        return False
    settle_for_lsws(written, [user])
    if recorded:
        refresh_change(user, token)
    return True


def release_many(users, token, reason="bulk-version-change", owner=None):
    """release() for many accounts, one cPanel call per hand-back value per
    RECONCILE_CHUNK of them: a bulk move would otherwise hand back and
    rebuild Apache configuration once per account, and holding every
    account's lock at once ran out of descriptors on a large box (found in
    review). Returns {account: why} for those whose change must not go
    ahead; their changes are ended. What they had handed back is re-pinned
    by the pass that follows every bulk move (notify_bulk_change)."""
    if load_conf()["selector_to_multiphp"] != "on":
        if not withdrawal_due():
            return {}
        withdrawn, recorded = WITHDRAWING, False
    else:
        withdrawn, recorded = RELEASING, True
    users = sorted(set(users))
    refused, written = {}, []
    for start in range(0, len(users), RECONCILE_CHUNK):
        chunk = users[start:start + RECONCILE_CHUNK]
        if recorded:
            for user in chunk:
                if not begin_change(user, token, owner=owner):
                    refused[user] = Why("the change could not be recorded",
                                        "change-unrecorded")
        # sorted, so two bulk moves waiting for the same accounts cannot
        # each hold what the other waits for
        with contextlib.ExitStack() as stack:
            held = []
            for user in chunk:
                if user in refused:
                    continue
                if stack.enter_context(path_lock_wait(pass_lock_path(user),
                                                      CHANGE_LOCK_WAIT)):
                    held.append(user)
                else:
                    refused[user] = Why("a pass held the account for %ds"
                                        % CHANGE_LOCK_WAIT, "pass-held")
            refused.update(release_held(held, reason, withdrawn=withdrawn,
                                        written=written))
        if recorded:
            for user in chunk:
                if user in refused:
                    end_change(user, token)
                else:
                    refresh_change(user, token)
    # once for every chunk: no account is switched before release_many
    # returns
    settle_for_lsws(written, users)
    if refused:
        log("RELEASE-REFUSED %d account(s) of a bulk change: %s"
            % (len(refused), "; ".join("%s: %s" % (u, refused[u])
                                       for u in sorted(refused)[:10])))
        # a count per code, not a line per account: a bulk move refused on
        # a large box would fill the day's reports
        counts = {}
        for why in refused.values():
            code = getattr(why, "code", "other")
            counts[code] = counts.get(code, 0) + 1
        for code in sorted(counts):
            remember("change-refused", code, accounts=counts[code],
                     change=reason)
    return refused


def reconcile(dry_run=False, reason="reconcile", withdraw=False):
    """Fleet convergence, one pass at a time.

    A dry run mutates nothing, so it is never blocked (and never blocks):
    an admin must always be able to read the plan. A real pass takes the
    fleet lock and gives up at once if another pass holds it — the state
    that pass is converging is the state this call would converge.

    withdraw: hand every pin of ours back instead of mirroring — the same
    walk with the coverage withdrawn (_reconcile_pass). It waits for the
    fleet (fleet_lock_for_withdrawal), and is refused at once, before any
    wait, while selector-to-multiphp is on. Returns whether the pass RAN,
    whatever it wrote: the withdrawal has to know that before it counts
    what still stands, and a pass that was refused, suspended or deferred
    has said why itself.
    """
    if dry_run:
        return _reconcile_pass(True, reason, withdraw)
    if withdraw and load_conf()["selector_to_multiphp"] == "on":
        print(WITHDRAW_WHILE_ON)
        log("WITHDRAW refused — selector-to-multiphp is on")
        return False
    lock = fleet_lock_for_withdrawal() if withdraw \
        else path_lock_nb(RECONCILE_LOCK)
    with lock as acquired:
        if not acquired:
            if withdraw:
                # no request marker: the running pass would serve it as a
                # PLAIN pass, which refuses with the sync off — or, with it
                # on, re-pins what this one meant to withdraw
                print("another pass is still running — run --withdraw again "
                      "once it finishes")
                log("WITHDRAW deferred — a pass held the fleet for %ds "
                    "(reason=%s)" % (WITHDRAW_LOCK_WAIT, reason))
                return False
            # Not "redundant": the running pass may already be past the
            # accounts this request cares about. Leave a marker for it.
            try:
                with open_private(RECONCILE_REQUEST, "w"):
                    pass  # the marker is the file's existence, not content
            except OSError as e:
                log("RECONCILE-REQUEST could not be recorded: %s" % e)
            print("another reconcile is already running — it will re-run")
            log("RECONCILE deferred — a pass is already running, requested "
                "a re-run (reason=%s)" % reason)
            return False
        ran = _reconcile_pass(False, reason, withdraw)
        for _ in range(RECONCILE_FOLLOWUPS):
            if not os.path.exists(RECONCILE_REQUEST):
                break
            try:
                os.unlink(RECONCILE_REQUEST)
            except OSError:
                break
            log("RECONCILE re-running for a request that arrived mid-pass")
            _reconcile_pass(False, "queued-request")
    # The cap bounds the work THIS process does, never the request itself:
    # one landing during the last follow-up must still be served, and
    # handle_restore has no other way in until the daily run, and the
    # catch-up unit runs at boot. Looked for AFTER the release, and
    # dispatched there: a requester that failed the lock a moment before
    # the release writes its marker after any look taken inside, and a
    # detached pass started while this one still held the lock would fail
    # to acquire, leave the marker again and exit — reproducing the drop
    # this exists to prevent.
    if os.path.exists(RECONCILE_REQUEST):
        log("RECONCILE follow-up cap reached with a request still "
            "standing — dispatching a detached pass")
        spawn_reconcile("queued-request")
    return ran


@contextmanager
def fleet_lock_for_withdrawal():
    """The fleet lock for a withdrawal: waited for, WITHDRAW_LOCK_WAIT at
    most. A withdrawal runs with selector-to-multiphp off, and a mirroring
    pass holding the lock stops at its next chunk once it reads that
    (fleet_write); a withdrawal already running is doing this one's work.
    Found live: a --disable during the package-update pass an upgrade
    starts gave up at once on a 500-account box, and left every pin of ours
    standing for an admin to hand back by hand."""
    with path_lock_nb(RECONCILE_LOCK) as acquired:
        if acquired:
            yield True
            return
    print("another pass is running — waiting for it to stop (%ds at most)"
          % WITHDRAW_LOCK_WAIT)
    with path_lock_wait(RECONCILE_LOCK, WITHDRAW_LOCK_WAIT) as acquired:
        yield acquired


def _reconcile_pass(dry_run, reason, withdraw=False):
    """Bring every account into the synchronized state.

    The planning is the same a Selector version change triggers, but the
    writing is not: accounts are taken in chunks, and each chunk's planned
    domains are written grouped by target version — one cPanel call per
    version, covering every account in the chunk that wants it. Per
    account it was ~8s and hours on a large box; per chunk it is ~0.35s an
    account.

    The fleet loop also adds the one-time baseline recording before the
    first pin can be written, removal of sync state that no longer
    corresponds to anything (records of deleted accounts, entries for
    domains cPanel no longer lists), and a re-plan after any round that
    wrote. Idempotent — a converged fleet plans nothing and calls
    nothing.

    dry_run prints every account's plan and changes nothing; it works
    with the kill switch off, so the plan can be reviewed before
    enabling.

    withdraw is the disable's walk. The coverage is read for real and then
    WITHDRAWN (Coverage.withdrawn), so every domain reads inert and the
    planner can only hand back — the path a box that lost suEXEC already
    takes, same group rule, same ledger — while the handler table still
    picks values the web server can serve. It runs only while
    selector-to-multiphp is OFF: with it on, the next pass would put every
    pin straight back. And it records no baseline: this is not the sync's
    first write, and a picture taken here is of a box mid-hand-back.

    Returns True when the fleet was walked, False on every refusal and when
    syncing turned off mid-pass (fleet_write)."""
    syncing = load_conf()["selector_to_multiphp"] == "on"
    if not dry_run and withdraw and syncing:
        print(WITHDRAW_WHILE_ON)
        log("WITHDRAW refused — selector-to-multiphp is on")
        return False
    if not dry_run and not withdraw and not syncing:
        print("selector-to-multiphp syncing is off — "
              "reconcile does nothing; preview with --dry-run")
        log("RECONCILE skipped — selector-to-multiphp is off")
        return False
    default_pkg = system_default()
    if selector_suspended(default_pkg) and not withdraw:
        # Not for a withdrawal. This guard exists for the GATEWAY RULE —
        # `inherit` and a default-equal pin mean "delegated to the
        # Selector" only while the default is the ea-php chain it bends.
        # A withdrawal applies no gateway rule and reads no Selector
        # version: it restores recorded predecessors. Refusing here left
        # --disable having turned the switch off with every pin standing
        # and no re-run able to finish, on any box whose default is an
        # alt-php — the very state this verb exists to prevent.
        print(SUSPENDED_BANNER % default_pkg)
        log("RECONCILE suspended — system default %r" % default_pkg)
        return False
    # Apache's modules and php.conf cannot change during the walk: read
    # once, and the same reading judges every account.
    #
    # A box the Selector serves nothing on still walks: nothing there can
    # be mirrored, but pins we wrote before it lost coverage have to be
    # able to come back. Only the alt-php default's suspension above stops
    # the pass outright, and it takes no FPM pool snapshots; the toggle
    # hook still copies one whenever a domain ENTERS FPM, so what such a
    # box can lose is the tuning of a domain already on FPM at install.
    coverage = read_coverage()
    if coverage is None and withdraw:
        # A withdrawal needs no coverage FACTS — it forces every domain
        # inert — only php.conf's handler table, to pick a hand-back value
        # the web server can actually serve. So an unreadable module list
        # does not stop it: suexec/suphp are never consulted under a
        # withdrawal, and `routes` is reached only where a domain is
        # covered. Aborting here left a box whose web server will not
        # answer — a plausible one to be disabling — with the switch off
        # and every pin standing.
        coverage = Coverage(False, False, php_conf_handlers())
    if coverage is None:
        print("%s — nothing to reconcile" % NO_WEB_SERVER)
        log("RECONCILE-ABORT %s" % NO_WEB_SERVER)
        remember("pass-aborted", "reconcile", why=NO_WEB_SERVER)
        return False
    if withdraw:
        coverage = coverage._replace(withdrawn=WITHDRAWING)
        print(WITHDRAW_BANNER)
        log("WITHDRAW pass — every pin of ours goes back to the pin its "
            "domain arrived with (reason=%s)" % reason)
    elif coverage.inert:
        # as in mirror(): the fleet pass runs so pins of ours can go back.
        # Nothing here can be mirrored — every domain reads inert — so the
        # walk either writes hand-backs or writes nothing at all.
        print(INERT_BANNER % coverage.inert)
        log("RECONCILE suspended — %s; handing back any pins of ours"
            % coverage.inert)
    vhosts = all_vhosts()
    if vhosts is None:
        print("no vhost list from cPanel — nothing to reconcile")
        log("RECONCILE-ABORT no vhost list from cPanel")
        remember("pass-aborted", "reconcile", why="no vhost list from cPanel")
        return False
    by_user = {}
    for v in vhosts:
        if v.get("account"):
            by_user.setdefault(v["account"], []).append(v)
    if not dry_run:
        if not withdraw:
            write_baseline()
        prune_records(by_user, load_userdatadomains()[0])
    # A dry run previews and changes nothing, so it reads the box once:
    # per account, mirror() would otherwise re-ask whmapi for the system
    # default, start a selectorctl process, and re-read the pin map. On a
    # few hundred accounts that is minutes, for a command whose whole
    # purpose is to be read before anything is enabled.
    #
    # A real pass takes this reading per chunk instead, inside write_chunk
    # — its own writes change the pin map as it goes, and the verdicts it
    # persists must not rest on a target the selector has moved off.
    preview, preview_aliases, preview_pins = ({}, None, None)
    if dry_run:
        snapshot = all_selector_versions(with_websites=True)
        if snapshot is None and not withdraw:
            # the refusal fleet_walk makes for this same read. A preview
            # built on no answer shows every account with nothing to do —
            # a converged box, which is the one conclusion it is read to
            # disprove.
            print("no PHP Selector state for this server — "
                  "nothing can be previewed")
            log("RECONCILE preview aborted — no selector state for this "
                "server")
            return False
        # a withdrawal consults no selector version (see write_chunk), so
        # its preview must be readable on a box where that read fails too
        preview = snapshot or {}
        preview_aliases, preview_pins = load_userdatadomains()
    accounts = sorted(by_user)
    if dry_run:
        wrote = 0
        for user in accounts:
            print("== %s ==" % user)
            # a dry run changes nothing, so it needs no exclusion — and
            # must never defer, or the preview would be silently incomplete
            mirror(user, reason=reason, vhosts=by_user[user],
                   dry_run=True, coverage=coverage,
                   default_pkg=default_pkg, raw_pins=preview_pins,
                   aliases=preview_aliases,
                   selector=fleet_reading_of(user, by_user[user],
                                             preview_pins,
                                             preview.get(user, (None, {}))))
        log("RECONCILE done accounts=%d wrote=0 dry_run=True reason=%s"
            % (len(accounts), reason))
        return True
    # A real pass writes in batches, and re-plans after any round that
    # wrote or found a request: the round read the selector at its head,
    # and a version set while it ran must not be left standing as the
    # older pin (the hazard the per-account pass guard exists for). A
    # change that lands while the fleet holds its account's pass lock is
    # deferred with a request marker, which the chunk consumes and
    # reports. A converged round that found none writes nothing and ends
    # the loop, at the cost of one extra planning round — about a second
    # for a few hundred accounts.
    wrote = 0
    settled = False
    requested = set()
    for round_no in range(1 + PASS_FOLLOWUPS):
        this_round, requested, stopped = fleet_write(
            accounts, by_user, default_pkg, coverage, reason)
        wrote += this_round
        if stopped:
            log("RECONCILE stopped — selector-to-multiphp turned off "
                "mid-pass: accounts=%d wrote=%d reason=%s"
                % (len(accounts), wrote, reason))
            return False
        if not this_round and not requested:
            settled = True
            break
        log("RECONCILE re-planning after round %d: wrote %d account(s), "
            "%d request(s) arrived mid-round"
            % (round_no + 1, this_round, len(requested)))
    if not settled:
        # The cap bounds the work THIS process does, never the change. A
        # request the last round consumed was not served by a re-plan, so
        # it goes to a detached pass for that one account, as
        # guarded_mirror does past its own cap. A round that merely wrote
        # leaves nothing behind: a change that arrived while its account's
        # lock was free was served by its own trigger's pass.
        for user in sorted(requested):
            spawn_mirror(user, reason)
        log("RECONCILE re-plan cap reached with the last round still "
            "writing or finding requests — dispatched %d detached "
            "pass(es)" % len(requested))
    log("RECONCILE done accounts=%d wrote=%d dry_run=False reason=%s"
        % (len(accounts), wrote, reason))
    return True


def fleet_write(accounts, by_user, default_pkg, coverage, reason):
    """One convergence round over the whole fleet. Returns (how many
    accounts were written, the accounts whose request markers the round
    consumed — see write_chunk, whether syncing turned off mid-round).

    Accounts are taken RECONCILE_CHUNK at a time. Each chunk plans every
    one of its accounts first, then writes the planned domains grouped by
    target version — one cPanel call per version, covering every account
    in the chunk that wants it.

    A mirroring round reads the switch again before every chunk and stops
    once it is off: a --disable, or the remote flag's kill, arrived while
    it ran, and what it would still write is for the hand-back to undo. A
    hand-back runs only while the switch is off, so it never stops.
    """
    written_accounts, requested = 0, set()
    for start in range(0, len(accounts), RECONCILE_CHUNK):
        if not coverage.withdrawn \
                and load_conf()["selector_to_multiphp"] != "on":
            return written_accounts, requested, True
        wrote, asked = write_chunk(
            accounts[start:start + RECONCILE_CHUNK], by_user, default_pkg,
            coverage, reason)
        written_accounts += wrote
        requested |= asked
    return written_accounts, requested, False


def write_chunk(chunk, by_user, default_pkg, coverage, reason, held=False,
                refused=None):
    """Plan every account in the chunk, then write them together.

    The selector state and the pin map are read fresh here, once for the
    chunk — not once for the pass. Both reads answer for the whole box in
    one call (see all_selector_versions), so a chunk's evidence is at most
    one chunk old when it is used, where a pass-wide reading would age
    across every write. That matters because plan_mirror's verdicts are
    persisted: a stale target could park an agreeing pin as a takeover, or
    claim a merely-coincidental pin as ours.

    Returns (accounts written, accounts whose request marker this chunk
    consumed). A marker on an account the chunk held was left by a trigger
    that could not take the lock while the chunk ran — state moved under
    the planning — and the chunk is that marker's holder: it serves it as
    guarded_mirror serves its own, by consuming it and handing the account
    back to the caller for a re-plan (or, past the caller's cap, a
    detached pass of its own). Markers on accounts another pass holds are
    that pass's to consume.

    An account with a PHP Selector change in flight (begin_change) is left
    alone, and its lock untaken, so the pass ending the change is not kept
    waiting: a request is left for that pass instead. Not on a withdrawal
    or a release, which hand pins back and so never name the version an
    account is leaving.

    held: the caller holds every account's pass lock already (a release,
    release_many). Taking it again through another descriptor would fail.

    refused: out, for a release: {account: why} for each account the
    release could not step aside for whole, which it leaves as it is
    rather than hand back the rest and then refuse the change — found in
    review, every refused attempt rebuilt Apache twice for nothing — and
    for each a hand-back of which did not land.

    An account one of whose changes began or ended after the Selector was
    read (changed_since) is not planned from that reading: a bulk move that
    handed it back, switched it and ended its change meanwhile left the
    reading naming the version it had just left, over the `inherit` the
    release wrote (found in review). It leaves a request this chunk serves,
    so the caller plans it again from a fresh reading.
    """
    read_at = fs_clock()
    if coverage.withdrawn == RELEASING:
        # a release consults no Selector version: every domain is out of
        # coverage, and the hand-back values come from the ledger and the
        # handler table (handback_by_group)
        selector = {}
    else:
        selector = all_selector_versions(with_websites=True)
    if selector is None:
        if not coverage.withdrawn:
            # no answer at all is not "every account is native": mirroring
            # native means unpinning, so a wrong reading here would plan an
            # unpin of every domain the ledger proves we wrote
            log("RECONCILE-CHUNK skipped — no selector state for this server")
            return 0, set()
        # A withdrawal asks the Selector nothing: every domain is inert, so
        # no target is computed and the hand-back values come from the
        # ledger's `was` and the handler table. Refusing here left every pin
        # standing on precisely the box most likely to be disabled — one
        # whose Selector is not answering — with no re-run able to finish.
        # Measured on a live CL10 box, where this bulk read returns None
        # while the per-account one answers.
        log("WITHDRAW-CHUNK proceeding without a selector reading — a "
            "withdrawal consults none")
        selector = {}
    aliases, raw_pins = load_userdatadomains()
    plans, owner, locked = {}, {}, []
    # domains this chunk is handing back rather than mirroring; the write
    # is the same call either way, only the ledger differs afterwards
    releases, arrived, carried = set(), {}, {}
    with contextlib.ExitStack() as stack:
        for user in chunk:
            if not coverage.withdrawn and pending_changes(user):
                leave_request(user, reason,
                              "a PHP Selector change is in flight; its end "
                              "runs the pass")
                continue
            if not held and \
                    not stack.enter_context(path_lock_nb(pass_lock_path(user))):
                # another pass holds this account: leave a request, exactly
                # as guarded_mirror does, and let that holder re-run
                leave_request(user, reason)
                continue
            locked.append(user)
            if restoring(user) or modifying(user):
                # under its lock, as guarded_mirror asks
                if not restoring(user):
                    mark_modify_held(user)
                log("MIRROR-SKIP user=%s — being %s; its end converges it"
                    % (user, "restored" if restoring(user) else "modified"))
                continue
            if not coverage.withdrawn and changed_since(user, read_at):
                leave_request(user, reason,
                              "a PHP Selector change began or ended after "
                              "this chunk read the Selector; planned again")
                continue
            state = selector.get(user)
            if coverage.withdrawn == RELEASING:
                state = ("native", {})  # never read (above)
            elif state is None or state[0] is None:
                # The fleet reading did not cover this account, and no
                # answer is not "nothing to do" — collapsing it to native
                # would plan an unpin of every domain the ledger proves we
                # wrote. Fall back to the per-account query: a different
                # mechanism, which may answer where the fleet one did not.
                # It costs one process, for the few accounts that need it.
                state = selector_state(user)
            else:
                state = fleet_reading_of(user, by_user[user], raw_pins, state)
            if state[0] is None:
                if not coverage.withdrawn:
                    log("MIRROR-SKIP user=%s — no selector state to mirror"
                        % user)
                    continue
                # as above: the value is never read on a withdrawal, and
                # an account the Selector cannot answer for still has pins
                # of ours to hand back
                state = ("native", {})
            vhosts = by_user[user]
            # the pool yaml is the only backup of a tenant's FPM tuning and
            # cPanel deletes it on a disable, so it is copied on every pass
            # that sees the domain on FPM — including one that writes nothing
            snapshot_fpm_pools(user, vhosts)
            targets = selector_state(user) \
                if coverage.withdrawn == RELEASING \
                and inherits_an_alt_php(vhosts, raw_pins) else None
            if targets is not None and targets[0] is OUTSIDE_CAGEFS:
                # no version to judge a site below against: such a group
                # holds, as for an account that does not answer
                targets = (None, {})
            # NEVER hold the record lock across the write below: the write
            # raises our own hook synchronously and the hook needs this very
            # lock. Planning takes it, the write does not.
            with record_lock(user):
                try:
                    record = own_record(user)
                except RecordUnusable as e:
                    # the rest of the chunk goes on; this account is left
                    # alone, and its file as it is (load_record logged it)
                    log("MIRROR-SKIP user=%s — %s" % (user, e.note()))
                    continue
                before, moved = json.dumps(record, sort_keys=True), []
                plan, skips, record = plan_mirror(
                    vhosts, state[0], state[1], default_pkg, record,
                    raw_pins=raw_pins, coverage=coverage,
                    releases=releases, arrived=arrived, carried=carried,
                    release_targets=targets,
                    aliases=aliases, moved=moved,
                )
                plan = hold_unservable(plan, user, coverage.handlers)
                why_not = release_refusal(record, raw_pins, plan, vhosts,
                                          skips) \
                    if refused is not None \
                    and coverage.withdrawn == RELEASING else None
                # Only when the planning actually recorded something. A
                # converged fleet would otherwise rewrite — and fsync —
                # every account's record on every round to change
                # nothing, which is the recurring case and was most of
                # this pass's cost when measured. And not for a release
                # that is refused: it leaves the account as it is, its
                # record too (found in review: a refused release made a
                # pin the domain's own, no change having happened).
                if why_not is None \
                        and json.dumps(record, sort_keys=True) != before:
                    save_record(user, record)
                    log_carried(moved)
            for dom, why in skips:
                log("MIRROR-SKIP user=%s domain=%s (%s)" % (user, dom, why))
            if why_not is not None:
                refused[user] = why_not
                continue
            if not plan:
                log("MIRROR-PASS user=%s skipped=%d writes=0 reason=%s"
                    % (user, len(skips), reason))
                continue
            if not record_pending(user, plan, releases, arrived, carried):
                continue
            plans[user] = plan
            for target, doms in plan.items():
                for dom in doms:
                    owner[dom] = user

        batches = {}
        for plan in plans.values():
            for target, doms in plan.items():
                batches.setdefault(target, []).extend(doms)
        wrote_users, claims = set(), {}
        planned_vhosts = [v for user in plans for v in by_user[user]]
        roots, bare, unlanded = document_roots(planned_vhosts), set(), set()
        for target, doms in order_writes(batches, planned_vhosts):
            held = over_bare(doms, bare, roots) \
                if from_pkg(target) is not None else []
            for dom in held:
                log("MIRROR-HOLD user=%s -> %s: %s, above a site whose own "
                    "pin did not land" % (owner[dom], target, dom))
            below = under_unlanded(doms, unlanded, roots) \
                if target == "inherit" else []
            for dom in below:
                log("MIRROR-HOLD user=%s -> inherit: %s, below a site whose "
                    "own write did not land" % (owner[dom], dom))
            held += below
            doms = [d for d in doms if d not in held]
            written = write_batch(target, doms, reason, owner, raw_pins) \
                if doms else []
            unlanded.update(d for d in doms + held if d not in written)
            if from_pkg(target) is not None:
                bare.update(d for d in doms if d not in written
                            and (raw_pins or {}).get(d) == "inherit")
            missed = {}
            for dom in doms + held:
                if dom not in written and dom not in releases \
                        and dom not in carried:
                    missed.setdefault(owner[dom], []).append(dom)
            for user, ds in missed.items():
                drop_pending(user, ds)
            by_account = {}
            for dom in written:
                by_account.setdefault(owner[dom], []).append(dom)
            for user, ds in by_account.items():
                record_landed(user, ds, target, releases, arrived, carried,
                              default_pkg, coverage.withdrawn)
                wrote_users.add(user)
                claims.setdefault(user, {}).update(
                    (d, target) for d in ds
                    if d not in releases and d not in carried)
        for user in sorted(claims):
            if back_at_arrival(user, claims[user], roots):
                # consumed below, once the lock is released: the caller
                # re-plans the account, or past its cap a detached pass does
                leave_request(user, reason, REJUDGE_BELOW)
        if refused is not None:
            # a hand-back the release planned that did not land refuses the
            # change, also one of a pin what still stands after it leaves
            # out (standing_of_ours, adopted=False). Found in review:
            # cPanel refused the release's write, the change went ahead, and
            # the site served the version it left with the server-wide
            # extensions until the pass ending the change
            for dom in sorted(unlanded):
                refused.setdefault(owner[dom], Why(
                    "a pin of the sync's still stands on %s: its hand-back "
                    "did not land" % dom, "handback-failed"))
        if coverage.withdrawn == RELEASING:
            # A release is not a pass. Its writes are paced before they are
            # made (release_held), and the pass that ends the change paces
            # off the stamp: stamped here, every tenant's change would wait
            # DOOR_PACE between its two writes. The requests the release's
            # own deferrals left are that pass's to serve.
            return len(wrote_users), set()
        for user in locked:
            # a pass ran for this account whether or not it wrote; the
            # tenant door paces off this stamp's mtime
            try:
                with open_private(pass_stamp_path(user), "w"):
                    pass  # the mtime is the record, not the content
            except OSError as e:
                log("PASS-STAMP could not be recorded: %s" % e)
    # Looked for AFTER the release, as guarded_mirror does: a requester that
    # fails the lock a moment before it is released writes its marker after
    # any look taken inside — for an account already checked while the
    # rest of the chunk is still being scanned — and on the common
    # converged round nothing would re-plan it. Released, the account has
    # no holder but us to serve a marker; a pass that took the lock in
    # between consumes the same marker itself, and serving it twice is a
    # harmless re-plan.
    requested = set()
    for user in locked:
        request = pass_request_path(user)
        if not os.path.exists(request):
            continue
        try:
            os.unlink(request)
        except OSError as e:
            log("PASS-REQUEST could not be consumed for %s: %s" % (user, e))
            continue
        requested.add(user)
        log("PASS request arrived while the fleet held user=%s — "
            "re-planning" % user)
    return len(wrote_users), requested


# what kept a pin of ours (its skip's code) -> the refusal's code
PIN_KEPT = {"docroot": "pin-kept-docroot", "cascade": "pin-kept-cascade",
            "unknown": "pin-kept-unknown", "unknown-above": "pin-kept-unknown"}


def release_refusal(record, raw_pins, plan, vhosts, skips):
    """Why a planned release has to leave the account as it is, or None: a
    pin of ours it would leave on the version the account is leaving
    (left_standing)."""
    left = left_standing(record, raw_pins, plan, vhosts)
    if left:
        skip = dict(skips).get(left[0])
        return Why("a pin of the sync's still stands on %s: %s" % (
            left[0], skip or "it could not be handed back"),
            PIN_KEPT.get(getattr(skip, "code", None), "pin-kept-other"))
    return None


def left_standing(record, raw_pins, plan, vhosts):
    """The alt-php pins of ours a planned release leaves where they are,
    and would strand on the version the account is leaving: on domains
    cPanel lists (`vhosts`), as in standing_of_ours. Not one the domain
    arrived with (`was` equal to it), which stands without the sync too
    (keep_what_a_release_moves); one nobody read counts, as there (found in
    review: left out here, the release wrote first and was refused
    after)."""
    planned = set(d for doms in plan.values() for d in doms)
    listed = {v["vhost"] for v in vhosts}
    left = []
    for dom, entry in record["domains"].items():
        if dom in planned or dom not in listed:
            continue
        pin = (raw_pins or {}).get(dom)
        row = effective_entry(entry, pin)
        if pin is None:
            claims = [row.get("version")] if row.get("owner") == "selector" \
                else []
            if isinstance(row.get("pending"), dict):
                claims.append(row["pending"].get("version"))
            if any(isinstance(c, str) and from_pkg(c) for c in claims):
                left.append(dom)
        elif from_pkg(pin) is not None and row.get("owner") == "selector" \
                and row.get("version") == pin and row.get("was") != pin:
            left.append(dom)
    return sorted(left)


def log_carried(moved):
    """The rows a saved plan carried (plan_mirror's `moved`)."""
    for old, new in moved:
        log("LEDGER-CARRIED %s -> %s: the addon parked on that subdomain"
            % (old, new))


def carry_addon_rows(domains, listed, aliases):
    """Move each ledger row kept under an addon's subdomain name to the
    addon's own name; returns [(old, new)] for the rows moved.

    cPanel creates an addon on a subdomain (addon.main.test), lists it
    under that name until the addon is parked onto it, and under the
    addon's own name (addon.test) from then on. A pass that ran in between
    pinned the subdomain and kept its row under the subdomain's name, and
    the next one found the addon with our pin and no row, which reads as
    a pin set in MultiPHP Manager (takeover-as-found). --disable then left
    our alt-php standing, and an FPM toggle
    pooled it outside the cage (found in review). A row of the addon's own
    is never replaced, but for the mark the FPM listener leaves on a domain
    with no row (reason `fpm`) that names the carried row's pin: that one
    was written for our own pin, found under the wrong name."""
    carried = []
    aliases = aliases or {}
    # the account's rows, not every addon on the box: this runs per account
    # in a fleet pass (found in review: 20k addons cost seconds a round)
    for old in sorted(d for d in domains if d in aliases):
        new = aliases[old]
        if new not in listed:
            continue
        mine = domains.get(new)
        if mine is not None and not (
                mine.get("reason") == "fpm"
                and mine.get("version") == domains[old].get("version")):
            continue
        domains[new] = domains.pop(old)
        carried.append((old, new))
    return carried


def state_accounts():
    """Every account name a file in the state directory belongs to: its
    record, its record lock, or one of its `@` files and directories."""
    names = set()
    for name in os.listdir(STATE_DIR):
        if name.startswith("_") or name == os.path.basename(CONF_PATH):
            continue
        if "@" in name:
            names.add(name.split("@", 1)[0])
        elif name.endswith((".json", ".lock")):
            names.add(name.rsplit(".", 1)[0])
    return names


def prune_records(by_user, aliases=None):
    """Drop sync state nothing corresponds to any more: every file of an
    account that no longer exists (found in review: walked by its record
    alone, an account that never had one kept its change files, stamps and
    locks), and domain entries cPanel no longer lists for an account it
    does list. An entry kept under the subdomain an addon has since been
    parked on is carried to the addon instead (carry_addon_rows): this runs
    before the fleet's planning. The engine's own "_"-prefixed files are
    never touched."""
    for account in sorted(state_accounts() - set(by_user)):
        if restoring(account) or modifying(account):
            # an account restored as new has no system user until the
            # restore makes it: its mark is the restore's (found in review,
            # pruned, the hold went)
            continue
        try:
            pwd.getpwnam(account)
        except KeyError:
            pass
        else:
            # the account exists but the listing has no vhost for it: no
            # answer about its domains, not "all gone" — pruning here would
            # leave every mirror pin unprovable, takeover-as-found on the
            # next selector change
            continue
        for path in (record_path(account),
                     record_lock_path(account),
                     pass_lock_path(account),
                     pass_request_path(account),
                     pass_stamp_path(account),
                     change_stamp_path(account),
                     door_lock_path(account),
                     release_stamp_path(account),
                     new_pending_path(account),
                     new_pending_path(account) + ".lock",
                     restoring_path(account),
                     modify_pending_path(account),
                     modify_held_path(account)):
            if os.path.exists(path):
                os.unlink(path)
        # the pool copies exist so an operator can restore a domain's
        # tuning; with the account gone there is nothing to restore onto
        shutil.rmtree(pool_dir(account), ignore_errors=True)
        shutil.rmtree(changes_dir(account), ignore_errors=True)
        log("RECONCILE-PRUNE removed the state of deleted account %s"
            % account)
    for name in sorted(os.listdir(STATE_DIR)):
        if not name.endswith(".json") or name.startswith("_"):
            continue
        account = name[:-len(".json")]
        if account not in by_user or restoring(account) \
                or modifying(account):
            # an account being modified has its domains renamed before its
            # rows follow them (handle_modify): found in review, dropped
            # here as removed, they took the proof of the sync's pins
            continue
        current = {v["vhost"] for v in by_user[account]}
        # nothing to drop is the normal case, and writing anyway would
        # rewrite (and fsync) every account's record on every pass
        with record_lock(account):
            try:
                rec = load_record(account)
            except RecordUnusable:
                # nothing may write it, pruning included (logged there)
                continue
            carried = carry_addon_rows(rec["domains"], current, aliases)
            gone = sorted(d for d in rec["domains"] if d not in current)
            if not gone and not carried:
                continue
            for dom in gone:
                del rec["domains"][dom]
                # same for a domain cPanel no longer lists
                try:
                    os.unlink(pool_path(account, dom))
                except OSError:
                    pass
            save_record(account, rec)
        for old, new in carried:
            log("LEDGER-CARRIED %s -> %s: the addon parked on that "
                "subdomain" % (old, new))
        if gone:
            log("RECONCILE-PRUNE %s: dropped entries for removed domains: "
                "%s" % (account, ",".join(gone)))


# --------------------------------------------------------------------------
# MultiPHP -> Selector: event handling
# (entry points for the cPanel hook script, utils/multiphp_sync_hook.py)
# --------------------------------------------------------------------------

def event_domains(names, vhosts=None, aliases=None):
    """(domain, account, vhost) for each event name that resolves, once.
    `vhosts`: cPanel's listing when the caller has read it, read here
    otherwise; `aliases` likewise (load_userdatadomains).

    cPanel events carry both the zone name and the addon's internal
    subdomain-FQDN form, so the same domain can appear twice; a name that
    resolves to nothing is skipped rather than guessed at (see
    resolve_event_vhost). Yields nothing when the vhost list itself went
    unanswered: no name can be attributed then, and the next mirror pass
    recovers whatever the event would have recorded — a missed event is a
    designed-for case, a traceback in the hook cPanel is waiting on is not.
    """
    if vhosts is None:
        vhosts = all_vhosts()
    if vhosts is None:
        log("EVENT skipped — no vhost list from cPanel: %s" % list(names))
        return
    by_name = {v["vhost"]: v for v in vhosts}
    # each account's vhosts per document root, read once: asked per name,
    # a bulk event walked the box's listing once per domain (found in
    # review: 4,000 names on a box of 54,000 vhosts took 19 s of the
    # request cPanel holds open). No document root, no siblings: nothing
    # may be a sibling of nothing.
    by_root = {}
    for v in vhosts:
        if v.get("documentroot"):
            by_root.setdefault((v.get("account"), v["documentroot"]),
                               []).append(v)
    if aliases is None:
        aliases, _ = load_userdatadomains()
    seen = set()
    for name in names:
        vhost = resolve_event_vhost(name, by_name, aliases)
        if not vhost:
            log("EVENT vhost not resolved, skipped: %s" % name)
            continue
        dom = vhost["vhost"]
        if dom in seen:
            continue
        seen.add(dom)
        yield dom, vhost["account"], vhost
        # WHM's php_set_vhost_versions pins every domain that shares the
        # named one's document root (get_impacted_domains) but hands the
        # post hook only the names the caller gave. UAPI's result.vhosts
        # already lists them; this makes the WHM transport say as much.
        for sibling in by_root.get((vhost.get("account"),
                                    vhost.get("documentroot")), ()):
            if sibling is vhost or sibling["vhost"] in seen:
                continue
            seen.add(sibling["vhost"])
            log("EVENT includes %s: it shares %s's document root, so "
                "cPanel pinned it too" % (sibling["vhost"], dom))
            yield sibling["vhost"], sibling["account"], sibling


def nested_pins_of_ours(vhosts, entries, raw_pins):
    """{document root: [the account's domains below it that carry an
    alt-php pin of ours where they would be on `inherit` without the
    sync]}, `vhosts` and `entries` one account's: the domains a pin on a
    domain of that root reaches through the .htaccess cascade, but for
    ours (serving_gap). One that would carry a pin of its own keeps the
    parent's from reaching it. Keyed by every root above each, so a bulk
    event reads the account once (found in review: read per domain, an
    event naming 4,000 domains of one account took 15 s of the request
    cPanel holds open)."""
    below = {}
    for v in vhosts:
        child = (v.get("documentroot") or "").rstrip("/")
        raw_pin = (raw_pins or {}).get(v["vhost"])
        entry = effective_entry(entries.get(v["vhost"], {}), raw_pin)
        was = entry.get("was")
        if not child or raw_pin is None or not from_pkg(raw_pin) \
                or entry.get("owner") != "selector" \
                or entry.get("version") != raw_pin \
                or (was if isinstance(was, str) and was else "inherit") \
                != "inherit":
            continue
        path = child.rpartition("/")[0]
        while path:
            below.setdefault(path, []).append(v["vhost"])
            path = path.rpartition("/")[0]
    return below


def pin_of_ours_above(dom, cascade, entries, raw_pins):
    """The domain whose pin of ours `dom` runs through Apache's .htaccess
    cascade (pin_source), or None: a pin of its own (an explicit default
    shields it; found in review, taken for `inherit`, it ran a pass that
    wrote nothing), no pin above it, someone else's, or one nobody read.
    `cascade`: document_root_groups of the domain's account, which a bulk
    event asks for once; `raw_pins` as read after the event's write."""
    roots, groups = cascade
    if dom not in roots:
        return None
    pins = raw_pins or {}
    source = pin_source(dom, pins, roots, groups)
    if source is None or pins.get(source) is None:
        return None
    row = effective_entry(entries.get(source, {}), pins[source])
    if row.get("owner") == "selector" and row.get("version") == pins[source]:
        return source
    return None


def parent_pin_accounts(moved, version, vhosts, raw_pins):
    """The accounts whose pass has to run now because a pin an event
    confirmed - `version` on each (domain, account, vhost) of `moved` -
    reaches a pin of ours through Apache's .htaccess cascade
    (nested_pins_of_ours). The pass hands those back (serving_gap): until it
    runs they serve the Selector's version where without the sync they
    would serve the parent's. Whoever owns the parent and whatever the
    listener made of the event - off, a parent on PHP-FPM or out of
    coverage, a takeover or not - the cascade reaches them all the same
    (found in review: only a recorded takeover ran the pass).

    None while the mirror is off and no hand-back is under way or due:
    nothing of ours stands then. `inherit` reaches them only where it lets
    a pin higher up through (lets_a_pin_through): an explicit default it
    replaced shielded them. Otherwise it cascades the Selector's own
    version, what our pin serves."""
    if not moved or not vhosts or not (
            load_conf()["selector_to_multiphp"] == "on" or withdrawal_due()):
        return set()
    by_account = vhosts_by_account(vhosts)
    default_pkg = system_default() if version == "inherit" else None
    accounts, read = set(), {}
    for dom, user, vhost in moved:
        if user in accounts:
            continue
        if user not in read:
            # once per account: a bulk event names thousands of domains
            mine = by_account.get(user, [])
            try:
                entries = load_record(user)["domains"]
            except RecordUnusable:
                read[user] = None  # left alone, as a pass leaves it
            else:
                roots, groups = document_root_groups(mine)
                pins = nosync_pins(
                    dict((d, raw_pins[d]) for d in roots
                         if d in (raw_pins or {})),
                    {"domains": entries}, default_pkg) \
                    if version == "inherit" else None
                read[user] = (nested_pins_of_ours(mine, entries, raw_pins),
                              roots, groups, pins)
        if read[user] is None:
            continue
        below, roots, groups, pins = read[user]
        nested = below.get((vhost.get("documentroot") or "").rstrip("/"))
        if not nested or (pins is not None and not lets_a_pin_through(
                dom, roots, groups, pins, default_pkg)):
            continue
        log("PARENT-PIN: %s -> %s reaches %s through the .htaccess "
            "cascade — re-judging the sync's pins there"
            % (dom, version, ", ".join(nested[:5])))
        accounts.add(user)
    return accounts


def lets_a_pin_through(dom, roots, groups, pins, default_pkg):
    """Whether `dom`, set to `inherit`, now runs a pin above it that is not
    a gateway value, `pins` its account's as they would stand without the
    sync (nosync_pins): the sites below it on `inherit` run that one from
    then on, and not the Selector's. A pin nobody read may be one. Found by
    a sequence fuzzer: an admin's `inherit` over an isolated website's
    explicit default, the website out of coverage, brought the main
    domain's ea-php81 to the site below it, and the sync's pin of that
    site's own 8.0 stayed until the daily run."""
    if dom not in roots:
        return False
    runs = runs_on(dom, pins, roots, groups)
    return runs is None or not is_gateway(runs, default_pkg)


def rejudge_parent_pins(names, version, echoed, pace=False, covered=None):
    """parent_pin_accounts for an event the listener leaves alone, and
    their passes. `echoed`: the names that were our own writes, which the
    pass that made them judged when it planned. `covered`: the accounts a
    pass of the same event has judged already (handle_fpm_event, FLEET for
    all of them): found in review, a tenant's PHP-FPM enable ran its
    account's pass a second time, paced, behind the first."""
    if set(names) <= echoed or covered == FLEET \
            or not (load_conf()["selector_to_multiphp"] == "on"
                    or withdrawal_due()):
        return
    aliases, raw_pins, vhosts = load_userdata_listing()
    if not vhosts:
        return
    moved = [(dom, user, vhost) for dom, user, vhost
             in event_domains(names, vhosts, aliases)
             if dom not in echoed and (raw_pins or {}).get(dom) == version]
    accounts = parent_pin_accounts(moved, version, vhosts, raw_pins) \
        - set(covered or ())
    if accounts:
        dispatch_parent_pin(accounts, pace)


def rejudge_pins_above(names, version, echoed, pace=False):
    """With multiphp-to-selector off, the passes for the sites an event set
    to `inherit` under a pin of ours: from then on they run that pin
    through the .htaccess cascade (pin_of_ours_above), which serves the
    Selector's version for the site it is on, not necessarily for these.
    The listener does the same when it is on (handle_event). Found in
    review: with it off, an isolated website on 8.0 set to `inherit` ran
    the main domain's 8.2 with the server-wide extensions until the daily
    run. `echoed`: the names that were our own writes."""
    if version != "inherit" or set(names) <= echoed \
            or not (load_conf()["selector_to_multiphp"] == "on"
                    or withdrawal_due()):
        return
    aliases, raw_pins, vhosts = load_userdata_listing()
    if not vhosts:
        return
    accounts, by_account, read = set(), vhosts_by_account(vhosts), {}
    for dom, user, _ in event_domains(names, vhosts, aliases):
        if dom in echoed or user in accounts \
                or (raw_pins or {}).get(dom) != "inherit":
            continue
        if user not in read:
            # once per account: a bulk event names thousands of domains
            try:
                read[user] = (load_record(user)["domains"],
                              document_root_groups(by_account.get(user, [])))
            except RecordUnusable:
                read[user] = None  # left alone, as a pass leaves it
        if read[user] is None:
            continue
        entries, cascade = read[user]
        above = pin_of_ours_above(dom, cascade, entries, raw_pins)
        if above is not None:
            log("EVENT %s -> inherit runs the pin of the sync's on %s: "
                "re-judging the account" % (dom, above))
            accounts.add(user)
    dispatch_parent_pin(accounts, pace)


def dispatch_parent_pin(accounts, pace=False):
    """The passes parent_pin_accounts asks for: one account's own, a
    reconcile past one. With the mirror off and a hand-back under way or
    due, the pass would refuse, and the walk may reach these accounts only
    later: they go back now, as it will — one account's at once
    (withdraw_account), and past one the walk itself, detached, which
    hands back every account it is due for (found in review: each account
    went back inline, inside the request cPanel was serving)."""
    if not accounts:
        return
    if load_conf()["selector_to_multiphp"] != "on":
        if len(accounts) > 1:
            spawn_withdraw("parent-pin")
            return
        for account in accounts:
            withdraw_account(account, "parent-pin", pace=pace)
        return
    if len(accounts) > 1:
        spawn_reconcile("parent-pin")
        return
    for account in accounts:
        guarded_mirror(account, "parent-pin", pace=pace)


def withdraw_account(user, reason, pace=False):
    """Hand the account's pins of ours back now, as a withdrawal under way
    or due will (release_held, WITHDRAWING). Left to that walk while a pass
    holds the account: it may be the walk itself. pace: a tenant's event,
    which waits out DOOR_PACE before it writes, as the door's do. Returns
    whether it ran."""
    with path_lock_nb(pass_lock_path(user)) as alone:
        if alone:
            stuck = release_held([user], reason, pace=pace,
                                 withdrawn=WITHDRAWING)
            if stuck:
                log("PARENT-PIN %s not handed back yet — %s"
                    % (user, stuck[user]))
        return alone


def forget_replaced_pins(names, version, echoed):
    """With multiphp-to-selector off an event decides nothing, but the
    ledger has to stay true: a write over a pin of ours replaced it,
    whatever the value. Of a gateway value: the row's `was` is what the
    domain carried before our FIRST mirror. Left standing, the next pass
    re-mirrored the domain under that older `was`, and once the default
    moved a hand-back restored it: an admin's `inherit` came back as an
    explicit ea-php83 that was no longer the default (found in review). Of
    any other: the next pass took it for a takeover only while the value
    stood. Found in review: an admin's ea-php81, and then alt-php82 again
    before any pass, read as the pin of ours still standing, and --disable
    moved the admin's alt-php82 to `inherit`. So the row goes, as a
    takeover or a gateway return clears it with the direction on, and the
    next pass records what the domain carries then. Writes nothing;
    confirmed against the stored pin, as every event is, and never for our
    echo.

    Nor while a pass of ours holds the account (pass_running): the write
    is ours then, intent or none. Found in review: during a remote flag
    kill the switches read off and no intent marked our writes, and a
    release's hand-back dropped the row it was writing, `was` and all.
    And cheaply, inside the cPanel request it serves: no listing asked of
    cPanel (load_userdata_listing), and no default (found in review: both,
    on every such request, before it knew the event was ours)."""
    if set(names) <= set(echoed):
        return
    aliases, stored, vhosts = load_userdata_listing()
    if vhosts is None:
        return
    by_user = {}
    for dom, user, _vhost in event_domains(names, vhosts, aliases):
        if dom not in echoed and (stored or {}).get(dom) == version:
            by_user.setdefault(user, []).append(dom)

    def replaced(entries, dom):
        entry = entries.get(dom, {})
        return entry.get("owner") == "selector" \
            and entry.get("version") != version
    for user, doms in sorted(by_user.items()):
        if pass_running(user):
            continue
        # read once per account: in the generator it was read per domain
        entries = ledger_entries(user) or {}
        if not any(replaced(entries, d) for d in doms):
            continue
        try:
            with updated_record(user) as rec:
                for dom in doms:
                    if replaced(rec["domains"], dom):
                        del rec["domains"][dom]
                        log("EVENT %s -> %s replaced a pin of ours; its row "
                            "goes, and the next pass records what the domain "
                            "carries now" % (dom, version))
        except RecordUnusable as e:
            log("EVENT %s -> %s: record of %s unusable: %s"
                % (",".join(doms), version, user, e.note()))


def handle_event(vhosts, version, actor, pace=False):
    """Process one php_set_vhost_versions event (canonical state re-read).

    pace: the event is a tenant's own (the UAPI transport), so a pass it
    starts takes the door's throttle — a tenant looping `inherit` on
    their own domain must not drive one Apache rebuild after another."""
    def retire_echoes():
        # Our own mirror write fires this hook whether or not the reverse
        # direction is on, and its intents have to be retired by the event
        # they belong to. Returning first would leave them standing for
        # INTENT_TTL, and an admin write of the same value in that window —
        # once the direction is on — would read as our echo and its
        # takeover never be recorded (measured live by rpm test 83: "ECHO
        # consumed" 16s after our write, with the switch off).
        #
        # Returns the ones that were ours, which is how the refusals below
        # tell an event worth coming back to from the sound of our own
        # writing.
        return consume_intents(vhosts, version)

    if load_conf()["multiphp_to_selector"] != "on":
        echoed = retire_echoes()
        log("EVENT ignored — multiphp_to_selector is off: %s -> %s"
            % (vhosts, version))
        forget_replaced_pins(vhosts, version, echoed)
        rejudge_parent_pins(vhosts, version, echoed, pace)
        rejudge_pins_above(vhosts, version, echoed, pace)
        return
    default_pkg = system_default()
    if selector_suspended(default_pkg):
        retire_echoes()
        log("EVENT ignored — the selector is disabled by the system default "
            "(%r): %s -> %s" % (default_pkg, vhosts, version))
        return
    # one reading for the whole event: `httpd -M` measures in the tens of
    # milliseconds, and an event names any number of domains
    coverage = read_coverage()
    if coverage is None or coverage.inert:
        echoed = retire_echoes()
        log("EVENT ignored — %s: %s -> %s"
            % (coverage.inert if coverage else NO_WEB_SERVER, vhosts, version))
        if coverage is None:
            # An inert box is a box to leave alone; a reading that merely
            # failed is not. The pins moved either way, and what this
            # event would have converged — a hand-back above all — would
            # otherwise wait for some unrelated trigger.
            #
            # Deferred to a pass rather than decided here, because nothing
            # can be classified without the reading; the pass takes its
            # own, and refuses again if it still cannot. It is the same
            # guarded pass every other trigger uses, so it inherits what
            # this refusal would otherwise have to re-invent: the account
            # lock that stops passes stacking, the tenant throttle, and
            # the kill-switch check inside mirror().
            #
            # Armed only by news, and by the one kind of news that needs a
            # pass. Confirming against the store is not enough on its own:
            # this hook fires for calls cPanel REFUSED, and a refused call
            # restating the value already stored — `inherit` on any
            # unpinned domain — confirms perfectly. So the same three
            # tests the classification path applies are applied here: the
            # value must not be our own echo, it must be a gateway value
            # (a takeover needs no convergence; a hand-back is the whole
            # reason this branch exists), and the ledger must not already
            # record it, which is the no-op rule that keeps a restatement
            # from passing for a change.
            _, stored = load_userdatadomains()
            deferred, seen = set(), {}
            for dom, user, _vhost in event_domains(vhosts):
                if dom in echoed or (stored or {}).get(dom) != version:
                    continue
                if not is_gateway(version, default_pkg):
                    continue
                if user not in seen:
                    seen[user] = ledger_entries(user)
                if seen[user] is None \
                        or seen[user].get(dom, {}).get("version") == version:
                    continue
                deferred.add(user)
            for user in sorted(deferred):
                guarded_mirror(user, "coverage-unread", pace=pace)
        rejudge_parent_pins(vhosts, version, echoed, pace)
        return
    states, remirror, pending, records = {}, set(), {}, {}
    # the pins this event moved, whatever is made of them below: each
    # reaches the domains nested in its document root (parent_pin_accounts)
    moved = []
    # whose restatement of a pin of ours makes it MultiPHP's: root's (WHM's
    # payload names what was asked, and only root's is never refused for a
    # domain it does not own), and a tenant's own through the UAPI, whose
    # result names only what cPanel confirmed
    trusted = pace or actor in ("root", "admin/api")
    listing = all_vhosts()
    if listing is None:
        # asked once: a second read inside the request cPanel holds open
        # would only wait again (found in review)
        log("EVENT skipped — no vhost list from cPanel: %s" % list(vhosts))
        return
    events = list(event_domains(vhosts, listing))
    # One reading for the whole event: a bulk apply names domains of any
    # number of accounts, and a query each would spend minutes inside the
    # request cPanel holds open. One account is cheaper asked directly,
    # which is also the common case.
    fleet = None
    if len({user for _, user, _ in events}) > 1:
        # a read that did not answer stays None: collapsing it to {} would
        # read as "every account unanswered" and skip every domain of the
        # event, including the gateway returns it must re-mirror. None falls
        # through to the per-account reads below, which go through
        # selectorctl — a different mechanism, and one that may answer.
        fleet = all_selector_versions(with_websites=True)
    # The payload is a routing hint, never evidence: cPanel fires this
    # post-stage hook even for calls it REJECTED, and these payload shapes
    # carry no result to test — so a caller could name a domain they do not
    # own and still steer this root-side handler onto it. Every domain is
    # confirmed against the pin stored in /etc/userdatadomains, which
    # cPanel has already updated by the time this hook runs.
    aliases, stored_pins = load_userdatadomains()
    # every echo of the event retired at once, and each account's domains
    # and document roots gathered once: per domain, a bulk event spent
    # minutes of the request cPanel holds open (found in review). A claim
    # the store does not confirm keeps its intent.
    ours = consume_intents([dom for dom, _, _ in events
                            if (stored_pins or {}).get(dom) == version],
                           version)
    mine, by_account, cascades = {}, vhosts_by_account(listing), {}
    for _, user, vhost in events:
        mine.setdefault(user, []).append(vhost)
    for dom, user, vhost in events:
        stored = (stored_pins or {}).get(dom)
        if stored != version:
            log("EVENT unconfirmed, ignored: %s claims %s, store holds %r "
                "(by %s)" % (dom, version, stored, actor))
            continue
        if vhost.get("php_fpm"):
            # out of coverage: an entry here would outlive the FPM window
            # and keep the domain out of the sync afterwards. The echo is
            # still retired first — the hand-back writes to FPM vhosts, so
            # an intent left standing here would swallow a real admin write
            # of the same value for the rest of its TTL.
            if dom in ours:
                log("ECHO consumed (our own hand-back): %s -> %s"
                    % (dom, version))
            else:
                log("EVENT ignored, domain runs PHP-FPM: %s" % dom)
                moved.append((dom, user, vhost))
            continue
        if dom in ours:
            log("ECHO consumed (our own mirror write): %s -> %s" % (dom, version))
            continue
        # one read per account, not per domain — a routing read only.
        # Concurrent writers are the norm (see record_lock), so nothing
        # that decides ownership may rest on this snapshot: those
        # decisions are re-made under the lock in the write phase below.
        if user not in records:
            records[user] = ledger_entries(user)
            if records[user] is not None and carry_addon_rows(
                    records[user], {v["vhost"] for v in listing}, aliases):
                # an addon's row a pass kept under the subdomain it was made
                # on is the addon's here too, and the write phase carries it
                # on disk whatever the event decides: read as no row, root
                # restating our pin on the addon was taken for a
                # confirmation (found by Bugbot)
                pending.setdefault(user, [])
        if records[user] is None:
            continue  # its record is unusable: left alone, as a pass does
        entry = records[user].get(dom, {})
        restating = False
        if entry.get("version") == version:
            # The stored pin proves the value is on disk, not that this call
            # put it there — cPanel fires this hook for rejected calls too,
            # and a claim of the value already stored matches either way.
            # The ledger records this domain at this version, so the pin has
            # not moved and the event carries no news. Classifying anyway
            # would read a stale mirror as an admin decision, or hand a
            # parked domain back into the sync on nobody's authority.
            #
            # Except root restating a pin of ours, or a tenant through the
            # UAPI, whose result names only the caller's own domains, and
            # only what cPanel confirmed: set in MultiPHP Manager, it is
            # MultiPHP's from then on, as one set before the sync is
            # (restated, in the write phase). Found in review: taken for no
            # news, an admin's later pin above made the sync hand the domain
            # back onto it.
            restating = trusted and entry.get("owner") == "selector" \
                and entry.get("was") != version \
                and from_pkg(version) is not None
            if trusted and entry.get("owner") == "selector" \
                    and entry.get("reason") == "step-aside" \
                    and is_gateway(version, default_pkg):
                # the gateway value a step-aside of ours shows, written
                # explicitly: the domain's own from then on, as a default
                # set before the sync was (found in review: taken for no
                # news, the --disable after it restored the alt-php the
                # domain had arrived with over the admin's default)
                pending.setdefault(user, []).append(
                    (dom, "restate-default", version))
                continue
            if not restating:
                log("EVENT no-op, this version is already recorded: %s -> %s "
                    "(by %s)" % (dom, version, actor))
                continue
        moved.append((dom, user, vhost))
        if user not in states:  # one selector query per account, not per domain
            state = None if fleet is None else fleet.get(user)
            if state is None or state[0] is None:
                # the box-wide read answered for other accounts, not for
                # this one, and no answer is not "nothing to do": ask this
                # account directly, as the chunked pass does
                state = selector_state(user)
            else:
                # a `native` read outside the cage, confirmed as the
                # chunked pass does
                state = fleet_reading_of(user, mine[user], stored_pins,
                                         state)
            states[user] = state
        account_current, isolated = states[user]
        if account_current is None:
            log("EVENT skipped, no selector state: %s" % dom)
            continue
        if account_current is OUTSIDE_CAGEFS:
            # out of coverage, as the handler gap below: an entry here
            # would outlive the account's return to CageFS, and the
            # account's pass hands back what stands of ours
            log("EVENT ignored, %s: %s" % (OUTSIDE_CAGEFS, dom))
            continue
        cur_sel = isolated.get(dom, account_current)
        if restating:
            # only the Selector's version is the Selector's: a pin of ours
            # left behind is a stale mirror the next pass re-pins, and the
            # call restating it may have been refused
            if to_pkg(cur_sel) == version:
                pending.setdefault(user, []).append((dom, "restate", version))
            else:
                log("EVENT no-op, this version is already recorded: %s -> "
                    "%s (by %s)" % (dom, version, actor))
            continue
        # the version cPanel now RESOLVES for the domain, not the pin the
        # event carries: `inherit` is served by the parent's pin (see
        # Coverage.gap), and this listing was read after the write
        gap = coverage.gap(vhost.get("version"), to_pkg(cur_sel), default_pkg)
        if gap:
            # out of coverage, as FPM above: an entry here would outlive
            # the handler change that brings the domain back
            log("EVENT ignored, %s: %s" % (gap, dom))
            above = None
            if is_gateway(version, default_pkg):
                if user not in cascades:
                    cascades[user] = document_root_groups(
                        by_account.get(user, []))
                above = pin_of_ours_above(dom, cascades[user], records[user],
                                          stored_pins)
            if above is not None:
                # handed to the gateway, it runs the pin of ours above it
                # at once, which serves the Selector's version for that
                # domain, not necessarily for this one: the account's pass
                # judges it now (found in review: it ran the parent's 8.1
                # with the server-wide extensions until the daily run)
                log("EVENT %s -> %s runs the pin of the sync's on %s: "
                    "re-judging the account" % (dom, version, above))
                remirror.add(user)
            continue
        verdict = classify_event(
            version, to_pkg(cur_sel), default_pkg, dom in isolated)
        if verdict == "gateway-return":
            # drop any entry; the mirror pass after this loop rebuilds the
            # ledger entry for this domain
            pending.setdefault(user, []).append((dom, "clear", None))
            log("GATEWAY-RETURN: %s (by %s) -> back under selector; "
                "resuming mirror" % (dom, actor))
            remirror.add(user)
        elif verdict == "mirror-confirm":
            # whether this may claim the pin depends on who owns it at
            # write time, so the decision and its log live in the write
            # phase, under the lock
            pending.setdefault(user, []).append((dom, "mirror", version))
        else:  # takeover — on an isolated website too (classify_event)
            pending.setdefault(user, []).append((dom, "takeover", version))
            log("TAKEOVER: %s -> %s (by %s); mirroring paused for domain"
                % (dom, version, actor))

    # one write per account, not per classified domain: each one is an
    # fsync inside the request cPanel holds open. Written before the pass
    # below, which rebuilds the entries a gateway return dropped (and
    # never called while the record lock is held — it takes it itself).
    #
    # Every entry is re-read HERE, inside the lock, and the ownership
    # decisions are made against it rather than against the snapshot the
    # classification above ran on: that snapshot predates the selector
    # queries, so a takeover recorded by another
    # writer in between would otherwise be overwritten — handing an
    # admin-pinned domain back to the mirror, for the next selector change
    # to overwrite.
    # cPanel writes every domain sharing a document root with one a call
    # names, and raises its hook naming that one: the mates' echoes carry no
    # mark of ours, the named domain's does (record_pending)
    roots = document_roots(v for v in listing if v.get("account") in pending)
    groups = {}
    for dom, root in roots.items():
        groups.setdefault(root, set()).add(dom)
    listed = {v["vhost"] for v in listing}
    for user, changes in pending.items():
        now = time.strftime("%F %T")
        try:
            with updated_record(user) as rec:
                # an addon's row a pass kept under the subdomain it was made
                # on: read as no row, the confirmation below recorded our own
                # pin as the one it arrived with (found in review)
                for old, new in carry_addon_rows(rec["domains"], listed,
                                                 aliases):
                    log("LEDGER-CARRIED %s -> %s: the addon parked on that "
                        "subdomain" % (old, new))

                # taken before any claim below clears a mark: a write of
                # ours in flight on a domain is one whose pending mark, on
                # it or a mate, names the version, while a pass of ours
                # holds the account (found in the final review: any pass
                # holding it made an admin's write the sync's)
                marks = {d: e["pending"].get("version")
                         for d, e in rec["domains"].items()
                         if isinstance(e, dict)
                         and isinstance(e.get("pending"), dict)}
                running = pass_running(user)

                def group_in_flight(dom, version_of):
                    return running and any(
                        marks.get(d) == version_of
                        for d in groups.get(roots.get(dom), {dom}))

                for dom, kind, version_of in changes:
                    entry = rec["domains"].get(dom, {})
                    if kind == "restate-default":
                        # re-made against the state we would overwrite, as
                        # a restatement is: still our step-aside at that
                        # value, and no write of ours in flight on it
                        if entry.get("owner") == "selector" \
                                and entry.get("reason") == "step-aside" \
                                and entry.get("version") == version_of \
                                and not group_in_flight(dom, version_of) \
                                and not isinstance(entry.get("pending"), dict):
                            rec["domains"][dom] = {
                                "owner": "multiphp", "reason": "released",
                                "version": version_of, "was": version_of,
                                "since": now}
                            log("RESTATED: %s -> %s (by %s); the domain's own "
                                "from now on, as without the sync"
                                % (dom, version_of, actor))
                        else:
                            log("EVENT no-op, this version is already "
                                "recorded: %s -> %s (by %s)"
                                % (dom, version_of, actor))
                        continue
                    if kind == "restate":
                        # re-made against the state we would overwrite: still
                        # a pin of ours at that value, and no write of ours
                        # on it in flight, whose echo this may be: every one
                        # is marked pending before it is made (found in the
                        # final review: any pass holding the account dropped
                        # an admin's restatement)
                        ours_in_flight = group_in_flight(dom, version_of) or (
                            isinstance(entry.get("pending"), dict)
                            and entry["pending"].get("version") == version_of)
                        if entry.get("owner") == "selector" \
                                and entry.get("version") == version_of \
                                and entry.get("was") != version_of \
                                and not ours_in_flight:
                            rec["domains"][dom] = {
                                "owner": "multiphp", "reason": "takeover",
                                "version": version_of, "actor": actor,
                                "since": since_of(entry, "multiphp", now)}
                            log("RESTATED: %s -> %s (by %s); MultiPHP's from "
                                "now on, as a pin set before the sync is"
                                % (dom, version_of, actor))
                        else:
                            log("EVENT no-op, this version is already "
                                "recorded: %s -> %s (by %s)"
                                % (dom, version_of, actor))
                        continue
                    if kind != "clear" and entry.get("version") == version_of:
                        # the same no-op the snapshot side applies, re-made
                        # against the state we would overwrite: this domain is
                        # already recorded at this version, so the pin has not
                        # moved and the event carries no news. Writing anyway
                        # would attribute our own mirror to an admin and
                        # freeze the domain out of the sync.
                        log("EVENT no-op, this version is already recorded: %s -> "
                            "%s (by %s)" % (dom, version_of, actor))
                        continue
                    if kind == "clear":
                        rec["domains"].pop(dom, None)
                    elif kind == "mirror":
                        if entry.get("reason") in ("takeover",
                                                   "takeover-as-found"):
                            # the selector caught up to the version the admin
                            # pinned. A coincidence is not a hand-back:
                            # claiming the pin would let the next selector
                            # change overwrite a decision only a gateway
                            # return may end.
                            log("SAME-VALUE on a MultiPHP-owned domain, "
                                "ownership unchanged: %s -> %s (by %s)"
                                % (dom, version_of, actor))
                            continue
                        # Only a write of ours is the Selector's: one whose
                        # echo was missed. Every write of ours that claims is
                        # marked pending before it is made, with what it
                        # replaced (record_pending), and the claim takes
                        # that; a mate cPanel wrote with a domain of ours in
                        # flight names none, and record_written does,
                        # moments behind. Anything else was set in MultiPHP
                        # Manager, and is MultiPHP's, also at the Selector's
                        # version: served with the Selector's settings only
                        # while the two agree, it stays on its version when
                        # the Selector moves, without the sync (found in
                        # review: taken for the sync's, it followed every
                        # later Selector change). Decided 2026-10-12.
                        pending = entry.get("pending")
                        if isinstance(pending, dict) \
                                and pending.get("version") == version_of:
                            arrived = arrival_of(pending.get("was"),
                                                 pending.get("bare"))
                        elif group_in_flight(dom, version_of):
                            arrived = None
                        else:
                            rec["domains"][dom] = {
                                "owner": "multiphp", "reason": "takeover",
                                "version": version_of, "actor": actor,
                                "since": since_of(entry, "multiphp", now)}
                            log("TAKEOVER: %s -> %s (by %s), the PHP "
                                "Selector's version, set in MultiPHP "
                                "Manager; mirroring paused for domain"
                                % (dom, version_of, actor))
                            continue
                        rec["domains"][dom] = selector_claim(
                            entry, version_of, now, arrived=arrived)
                        log("MIRROR-CONFIRM: %s -> %s (by %s); our own write, "
                            "selector keeps control"
                            % (dom, version_of, actor))
                    else:
                        reason = ("takeover" if kind == "takeover"
                                  else "takeover-as-found")
                        rec["domains"][dom] = {
                            "owner": "multiphp", "reason": reason,
                            "version": version_of, "actor": actor,
                            "since": since_of(entry, "multiphp", now),
                        }
        except RecordUnusable as e:
            # unusable since the routing read: nothing of this event is
            # recorded for the account, and its file stays as it is
            log("EVENT not recorded for %s — %s" % (user, e.note()))

    # the pins this event moved reach the domains nested in their document
    # roots, and the account's pass re-judges those now rather than on its
    # next trigger, the daily run at worst (parent_pin_accounts). Not where
    # a reconcile follows, which runs every account's pass anyway.
    rejudge = set() if len(remirror) > 1 else parent_pin_accounts(
        [m for m in moved if m[1] not in remirror], version, listing,
        stored_pins)
    if load_conf()["selector_to_multiphp"] != "on":
        # a hand-back under way or due (parent_pin_accounts): no pass runs
        dispatch_parent_pin(rejudge, pace)
        rejudge = set()

    # one complete pass per account, after every domain of the event has
    # been classified: a mirror pass covers the whole account anyway, so
    # running it per domain would repeat it N times inside a hook that
    # cPanel is holding an admin's request open for
    if len(remirror | rejudge) > 1:
        # a pass each, inline, would rebuild Apache configuration once per
        # account with the admin's request waiting behind every rebuild;
        # the reconcile writes them a chunk of accounts per call instead,
        # and its fleet lock and request marker collapse this into one walk.
        log("GATEWAY-RETURN across %d accounts — dispatching convergence"
            % len(remirror | rejudge))
        spawn_reconcile("bulk-gateway-return")
    else:
        for account in remirror:
            guarded_mirror(account, "gateway-return", pace=pace)
        for account in rejudge:
            guarded_mirror(account, "parent-pin", pace=pace)


# handle_fpm_event's answer when it dispatched the fleet pass: every
# account is covered
FLEET = "every account"


def handle_fpm_event(vhosts, fpm_on, actor, pace=False):
    """Process a versionless php_fpm toggle event (coverage boundary).
    `pace` as in handle_event.

    FPM on: the domain leaves sync coverage, and cPanel pools whatever
    MultiPHP holds — so a pin of ours has to come back, or it serves our
    alt-php outside the cage without the user's configuration. An entry
    proving the pin is ours therefore arms a pass, which withdraws it and
    records the release — or, if php_fpm has not flipped in the vhost
    listing yet, leaves it to the reconcile (see the arming site below).
    A domain with no entry of ours gets one marking the exit, which FPM
    off then drops.
    FPM off: the domain rejoins — drop an entry that existed only for the
    exit, then run a mirror pass for the account (re-pins if the pin
    drifted while out of coverage).

    Returns the accounts a pass of this event's judged (FLEET when it
    dispatched the fleet pass), or None when it ran none."""
    if load_conf()["multiphp_to_selector"] != "on":
        log("FPM EVENT ignored — multiphp_to_selector is off: %s fpm=%s"
            % (vhosts, fpm_on))
        return
    if selector_suspended(system_default()):
        log("FPM EVENT ignored — the selector is disabled by the system "
            "default: %s fpm=%s" % (vhosts, fpm_on))
        return
    # Where the sync does not act, its FPM BOOKKEEPING is pointless: an
    # entry would be the only thing in the ledger of a box nothing is ever
    # written on. The SNAPSHOT below is not bookkeeping, though, and is
    # taken whatever this says — a coverage reading that fails is most
    # likely to fail here, since an FPM toggle rebuilds the very Apache
    # configuration `httpd -M` parses, and this event is the last moment a
    # tenant's pool tuning can be copied before a disable deletes it.
    #
    # That same likelihood is why a failed reading does not end a RETURN
    # here either: see the dispatch after the loop.
    coverage = read_coverage()
    unread = coverage is None
    inert = NO_WEB_SERVER if unread else coverage.inert
    remirror, pending, deferred = set(), {}, set()
    handback = set()  # accounts with a pin of ours to withdraw on FPM-on
    covered, fleet = set(), False  # what the passes below judge
    # an addon's row a pass left under the subdomain it was made on reads
    # as no row of ours unless carried (carry_addon_rows; found in review:
    # no hand-back was armed, and the fpm mark below then kept the carry
    # out for good)
    listing = all_vhosts()
    if listing is None:
        log("EVENT skipped — no vhost list from cPanel: %s" % list(vhosts))
        return
    aliases, _ = load_userdatadomains()
    listed = {v["vhost"] for v in listing}
    for dom, user, vhost in event_domains(vhosts, listing, aliases):
        # Confirm the claim as the version path does: this hook fires for
        # calls cPanel rejected too. The userdata php_fpm flag lags on an
        # enable, so it cannot serve as evidence; the pool yaml can, since
        # cPanel writes it before an enable hook and removes it before a
        # disable hook (both measured).
        #
        # Residual, accepted: a rejected disable naming an already-off
        # domain still confirms. It costs one convergence pass, which can
        # overwrite nothing the ledger does not prove is ours — and where
        # coverage went unread the ledger is asked outright, below.
        if os.path.exists(FPM_POOL_SRC % (user, dom)) is not bool(fpm_on):
            log("FPM EVENT unconfirmed, ignored: %s claims fpm=%s but the "
                "pool file %s (by %s)"
                % (dom, bool(fpm_on),
                   "is absent" if fpm_on else "is still there", actor))
            continue
        if fpm_on:
            # the event says FPM is on, so snapshot even if the userdata
            # entry still reads php_fpm=0 (post-hook the flag may not have
            # flipped, but cPanel has already written the pool yaml, and
            # this is the only chance to copy it before a later disable
            # deletes it)
            snapshot_fpm_pools(user, [dict(vhost, php_fpm=True)])
        # the snapshot is the tenant's tuning, not the ledger's: taken
        # above whatever the record says; everything below reads it
        entries = ledger_entries(user)
        if entries is None:
            continue  # its record is unusable: left alone, as a pass does
        carry_addon_rows(entries, listed, aliases)
        if inert:
            log("FPM EVENT recorded nothing — %s: %s fpm=%s (by %s)"
                % (inert, dom, bool(fpm_on), actor))
            # Only a domain the ledger marks as having LEFT coverage has a
            # return to converge. The pool file confirms the toggle landed,
            # not that anything changed: a refused disable naming a domain
            # whose FPM was already off confirms just as well, and without
            # this would arm a root pass for that domain's owner.
            if (not fpm_on
                    and entries.get(dom, {}).get("reason") == "fpm"):
                deferred.add(user)
            # An ENABLE over a pin of ours needs the same treatment, and
            # only when the reading merely failed: a genuinely inert box
            # took the domain out of coverage before FPM did, so its pin
            # has already gone back. Note the coincidence that makes this
            # the likely case rather than an exotic one — enabling FPM
            # rebuilds Apache, and this hook fires while that is happening,
            # which is exactly when `httpd -M` has nothing to say.
            if (unread and fpm_on
                    and entries.get(dom, {}).get("owner") == "selector"):
                deferred.add(user)
            continue
        if fpm_on:
            pending.setdefault(user, []).append((dom, vhost.get("version")))
            log("FPM-EXIT: %s (by %s) -> out of coverage" % (dom, actor))
            # A pin of ours must not be left for cPanel to pool: it would
            # serve our alt-php outside the cage, without the user's
            # Selector configuration. Arm a pass now rather than leaving it
            # to the next reconcile — the site is wrong in the meantime.
            # The pass re-proves ownership itself, so an approximate
            # trigger here costs at most one converged no-op pass.
            #
            # It reads the vhost list afresh, and php_fpm lags there on an
            # enable (see the snapshot above), so a pass that runs before
            # the flag flips judges the domain covered and withdraws
            # nothing. Nothing periodic catches it — the daily cron only
            # checks — so it waits for the account's next pass: a Selector
            # change, an event, the boot catch-up or an admin --reconcile.
            # Measured on a 230-account box the flag had flipped: the
            # withdrawal landed four seconds after the toggle. Worth
            # re-measuring if that ever stops holding, because the gap is
            # served outside the cage while it lasts.
            if entries.get(dom, {}).get("owner") == "selector":
                handback.add(user)
        else:
            pending.setdefault(user, []).append((dom, None))
            log("FPM-RETURN: %s (by %s) -> rejoins coverage; "
                "resuming mirror" % (dom, actor))
            remirror.add(user)

    # one write per account, not per toggled domain: every write is an
    # fsync, and one toggle event names domains of any number of accounts
    for user, changes in pending.items():
        try:
            with updated_record(user) as rec:
                for old, new in carry_addon_rows(rec["domains"], listed,
                                                 aliases):
                    log("LEDGER-CARRIED %s -> %s: the addon parked on that "
                        "subdomain" % (old, new))
                for dom, version in changes:
                    if fpm_on:
                        rec["domains"].setdefault(dom, {
                            "owner": "multiphp", "reason": "fpm",
                            "version": version,
                            "since": time.strftime("%F %T"),
                        })
                    elif rec["domains"].get(dom, {}).get("reason") == "fpm":
                        # an entry that exists only because of FPM goes with
                        # it; anything else records an owner and outlives
                        # the toggle
                        rec["domains"].pop(dom)
        except RecordUnusable as e:
            log("FPM EVENT not recorded for %s — %s" % (user, e.note()))

    if unread and deferred:
        # Both halves need convergence when the reading merely failed. A
        # RETURN rejoins coverage wearing whatever pin it had on FPM; an
        # ENABLE leaves a pin of ours for cPanel to pool. Either way the
        # pass that would have run runs anyway: it takes its own reading,
        # and refuses again if that still fails. An inert box is the only
        # one entitled to drop either, and `deferred` holds only accounts
        # whose toggle was confirmed against the pool file, so a rejected
        # call arms nothing.
        log("FPM %s with no coverage reading (%d account(s)) — deferring "
            "to a pass" % ("ENABLE" if fpm_on else "RETURN", len(deferred)))
        if len(deferred) > 1:
            # and it collapses like the readable path: this is the LIKELY
            # path for an enable, since enabling FPM rebuilds Apache while
            # this hook runs, so a pass per account inline is the cost the
            # collapse exists to avoid rather than a rare one
            spawn_reconcile("bulk-coverage-unread")
            fleet = True
        else:
            for account in deferred:
                guarded_mirror(account, "coverage-unread", pace=pace)
                covered.add(account)
    elif len(remirror) > 1:
        # the reasoning a bulk gateway return already applies: a pass each,
        # inline, rebuilds Apache configuration once per account with the
        # admin's request waiting behind every rebuild
        log("FPM-RETURN across %d accounts — dispatching convergence"
            % len(remirror))
        spawn_reconcile("bulk-fpm-return")
        fleet = True
    else:
        for account in remirror:
            guarded_mirror(account, "fpm-return", pace=pace)
            covered.add(account)
    # one toggle direction per event, so this never overlaps `remirror`
    if len(handback) > 1:
        # same reasoning as the RETURN half above: a pass each, inline,
        # rebuilds Apache configuration once per account with the admin's
        # request held open behind every rebuild
        log("FPM-EXIT across %d accounts — dispatching convergence"
            % len(handback))
        spawn_reconcile("bulk-fpm-exit")
        fleet = True
    else:
        for account in handback:
            guarded_mirror(account, "fpm-exit", pace=pace)
            covered.add(account)
    return FLEET if fleet else covered


# A note of the start of an account's modification that names no process,
# older than this, is not its end's: WHM modifies an account in seconds.
# One that names the process modifying it holds while that lives, up to
# MODIFY_TRACKED_TTL: a username change renames its databases too (found in
# review: an hour could run out).
MODIFY_TTL = 3600
MODIFY_TRACKED_TTL = 86400
# how long the pass a modification held waits for it to be done (wait_out)
MODIFY_WAIT_MAX = 600


def account_main_domain(user):
    """The account's main domain (DNS in its cPanel users file), or None."""
    try:
        with open(os.path.join(CPANEL_USERS_DIR, user)) as f:
            for line in f:
                if line.startswith("DNS="):
                    return line.split("=", 1)[1].strip() or None
    except OSError:
        pass
    return None


def modification_names(user, newuser, uid=None):
    """The names a modification of `user` holds: its own, and the new
    username `newuser` it asks for, unless another account has that name
    already. WHM refuses that rename: found by Bugbot, a post stage that
    never came left that account held for as long as the hook's parent
    lived, and one that came, which still names it, ended that account's
    own modification's hold, or a retry held it until it was done. `uid`:
    the account's, as noted at the start (renamed_away)."""
    names = [user]
    if isinstance(newuser, str) and ACCOUNT_NAME.match(newuser) \
            and newuser != user and (
                account_uid(newuser) is None
                # renamed (modify_moves): the name is this account's now
                or renamed_away(user, newuser, uid)):
        names.append(newuser)
    return names


def modification_holds(user, names, uid):
    """The names among `names` whose holds are this modification's: the old
    name `user` not where a new account has it, its uid not `uid`, the one
    noted at the start, whose own modification may hold that name. A hold
    of ours left there holds nothing for it (held_for_a_namesake). Found in
    review for the retry's start, by Bugbot for its end."""
    return [name for name in names
            if name != user or not isinstance(uid, int)
            or account_uid(user) in (None, uid)]


def handle_modify_start(user, modifier=None, newuser=None):
    """WHM's Modify Account begins (Whostmgr Accounts::Modify, pre): note
    the account's main domain, which its end no longer knows
    (handle_modify), and the process `modifier` modifying it (the hook's
    parent). Until the end the account is held (modifying): WHM renames its
    userdata, and a new username's system user, well before it raises the
    post stage, and a pass, a prune or a release in between saw the
    renamed domains with no row of theirs (found in review). So is a new
    username `newuser`, the call asks for: found in review, a PHP Selector
    change under it found nothing of the sync's to step aside, and its
    sites ran the version they left with the server-wide extensions until
    the end. Only for an account the sync has a record of: it has nothing
    to carry otherwise, and never a new username another account has
    already. Quick and quiet, since cPanel waits on this stage before it
    modifies the account."""
    if not isinstance(user, str) or not ACCOUNT_NAME.match(user) \
            or not os.path.exists(record_path(user)):
        return
    main = account_main_domain(user)
    if not main:
        return
    note = {"domain": main}
    started = process_started(modifier) if modifier else None
    if started is not None:
        note.update(pid=int(modifier), started=started)
    uid = account_uid(user)
    if uid is not None:
        note["uid"] = uid  # held_for_a_namesake
    for name in modification_names(user, newuser):
        try:
            with open_private(modify_pending_path(name), "w") as f:
                json.dump(note, f)
        except OSError as e:
            log("STATE %s could not be written: %s"
                % (modify_pending_path(name), e))


def modify_note(user):
    """The note of the account's modification in progress
    (handle_modify_start), or None: none, or one whose process has gone,
    that is too old, or that a deleted account of the name left
    (held_for_a_namesake), which all take it away."""
    path = modify_pending_path(user)
    try:
        age = time.time() - os.path.getmtime(path)
        with open(path) as f:
            note = json.load(f)
    except (OSError, ValueError):
        return None
    if not isinstance(note, dict):
        return None
    pid, started = note.get("pid"), note.get("started")
    if not held_for_a_namesake(user, note):
        if pid is not None and started is not None:
            if abs(age) < MODIFY_TRACKED_TTL \
                    and process_started(pid) == started:
                return note
        elif abs(age) < MODIFY_TTL:
            return note
    with contextlib.suppress(OSError):
        os.unlink(path)
    return None


def noted_uid(user):
    """The uid a modification's note under `user` keeps (handle_modify_start,
    spawn_finish_rename), read as it stands, or None."""
    try:
        with open(modify_pending_path(user)) as f:
            uid = json.load(f).get("uid")
    except (OSError, ValueError, AttributeError):
        return None
    return uid if isinstance(uid, int) else None


def mark_modify_held(user):
    """A pass was held while the account was being modified: its end runs
    the pass (handle_modify)."""
    try:
        with open_private(modify_held_path(user), "w"):
            pass
    except OSError as e:
        log("STATE %s could not be written: %s" % (modify_held_path(user), e))


def modifying(user):
    """Whether WHM's Modify Account is between its pre and post stages for
    the account: no pass, prune or release touches it then
    (handle_modify_start)."""
    return isinstance(user, str) and modify_note(user) is not None


def handle_modify(user, newuser, domain):
    """WHM's Modify Account ended (Accounts::Modify, post). cPanel keeps
    every userdata key, the phpversion included, under the new names: a
    username change keeps the domains, and a main domain change renames the
    main domain and every <x>.<old main> subdomain (an addon keeps its own
    name). The ledger is keyed by those names, and under the old ones it
    proved nothing: a PHP Selector change before the next pass stranded the
    sync's pins on the version the account left, served with the
    server-wide extensions, and otherwise the next pass took them for pins
    set in MultiPHP Manager, and a --disable left them standing (found in
    review). So the account's record
    follows a new username (move_account_state), and its rows the renamed
    domains (carry_renamed_rows), the old main domain as noted at the start
    (handle_modify_start). Without that note no row moves.

    The hold ends only once they have moved (end_modify_holds): found in
    review, ended first, a fleet prune while a move waited for a lock took
    the record. Where a pass held the account past the wait, the listing
    did not read, or the moves raised, they move later, under the holds
    still, in a retry of their own (finish_rename):
    found by Bugbot, the holds ended, and the next fleet prune took the
    record of the username gone, or the rows of the main domain gone. A
    pass the hold held runs then, once the process modifying
    the account is done (spawn_mirror's `after`), so after CloudLinux's own
    Modify Account hook, which re-enables a renamed main domain's
    isolation; nothing held, no pass (found in review: one for every
    modification, a package or a quota change too), but for a rename: in
    CageFS's "Disable All" mode the enable stays under the old name, and
    the pass hands the sync's pins on the account, out of CageFS, back at
    once (OUTSIDE_CAGEFS; found in CI). With the mirror off, the
    withdrawal walk where one is due."""
    if not isinstance(user, str) or not ACCOUNT_NAME.match(user):
        return
    note = modify_note(user)
    if note is None and isinstance(newuser, str) \
            and ACCOUNT_NAME.match(newuser) and newuser != user:
        # the note under the name the account has now: a new account that
        # took the old name by the post stage makes the old one a
        # namesake's to it (found by Bugbot: read as no rename at all)
        note = modify_note(newuser)
    note = note or {}
    names = modification_names(user, newuser, note.get("uid"))
    account, done = None, False
    try:
        account, done = modify_moves(user, newuser, domain, note.get("domain"),
                                     note.get("uid"))
    finally:
        if not done:
            # moves that did not finish, one that raised too, go to the
            # retry under the holds still: found by Bugbot, an error (a
            # full disk saving the record) ended them, and the next fleet
            # prune took the record of the username gone
            spawn_finish_rename(user, newuser, domain, note)
    if not done:
        return
    held = end_modify_holds(modification_holds(user, names, note.get("uid")))
    modified(account or user, (held or len(names) > 1) and note,
             (note["pid"], note["started"])
             if "pid" in note and "started" in note else None)


def modified(account, held, after):
    """A modification's end, once its holds are gone: the pass they held,
    or a rename's, after the process `after` names (handle_modify)."""
    if not held:
        return
    if load_conf()["selector_to_multiphp"] == "on":
        spawn_mirror(account, "account-modified", after=after)
    elif withdrawal_due():
        # with the mirror off, what the hold held is a hand-back's
        spawn_withdraw("account-modified")


# how many times finish_rename tries the moves, each waiting CHANGE_LOCK_WAIT
# at most for a pass holding the account; RENAME_PAUSE apart, since a listing
# that does not read fails at once
RENAME_RETRIES = 10
RENAME_PAUSE = 30


def spawn_finish_rename(user, newuser, domain, note):
    """finish_rename, detached: cPanel's request, which the post stage
    runs in, must not wait for it. The holds name the retry from the moment
    it starts, while that request, which they named, still runs: no pass,
    prune or release slips in between."""
    names = modification_names(user, newuser, note.get("uid"))
    argv = [sys.executable, "-Ibb", os.path.abspath(__file__),
            "--finish-rename", "--user", user]
    if names[1:]:
        argv += ["--to", newuser]
    if isinstance(domain, str) and domain:
        argv += ["--domain", domain]
    if isinstance(note.get("domain"), str):
        argv += ["--main", note["domain"]]
    if "pid" in note and "started" in note:
        argv += ["--after", "%d:%s" % (note["pid"], note["started"])]
    child = subprocess.Popen(argv, stdout=subprocess.DEVNULL,
                             stderr=subprocess.DEVNULL, env=detached_env(),
                             start_new_session=True)
    held = {"pid": child.pid, "started": process_started(child.pid)}
    if isinstance(note.get("domain"), str):
        held["domain"] = note["domain"]
    if "uid" in note:
        held["uid"] = note["uid"]
    for name in modification_holds(user, names, note.get("uid")):
        try:
            with open_private(modify_pending_path(name), "w") as f:
                json.dump(held, f)
        except OSError as e:
            log("STATE %s could not be written: %s"
                % (modify_pending_path(name), e))
    log("RENAME %s: the record and its rows move in a retry (a pass holds "
        "the account, or the listing did not read), the account held "
        "meanwhile" % user)


def finish_rename(user, newuser, domain, main, after):
    """handle_modify's moves, retried while a pass held the account or the
    listing did not read (RENAME_RETRIES times at most, RENAME_PAUSE
    apart), then the modification's end: its holds go, which name this
    process (spawn_finish_rename), and what they held runs. `after`: the
    process modifying the account, as its note named it
    ("<pid>:<started>")."""
    names = [user]
    if isinstance(newuser, str) and ACCOUNT_NAME.match(newuser) \
            and newuser != user:
        names.append(newuser)
    # the account's uid, which spawn_finish_rename keeps in its note under
    # the name the account has now
    uid = noted_uid(names[-1])
    account, done, failed = user, False, None
    for attempt in range(RENAME_RETRIES):
        if attempt:
            time.sleep(RENAME_PAUSE)
        try:
            account, done = modify_moves(user, newuser, domain, main, uid)
        except OSError as e:
            # the full disk handle_modify sends the moves here for: found
            # in the final review, the first raise ended the retry, its
            # holds went with it, and a prune took the record
            log("RENAME %s: the moves failed (%s); tried again" % (user, e))
            failed = e
            continue
        if done:
            break
    if not done:
        log("RENAME %s: no try of %d got through (a pass held the account, "
            "the listing did not read, or the moves failed); the record and "
            "its rows stay under the old names" % (user, RENAME_RETRIES))
        # the renamed account's pins of the sync read as MultiPHP's now:
        # recorded, as the crash the first raise was before the retry
        # caught it (found in the final check)
        remember("pass-aborted", "rename", why=(
            "the moves failed: %s" % (failed.strerror or failed)
            if failed is not None else "no try got through"))
    held = end_modify_holds(modification_holds(user, names, uid))
    pid, _, started = (after or "").partition(":")
    modified(account, held or len(names) > 1, (int(pid), started)
             if pid.isdigit() and started else None)


def renamed_away(user, newuser, uid):
    """Whether a modification renamed the account `user` to `newuser`:
    cPanel's users file is under the new name, and the account of that name
    is the one modified, by its uid as noted at the start (`uid`). One under
    the old name again is a new account that took it while the rename's
    retry waited (found by Bugbot: read as no rename at all). Without a
    noted uid, a users file still under the old name means no rename."""
    if not os.path.exists(os.path.join(CPANEL_USERS_DIR, newuser)):
        return False
    if isinstance(uid, int):
        return account_uid(newuser) == uid
    return not os.path.exists(os.path.join(CPANEL_USERS_DIR, user))


def modify_moves(user, newuser, domain, main, uid=None):
    """handle_modify's moves: the record to a new username, the rows to a
    renamed main domain `domain` from `main` (as noted at the start).
    `uid`: the account's, as noted at the start (renamed_away). Returns
    (the account's name from then on, whether nothing was left for a pass
    holding the account to finish_rename)."""
    account = user
    if isinstance(newuser, str) and ACCOUNT_NAME.match(newuser) \
            and newuser != user:
        if not renamed_away(user, newuser, uid):
            # the post stage of a modification that did not rename the
            # account (cPanel's users file is still under the old name):
            # the record stays with the account it proves
            log("RENAME %s -> %s: the account was not renamed; its record "
                "stays" % (user, newuser))
        elif os.path.exists(os.path.join(CPANEL_USERS_DIR, user)):
            # a new account took the old name meanwhile: the record left
            # under it goes on to the renamed account as at that account's
            # creation (forget_account, now or done already), and its rows
            # follow the renamed domains below (found by Bugbot: they went
            # on under the old domains, and the next fleet prune dropped
            # them)
            forget_account(user)
            account = newuser
        else:
            moved = move_account_state(user, newuser)
            if moved is None:
                return user, False
            if not moved:
                return user, True
            account = newuser
    if isinstance(main, str) and isinstance(domain, str) and domain \
            and main.lower() != domain.lower():
        return account, carry_renamed_rows(account, main.lower(),
                                           domain.lower())
    return account, True


def end_modify_holds(names):
    """End a modification's holds on the account's names, each under its
    pass lock, which a pass asks under too (guarded_mirror, write_chunk):
    one either ran held before, its mark (modify_held_path) taken here, or
    runs after, unheld. Returns whether a pass was held. A lock not had in
    CHANGE_LOCK_WAIT ends the hold all the same, and counts as held."""
    held = False
    for name in names:
        with path_lock_wait(pass_lock_path(name), CHANGE_LOCK_WAIT) as alone:
            held = held or not alone
            for path in (modify_pending_path(name), modify_held_path(name)):
                try:
                    os.unlink(path)
                except OSError:
                    continue
                held = held or path == modify_held_path(name)
    return held


def move_account_state(old, new):
    """Carry an account's record (and its PHP-FPM pool copies) to its new
    username, under both names' pass and record locks. A record the new
    name has already (a pass in between, which took the sync's pins for
    the ones the domains arrived with) keeps only what the old one does not
    prove. False when nothing could move, None when a pass held the account
    past the wait (finish_rename retries then)."""
    with path_lock_wait(pass_lock_path(old), CHANGE_LOCK_WAIT) as one, \
            path_lock_wait(pass_lock_path(new), CHANGE_LOCK_WAIT) as two:
        if not (one and two):
            log("RENAME %s -> %s: a pass held the account; its record stays "
                "under the old name for now" % (old, new))
            return None
        with record_lock(old), record_lock(new):
            try:
                record = renamed_record(old, new)
                kept = load_record(new)
            except RecordUnusable as e:
                log("RENAME %s -> %s: %s" % (old, new, e.note()))
                return False
            if record is None:
                log("RENAME %s -> %s: the record under the old name is a new "
                    "account's of that name; it stays with it" % (old, new))
                return True
            if record["domains"]:
                kept["domains"].update(record["domains"])
                save_record(new, kept)
            with contextlib.suppress(OSError):
                os.unlink(record_path(old))
        if os.path.isdir(pool_dir(old)) and not os.path.exists(pool_dir(new)):
            with contextlib.suppress(OSError):
                os.rename(pool_dir(old), pool_dir(new))
    log("RENAME %s -> %s: the record follows the account" % (old, new))
    return True


def renamed_record(old, new):
    """Under both record locks: the record under `old` that a rename to
    `new` carries, or None when it is not the renamed account's. While no
    account has the old name, the record there is the renamed account's.
    Once one has (WHM made it while the move waited for the pass locks),
    the record goes only where its stamps prove `new` (renamed_to); any
    other is the new account's own, left with it. Found in review: read as
    a deleted namesake's, nothing moved and the record was deleted, and a
    new account's own record made in the wait would have moved instead."""
    record = load_record(old)
    if not os.path.exists(os.path.join(CPANEL_USERS_DIR, old)):
        return record
    try:
        with open(record_path(old)) as f:
            raw = json.load(f)
    except FileNotFoundError:
        return {"domains": {}}
    except (OSError, ValueError):
        return None
    rows = raw.get("domains") if isinstance(raw, dict) else None
    if not isinstance(rows, dict) \
            or not all(isinstance(e, dict) for e in rows.values()) \
            or renamed_to(old, raw) != new:
        return None
    return raw


def carry_renamed_rows(user, old, new):
    """Carry the rows of a renamed main domain and of every <x>.<old>
    subdomain to the names cPanel now lists, as cPanel carried their
    versions. A row whose new name cPanel does not list stays where it is,
    but for an addon's subdomain, which cPanel never lists: one a pass left
    under it is carried on to the addon its new name is an alias of
    (carry_addon_rows; found in review: under the old name, which no alias
    names any more, the next prune dropped it and --disable took the
    addon's pin for an admin's).
    One the new name has already (a pass in between, which took the sync's
    pins there for what the domains arrived with) gives way to the old one,
    as move_account_state's does (found in review: it won, and a
    --disable left the sync's pins standing). False where a pass held the
    account past the wait, or the listing did not read (found in review:
    taken for done, the holds ended with the rows under the old names, and
    the next fleet prune dropped them): finish_rename retries then."""
    aliases, _, vhosts = load_userdata_listing()
    if vhosts is None:
        log("RENAME %s: %s -> %s, but no listing to carry the rows by yet"
            % (user, old, new))
        return False
    listed = {v["vhost"] for v in vhosts if v.get("account") == user}
    moved, carried = [], []
    with path_lock_wait(pass_lock_path(user), CHANGE_LOCK_WAIT) as acquired:
        if not acquired:
            log("RENAME %s: %s -> %s, but a pass held the account; its rows "
                "stay under the old names for now" % (user, old, new))
            return False
        try:
            with updated_record(user) as rec:
                for dom in sorted(rec["domains"]):
                    if dom == old:
                        renamed = new
                    elif dom.endswith("." + old):
                        renamed = dom[:-len(old)] + new
                    else:
                        continue
                    if (renamed in listed or aliases.get(renamed) in listed) \
                            and dom not in listed:
                        rec["domains"][renamed] = rec["domains"].pop(dom)
                        moved.append((dom, renamed))
                carried = carry_addon_rows(rec["domains"], listed, aliases)
        except RecordUnusable as e:
            log("RENAME %s: %s" % (user, e.note()))
            return True
    for dom, renamed in moved:
        with contextlib.suppress(OSError):
            os.rename(pool_path(user, dom), pool_path(user, renamed))
        log("LEDGER-CARRIED %s -> %s: the account's main domain was renamed"
            % (dom, renamed))
    for dom, addon in carried:
        log("LEDGER-CARRIED %s -> %s: the addon parked on that subdomain"
            % (dom, addon))
    return True


def handle_restore(user):
    """An account was just restored: converge it.

    Pins travel in the account package, Selector state in the homedir.
    cPanel raises the new-domain events mid-restore too, before the
    userdata holding the pins, and those leave the account to this hook
    (handle_new_domain), which takes the restoring mark away — so this is
    the one defined place where a restored account re-enters the sync.
    State-pure
    classification makes the pass safe on any restore variant: restricted
    restores drop alt-php pins (re-pinned from the restored Selector
    state), and pins for packages the destination cannot serve are held
    by the php.conf guard.

    Dispatched, never inline. cPanel holds the restore open across this
    hook and a transfer fires it once per account, so converging here
    would rebuild Apache configuration per account with the restore
    waiting behind each rebuild. The detached reconcile writes a chunk of
    accounts per cPanel call instead, and the fleet lock plus its request
    marker collapse a bulk restore's many dispatches into one walk (and
    one follow-up), instead of one pass per restored account.

    Except where the restore's start flagged a row (step_aside_for_restore):
    that account's own pass runs here, for the claims the flags are for.
    Until a pass makes them, an alt-php of the sync's back from the backup
    is not told from an admin's, and a PHP Selector change or a --disable
    made before the dispatched walk reached the account left it on the
    version the account had left, served with the server-wide extensions
    (found in review). A transfer's new accounts have no rows to flag.

    With the mirror off there is nothing to converge — the reconcile would
    refuse — so nothing is dispatched: a flagged pin of the sync's back
    from the backup is handed back, as the withdrawal does with the others,
    and every other flag goes (hand_back_restored). No pass makes the first
    claim the flags are for, and left, one would decide a claim long after
    (found in review)."""
    named = isinstance(user, str) and ACCOUNT_NAME.match(user)
    if named:
        try:
            os.unlink(restoring_path(user))
        except OSError:
            pass
        restamp_record(user)
    if load_conf()["selector_to_multiphp"] != "on":
        if named:
            hand_back_restored(user)
        log("RESTORE: %s — selector-to-multiphp is off, nothing to converge"
            % user)
        return
    if named and restored_flags(user):
        guarded_mirror(user, "account-restore")
    log("RESTORE: %s — dispatching convergence" % user)
    spawn_reconcile("account-restore")


def restored_flags(user):
    """Whether a row of the account carries a restore's flag."""
    try:
        return any(row.get("restored")
                   for row in load_record(user)["domains"].values())
    except RecordUnusable:
        return False


def hand_back_restored(user, inline=True):
    """A restore's end with the mirror off: a --disable came during it. The
    sync's own pins back from the backup are claimed (claim_restored) and
    handed back as that withdrawal would have. Found in review: the
    withdrawal skipped the account being restored, and its end dropped the
    flags, leaving the sync's pins as plain ones. inline=False (a dead
    restore's end, asked from anywhere, a pass's lock held perhaps), a pass
    holding the account, or a Selector that could not be read: by the
    withdrawal walk, detached, marked due at once (found in review: with
    the account's pass lock held the claim was made, and nothing handed it
    back). So is an inline hand-back that left a pin of the sync's standing
    (found in the final review: counted as done, nothing retried it)."""
    ours = claim_restored(user)
    if ours:
        log("RESTORE: %s — the sync's own versions back from the backup go "
            "back, as the --disable during the restore hands back: %s"
            % (user, ", ".join(ours)))
        if inline and withdraw_account(user, "account-restore") \
                and not standing_of_ours(user):
            return
    if ours is None or ours:
        mark_withdraw_pending()
        spawn_withdraw("account-restore")


def claim_restored(user):
    """The claims a restore's end makes with the mirror off: a flagged row's
    pin equal to the account's PHP Selector version is the sync's own, back
    from the backup, and is claimed (selector_claim); every other flag
    goes. Returns the domains claimed, or None where the Selector or the
    pins could not be read: then the flags of what could not be judged
    stay, and the withdrawal walk judges them again (withdraw; found in
    review: they all went, and the sync's pin stood as a plain one for
    good)."""
    try:
        rows = load_record(user)["domains"]
    except RecordUnusable:
        return []
    flagged = sorted(d for d, row in rows.items() if row.get("restored"))
    if not flagged:
        return []
    _, raw_pins = load_userdatadomains()
    current, isolated = selector_state(user)
    if current is None or raw_pins is None:
        log("RESTORE: %s — its PHP Selector versions or its pins could not "
            "be read; its restore's flags stay for the withdrawal walk" % user)
        return None
    unread = [d for d in flagged if d not in raw_pins]
    if current is OUTSIDE_CAGEFS:
        # an account the restore took out of CageFS: the Selector cannot
        # say which is the sync's own, the pin it held as the restore
        # began does (step_aside_for_restore)
        ours = [d for d in flagged if d not in unread
                and from_pkg(raw_pins[d]) is not None
                and raw_pins[d] == rows[d].get("held")]
    else:
        ours = [d for d in flagged if d not in unread
                and from_pkg(raw_pins[d]) is not None
                and raw_pins[d] == to_pkg(isolated.get(d, current))]
    now = time.strftime("%F %T")
    try:
        with updated_record(user) as rec:
            for dom in flagged:
                row = rec["domains"].get(dom)
                if row is None or dom in unread:
                    continue
                if dom in ours:
                    rec["domains"][dom] = selector_claim(
                        row, raw_pins[dom], now, arrived=raw_pins[dom])
                else:
                    row.pop("restored", None)
                    row.pop("held", None)
    except RecordUnusable:
        return []
    return None if unread else ours


def restored_accounts():
    """The accounts with a row a restore flagged (step_aside_for_restore)."""
    try:
        names = sorted(os.listdir(STATE_DIR))
    except OSError:
        return []
    accounts = []
    for name in names:
        if name.endswith(".json") and not name.startswith("_"):
            user = name[:-len(".json")]
            if restored_flags(user):
                accounts.append(user)
    return accounts


def restoring(user):
    """Whether the account is being restored (restoring_path): no pass
    touches it then (guarded_mirror, write_chunk, handle_new_domain).

    For as long as the process restoring it lives, RESTORE_TTL at most:
    found in review, a fixed day ended the hold early for a home directory
    restored over more than a day, and held a failed restore's account, or
    one whose restore hook --disable had removed, for the rest of it. A
    restore whose process is gone has ended without its post stage, and
    the mark goes with this answer. A mark that names no process, or
    cannot be read, holds for RESTORE_UNTRACKED_TTL; one dated ahead of
    that (a clock stepped back) does not hold at all, nor does one a
    deleted account of the name left (held_for_a_namesake).

    A restore over without its post stage is ended as that stage ends one
    (handle_restore), by whoever asks first: its record is restamped
    (restamp_record; found by Bugbot: only that stage did it, and a record
    the account kept kept a uid the account no longer has), its flags go
    with the mirror off (found in review: one took an admin's later alt-php
    for the sync's after a re-enable), and with it on, a pass makes the
    claims they are for."""
    path = restoring_path(user)
    try:
        age = time.time() - os.path.getmtime(path)
    except OSError:
        return False
    if abs(age) < RESTORE_TTL:
        mark = load_hold(path)
        if not held_for_a_namesake(user, mark):
            try:
                pid, started = int(mark["pid"]), str(mark["started"])
            except (ValueError, KeyError, TypeError, AttributeError):
                if abs(age) < RESTORE_UNTRACKED_TTL:
                    return True
            else:
                if process_started(pid) == started:
                    return True
    try:
        os.unlink(path)
    except OSError:
        return False  # another asker ended it
    log("RESTORE: %s — its restore ended without its post stage; passes "
        "resume" % user)
    restamp_record(user)
    if load_conf()["selector_to_multiphp"] != "on":
        hand_back_restored(user, inline=False)
    elif restored_flags(user):
        spawn_mirror(user, "account-restore")
    return False


def unset_phpversion(user, doms, aliases=None):
    """Remove the domains' phpversion key from cPanel's userdata, with
    cPanel's own module (no API removes one): the state of a domain that
    never had a version set. Returns the domains whose key went; a failure
    is logged and the key stays, which serves the same.

    An addon's userdata is its subdomain's: `aliases` is the map
    load_userdatadomains reads ({subdomain: addon}). Found in review: named
    by the addon, the removal failed for every addon. Both names of one
    file come back: found by Bugbot, keyed by the file, only the later name
    did, and an addon's row missed its `restored` flag."""
    if not doms:
        return set()
    userdata = {addon: sub for sub, addon in (aliases or {}).items()}
    files = {}
    for dom in doms:
        files.setdefault(userdata.get(dom, dom), []).append(dom)
    script = ("use Cpanel::Config::userdata::Simple; my $user = shift;"
              " for my $d (@ARGV) { eval { Cpanel::Config::userdata::Simple"
              "::set_cpanel_vhost_userdata($user, $d, { phpversion => undef });"
              " 1 } or print \"FAILED $d\\n\" }")
    res = run([CPANEL_PERL, "-e", script, user] + sorted(files))
    failed = {line.split(" ", 1)[1] for line in (res.stdout or "").splitlines()
              if line.startswith("FAILED ")}
    if res.returncode != 0:
        failed = set(files)  # what it did before it failed cannot be told
    if failed:
        log("RESTORE: %s — the version key could not be removed from %s "
            "(rc=%s): the restore keeps `inherit` there, not the backup's "
            "version" % (user, ", ".join(sorted(d for f in failed
                                                for d in files.get(f, [f]))),
                         res.returncode))
    return {dom for name, names in files.items() if name not in failed
            for dom in names}


def handle_restore_start(user, restorer=None):
    """A restore begins (PkgAcct::Restore, postExtract: phase 1 of every
    restore, before its home directory, its domains and the userdata
    holding their pins). It need not exist yet: a new account's is made
    later in the restore.

    A restore changes an account's PHP versions and its PHP Selector state
    together, so it goes as a Selector change does (release). Under the
    account's pass lock, waited for, the sync hands every pin of its own
    back (release_held), so nothing of its stands while the restore brings
    the Selector state back; then it marks the account (restoring_path,
    with `restorer`, the process restoring it), so no pass writes it until
    the restore ends and its post stage converges it (handle_restore).
    Found in review: a pass between the restore's domains and its
    userdata pinned what that phase then kept, and the pins in the backup
    were lost; and the hold alone left the sync's pins standing for what
    PHP-FPM or a parent's pin did meanwhile.

    cPanel's restore keeps every userdata key the account has. A domain
    that never had a version set has no phpversion key, and takes the
    backup's; one the sync handed back to `inherit` has the key, and would
    keep `inherit` over the backup's version. So where a domain arrived on
    `inherit`, the key goes too (unset_phpversion), as it would be without
    the sync.

    With the mirror off nothing of the sync's stands but what a hand-back
    under way or due has yet to reach, and that goes back as it will; the
    keys of earlier hand-backs go whatever the switch. The account is
    marked whatever the switch: one turned on mid-restore must not pin it
    either."""
    if not isinstance(user, str) or not ACCOUNT_NAME.match(user):
        log("RESTORE start ignored — no account name in the event: %r" % (user,))
        return
    mirroring = load_conf()["selector_to_multiphp"] == "on"
    handed, stuck = [], None
    with path_lock_wait(pass_lock_path(user), CHANGE_LOCK_WAIT) as acquired:
        try:
            if not acquired:
                stuck = "a pass held the account for %ds" % CHANGE_LOCK_WAIT
            else:
                handed, stuck = step_aside_for_restore(
                    user, RELEASING if mirroring
                    else WITHDRAWING if withdrawal_due() else None)
        finally:
            # whatever the step aside did: found in the final review, one
            # that raised let the restore go on unheld
            mark_restoring(user, restorer)
    standing = standing_of_ours(user) if stuck else []
    log("RESTORE: %s — %s; held from every pass until the restore ends"
        % (user, "pins of the sync's still stand on %s (%s): the backup's "
           "versions do not apply to them" % (", ".join(standing or ["?"]),
                                               stuck)
           if stuck else "handed back %d domain(s)" % len(handed)
           if handed else "nothing of the sync's stood"))


def step_aside_for_restore(user, mode):
    """handle_restore_start's step aside, under the account's pass lock:
    every pin of ours goes back (`mode`: RELEASING, or WITHDRAWING for a
    hand-back due; None, with the mirror off and none due, hands nothing
    back), what it can whatever a document-root group holds (release_held,
    whole=False). Then the version key goes where the sync made `inherit`
    over a domain that arrived on it: those handed back now, and those it
    handed back before (out of coverage, a --disable), which kept the key
    over the backup's version too (found in review). Returns ([the domains
    handed back now], why a pin of ours still stands, or None)."""
    aliases, raw_pins, vhosts = load_userdata_listing()
    listed = {v["vhost"] for v in vhosts or () if v.get("account") == user}
    try:
        # an addon's row a pass kept under the subdomain it was made on goes
        # to the addon first, as a release carries it: looked up under the
        # subdomain's name, it read as no pin, and its key stayed over the
        # backup's version (found by Bugbot)
        with updated_record(user) as rec:
            for old, new in carry_addon_rows(rec["domains"], listed, aliases):
                log("LEDGER-CARRIED %s -> %s: the addon parked on that "
                    "subdomain" % (old, new))
            entries = dict(rec["domains"])
    except RecordUnusable as e:
        return [], e.note()
    raw_pins = raw_pins or {}
    standing = set(standing_of_ours(user) or [])
    keyed = []
    for dom, entry in entries.items():
        pin = raw_pins.get(dom)
        row = effective_entry(entry, pin)
        if pin is None or row.get("was") not in (None, "", "inherit"):
            continue
        # a pin of ours, an earlier hand-back to `inherit`, and a native
        # account's `inherit` the pass after such a hand-back claimed (found
        # in review: its key stayed): no flag for that one, a claim keeps
        # its `was`
        if not row.get("bare", True):
            # it arrived with a key of its own set to `inherit`, which
            # cPanel's restore keeps over the backup's version: without the
            # sync it stays (found in review: it went, and the backup's
            # version landed for good)
            continue
        if (from_pkg(pin) is not None and row.get("owner") == "selector"
                and row.get("version") == pin) or (
                    pin == "inherit" and row.get("version") == "inherit"
                    and (row.get("reason") == "released"
                         or row.get("owner") == "selector")):
            keyed.append(dom)
    stuck = None
    if mode is not None:
        stuck = release_held([user], "restore", withdrawn=mode,
                             whole=False).get(user)
    _, after = load_userdatadomains()
    went = unset_phpversion(
        user, sorted(d for d in keyed if (after or {}).get(d) == "inherit"),
        aliases)
    if went:
        # A backup made where the sync ran holds its own pins as plain
        # keys, which come back to these domains now: one equal to the
        # Selector's version is the sync's pin back, and keeps what the
        # domain arrived with (selector_claim), on the first claim after
        # the restore only (plan_mirror, handle_restore). The flag keeps
        # the pin of the sync's the domain carried as the restore began
        # (`held`), which tells the sync's own where the Selector cannot,
        # for an account the restore takes out of CageFS (OUTSIDE_CAGEFS)
        try:
            with updated_record(user) as rec:
                for dom in went:
                    row = rec["domains"].get(dom, {})
                    if row.get("reason") != "released":
                        continue
                    row["restored"] = True
                    pin = raw_pins.get(dom)
                    before = effective_entry(entries.get(dom, {}), pin)
                    if from_pkg(pin) is not None \
                            and before.get("owner") == "selector" \
                            and before.get("version") == pin:
                        row["held"] = pin
        except RecordUnusable:
            pass
    return sorted(standing - set(standing_of_ours(user) or [])), stuck


def mark_restoring(user, restorer):
    """Mark the account as being restored by the process `restorer`."""
    mark = {"since": time.strftime("%F %T")}
    started = process_started(restorer) if restorer else None
    if started is not None:
        mark.update(pid=int(restorer), started=started)
    uid = account_uid(user)
    if uid is not None:
        mark["uid"] = uid  # held_for_a_namesake
    try:
        ensure_state_dir()
        with open_private(restoring_path(user), "w") as f:
            json.dump(mark, f)
    except OSError as e:
        log("STATE %s could not be written: %s" % (restoring_path(user), e))


def handle_new_domain(user, what, is_restore=False):
    """A new account, subdomain, addon or alias: mirror it now, rather
    than on its account's next pass, up to a day later. Until then
    MultiPHP Manager shows `inherit` where PHP Selector serves a version:
    served the same, but the two tools disagree.

    Dispatched, detached: cPanel holds the creating request open across
    this hook. A new account is one fleet reconcile, whose lock and request
    marker collapse a run of creations into one walk, a chunk of accounts
    per cPanel call. A new domain is one paced pass for its account once
    the account's new domains have settled (settle): a tenant
    creates them through their own API calls, and cPanel raises this hook
    before it has finished the domain.

    A restore's domains wait for its end (handle_restore). cPanel restores
    them before the userdata holding their pins, and keeps a key already
    present: a pass in between pinned an empty pin, and the pin in the
    backup was lost (found in review). Its start marks the account
    (handle_restore_start); Accounts::Create, which says it is a restore
    for a new account, marks it too, should that start have gone unseen.

    With the mirror off nothing is dispatched, marked or logged. The name
    comes from cPanel's payload; only an account that exists counts, and
    root is none (cPanel parks a domain nobody owns under it)."""
    if load_conf()["selector_to_multiphp"] != "on":
        return
    if not isinstance(user, str) or not ACCOUNT_NAME.match(user):
        log("NEW-DOMAIN ignored — no account name in the event (%s): %r"
            % (what, user))
        return
    try:
        pwd.getpwnam(user)
    except KeyError:
        log("NEW-DOMAIN ignored — no such account (%s): %s" % (what, user))
        return
    if user == "root":
        return
    if what == "account":
        if is_restore:
            forget_namesake_holds(user)
            touch_state_file(restoring_path(user))
            log("NEW-DOMAIN %s is being restored: its domains wait for the "
                "restore hook" % user)
            return
        forget_account(user)
        debounce(new_accounts_pending_path(),
                 lambda: spawn_reconcile("new-account", settle=True))
        return
    if restoring(user):
        log("NEW-DOMAIN %s (%s) left to the restore hook" % (user, what))
        return
    debounce(new_pending_path(user),
             lambda: spawn_mirror(user, "new-%s" % what, paced=True,
                                  settle=True))


def forget_account(user):
    """A new account takes nothing of a deleted one of the same name: its
    record and marks, dated before the account's creation (cPanel's
    STARTDATE), go. Found in review: fleet pruning only drops an account
    that is gone, and the new account's main domain took the old `was` for
    the pin it arrived with. What a pass wrote since stays; without a
    creation date nothing goes. A record an account renamed away from the
    name left before it could follow (renamed_to) goes on to that account
    instead, its pool copies with it, the old rows winning as in
    move_account_state: found by Bugbot, dropped while the rename's retry
    waited, the sync's pins read as an admin's from then on."""
    started = account_started(user)
    if started is None:
        return
    gone, heir = [], None
    with record_lock(user):
        # the record by its stamp too (stamped_before), under its lock: a
        # pass re-saving it meanwhile dates it after the account
        try:
            with open(record_path(user)) as f:
                record = json.load(f)
            stale = stamped_before(user, record_path(user), record, started)
        except (OSError, ValueError, AttributeError):
            stale = False
        if stale:
            heir = renamed_to(user, record)
            rows = record.get("domains")
            if heir is not None and isinstance(rows, dict) \
                    and all(isinstance(e, dict) for e in rows.values()):
                with record_lock(heir):
                    try:
                        kept = load_record(heir)
                    except RecordUnusable:
                        heir = None
                    else:
                        kept["domains"].update(rows)
                        save_record(heir, kept)
            else:
                heir = None
            with contextlib.suppress(OSError):
                os.unlink(record_path(user))
                if heir is None:
                    gone.append(os.path.basename(record_path(user)))
    if heir is not None:
        if os.path.isdir(pool_dir(user)) and not os.path.exists(pool_dir(heir)):
            with contextlib.suppress(OSError):
                os.rename(pool_dir(user), pool_dir(heir))
        log("RENAME %s -> %s: a new account took the old name before the "
            "record moved; it goes on to the renamed account" % (user, heir))
    # a modification's notes too: one the deleted account left held every
    # pass, prune and release of the new one (found by Bugbot)
    for path in (pass_request_path(user),
                 pass_stamp_path(user), change_stamp_path(user),
                 release_stamp_path(user), new_pending_path(user),
                 restoring_path(user), modify_pending_path(user),
                 modify_held_path(user)):
        try:
            if os.path.getmtime(path) < started:
                os.unlink(path)
                gone.append(os.path.basename(path))
        except OSError:
            pass
    for directory in (changes_dir(user), pool_dir(user)):
        try:
            if os.path.getmtime(directory) < started:
                shutil.rmtree(directory, ignore_errors=True)
                gone.append(os.path.basename(directory))
        except OSError:
            pass
    if gone:
        log("NEW-DOMAIN %s: dropped what a deleted account of that name "
            "left: %s" % (user, ", ".join(gone)))


def forget_namesake_holds(user):
    """forget_account for an account a restore creates. The restore brings
    STARTDATE back from the backup, so a deleted namesake's marks read as
    newer than the account (found by Bugbot: they held its restore's end).
    But no modification, PHP Selector change or new-domain wait can be the
    account's before it exists, so those go whatever their age; and so does
    a restore mark naming a process that is gone, or another uid
    (held_for_a_namesake), which only an earlier restore's can (found by
    Bugbot: re-dated, it ended this one's hold at once). The record is
    left to its stamps (left_by_a_namesake): the backup's account may be
    the one it proves."""
    gone = []
    stale = [new_pending_path(user), modify_pending_path(user),
             modify_held_path(user)]
    restorer = change_owner(restoring_path(user))
    if (restorer is not None and process_started(restorer[0]) != restorer[1]) \
            or held_for_a_namesake(user, load_hold(restoring_path(user))):
        stale.append(restoring_path(user))
    for path in stale:
        try:
            os.unlink(path)
            gone.append(os.path.basename(path))
        except OSError:
            pass
    if os.path.isdir(changes_dir(user)):
        shutil.rmtree(changes_dir(user), ignore_errors=True)
        gone.append(os.path.basename(changes_dir(user)))
    if gone:
        log("NEW-DOMAIN %s: dropped what a deleted account of that name "
            "left waiting: %s" % (user, ", ".join(gone)))


def touch_state_file(path):
    """Create or re-date one of the engine's per-account markers. A marker
    that cannot be written is logged and goes without: what it would hold
    back or wait for then happens at once."""
    try:
        ensure_state_dir()
        with open_private(path, "r+"):
            pass
        os.utime(path, None)
    except OSError as e:
        log("STATE %s could not be written: %s" % (path, e))


def new_accounts_pending_path():
    """Touched by every new account, taken by the reconcile that waits for
    them to settle (settle)."""
    return os.path.join(STATE_DIR, "_new-accounts.pending")


def debounce(path, spawn):
    """One more new domain or account for the settling pass that waits on
    `path`: mark it, and start the pass (spawn) unless one waits already.
    True when one was started.

    Under the mark's lock, which the pass takes to claim the mark (settle),
    so a mark made while the pass decides is never lost (found in review).
    The mark holds the time its pass was started: a pass that could not be
    started leaves no mark, and one dated from the future (a clock stepped
    back) or older than a pass can wait is not taken for a pass waiting."""
    try:
        ensure_state_dir()
        with path_lock(path + ".lock"):
            try:
                with open(path) as f:
                    began = float(f.read().strip())
                waiting = 0 <= time.time() - began \
                    < NEW_DOMAIN_WAIT_MAX + 2 * NEW_ACCOUNT_SETTLE
            except (OSError, ValueError):
                waiting = False
            if waiting:
                os.utime(path, None)   # it waits for this one too
                return False
            with open_private(path, "w") as f:
                f.write("%f\n" % time.time())
            try:
                spawn()
            except Exception as e:  # pylint: disable=broad-except
                log("SETTLE could not start the pass for %s: %s" % (path, e))
                os.unlink(path)
                return False
            return True
    except OSError as e:
        log("SETTLE %s could not be marked: %s" % (path, e))
        return False


def settle(path, quiet_for):
    """Wait until `path` has gone quiet_for seconds without a new mark
    (debounce), NEW_DOMAIN_WAIT_MAX at most, then take the mark: the pass
    after this reads what cPanel finished, and what comes later starts a
    pass of its own. True when cut off while a mark was still settling:
    the caller then hands on to another pass after its own (debounce), or
    that item would be read before cPanel had finished it (found in
    review). A mark dated in the future counts as just made."""
    start = time.time()
    while True:
        with path_lock(path + ".lock"):
            try:
                quiet = max(time.time() - os.path.getmtime(path), 0.0)
            except OSError:
                return False
            if quiet >= quiet_for or time.time() - start >= NEW_DOMAIN_WAIT_MAX:
                os.unlink(path)
                return quiet < quiet_for
        time.sleep(max(min(quiet_for - quiet,
                           NEW_DOMAIN_WAIT_MAX - (time.time() - start)), 0.1))


def wait_out(after):
    """Wait until the process `after` names ("<pid>:<started>",
    spawn_mirror) is gone, MODIFY_WAIT_MAX at most; a value that names none
    waits for nothing."""
    pid, _, started = (after or "").partition(":")
    if not pid.isdigit() or not started:
        return
    deadline = time.time() + MODIFY_WAIT_MAX
    while process_started(int(pid)) == started and time.time() < deadline:
        time.sleep(0.5)


def detached_env():
    """Environment for a detached pass: a whitelist, not a filtered copy.

    This process's environment is not trustworthy — a dispatch entry
    serves an in-cage caller's request, and cagefs.server scrubbing it is
    that server's contract to keep, not ours to assume (the same reasoning
    that makes run() pin SAFE_ENV for every child). `-Ibb` isolates the
    interpreter's own PYTHON* variables but not the dynamic loader's, so
    an inherited LD_PRELOAD or LD_LIBRARY_PATH would reach a root
    process.

    Starting from the whitelist also settles the routing problem it was
    written for: PROXYEXEC_UID cannot survive, and main() routes on that
    before it reads argv — a child that inherited it would be taken for
    the door, which refuses every argument, and the dispatched work would
    be dropped."""
    return dict(SAFE_ENV)


def spawn_mirror(user, reason, paced=False, settle=False, after=None):
    """Run one account's mirror pass detached.

    The per-account counterpart of spawn_reconcile, used when the
    follow-up cap is reached with a change still outstanding. One account
    is the granularity of the work, so a fleet walk would be the wrong
    tool: the marker names exactly one account.

    paced: the pass this continues was a tenant's, so the detached chain
    keeps the door's throttle — otherwise the cap would be the way around
    DOOR_PACE for exactly the change loop it exists to bound.
    settle: the pass waits for the account's new domains first
    (settle). after: (pid, process_started) of a process the pass waits
    out first, MODIFY_WAIT_MAX at most (handle_modify)."""
    subprocess.Popen(
        [sys.executable, "-Ibb", os.path.abspath(__file__),
         "--mirror", "--user", user, "--reason", reason]
        + (["--paced"] if paced else [])
        + (["--settle"] if settle else [])
        + (["--after", "%d:%s" % after] if after else []),
        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
        env=detached_env(), start_new_session=True)
    log("MIRROR dispatched user=%s (reason=%s)" % (user, reason))


def spawn_withdraw(reason):
    """Run the withdrawal walk detached (--withdraw), for the reason
    spawn_reconcile runs the fleet pass detached."""
    subprocess.Popen(
        [sys.executable, "-Ibb", os.path.abspath(__file__),
         "--withdraw", "--reason", reason],
        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
        env=detached_env(), start_new_session=True)
    log("WITHDRAW dispatched (reason=%s)" % reason)


def spawn_reconcile(reason, settle=False):
    """Run the fleet reconcile detached. Callers sit inside requests a
    person is waiting on (the WHM hook, the package install), and a walk
    over every account must not hold those open. settle: it waits for the
    new accounts to settle first (debounce)."""
    subprocess.Popen(
        [sys.executable, "-Ibb", os.path.abspath(__file__),
         "--reconcile", "--reason", reason]
        + (["--settle"] if settle else []),
        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
        env=detached_env(), start_new_session=True)
    log("RECONCILE dispatched (reason=%s)" % reason)


def spawn_report():
    """Run the daily report detached (--report): what the sync met reaches
    cl-summary's counters and Sentry (multiphp_sync_report). Nothing waits
    for it; it waits for this process to end instead (wait_out), so a crash
    this run ends with is recorded (main) before the report reads the day.
    cllib's switch for Sentry (DISABLE_SENTRY) reaches it as a fixed
    value, through the whitelisted environment."""
    me = os.getpid()
    env = detached_env()
    if os.environ.get("DISABLE_SENTRY"):
        env["DISABLE_SENTRY"] = "1"
    try:
        subprocess.Popen(
            [sys.executable, "-Ibb", os.path.abspath(__file__), "--report",
             "--after", "%d:%s" % (me, process_started(me))],
            stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL, env=env, start_new_session=True)
    except OSError as e:
        # the run it follows is not the report's to fail
        log("REPORT could not be started: %s" % e)


def run_report(test=False):
    """The daily report, here and now (multiphp_sync_report): its own
    module, so nothing else loads what it sends with. Nothing where the
    sync has no state directory. test: its events go to Sentry's `test`
    environment."""
    if not os.path.isdir(STATE_DIR):
        return
    here = os.path.dirname(os.path.realpath(__file__))
    if here not in sys.path:
        sys.path.insert(0, here)
    try:
        import multiphp_sync_report  # pylint: disable=import-outside-toplevel
    except Exception as e:  # pylint: disable=broad-except
        # a broken install: the run it follows is not the report's to fail
        # (main ends quietly on any error of its own)
        log("REPORT could not be loaded: %s" % e)
        return
    multiphp_sync_report.main(test=test)


def handle_default_change():
    """The MultiPHP system default changed: re-evaluate the suspension.

    A default that is not ea-php — an alt-php one, or one that could not
    be read at all — suspends both directions (every handler checks
    selector_suspended itself). An ea-php default reconciles, including a
    move between two ea-php defaults, which shifts the gateway value and so
    re-judges every domain that was pinned to the old one. Classification
    is state-pure, so every domain is judged exactly as at cold start and
    no memory of a pause is needed.

    Neither branch can say whether the sync WAS suspended: that would need
    the previous default, which nothing stores. So both report the state
    they found and what follows from it, rather than claiming a
    transition.

    The re-judging is the mirror's, so with it off this asks cPanel
    nothing: the reconcile would refuse."""
    if load_conf()["selector_to_multiphp"] != "on":
        log("DEFAULT-CHANGE ignored — selector-to-multiphp is off")
        return
    default_pkg = system_default()
    if selector_suspended(default_pkg):
        # not "an alt-php default": selector_suspended is also true for a
        # default that could not be read, and naming the wrong cause sends
        # the reader looking for a version change that never happened
        log("DEFAULT-CHANGE the system default is %r — the sync pauses "
            "here, and resumes under an ea-php default" % default_pkg)
        return
    log("DEFAULT-CHANGE the system default is %r; reconciling — the gateway "
        "value moved, so every domain is judged afresh" % default_pkg)
    spawn_reconcile("default-change")


def handle_handler_change():
    """A PHP version's handler changed (WHM MultiPHP Handlers, whmapi1
    php_set_handler, rebuild_phpconf): re-judge every domain.

    The handler decides how a pinned site runs, and a pin of ours stands
    only where its handler is the system default's — the one PHP Selector
    serves the site through (Coverage.handler_mismatch). A handler that
    moved can break that for pins already written, and can allow pins that
    were withheld, so the fleet pass judges them all again: it hands back
    what no longer holds and mirrors what newly does. With the mirror off
    there is nothing to write either way."""
    if load_conf()["selector_to_multiphp"] != "on":
        log("HANDLER-CHANGE ignored — selector-to-multiphp is off")
        return
    log("HANDLER-CHANGE a PHP handler changed; reconciling — every domain "
        "is judged against the new handlers")
    spawn_reconcile("handler-change")


def handle_easyapache_change():
    """An ea-* package transaction finished (the EasyApache hook, run by
    cPanel's package-manager universal hooks): re-judge every domain.

    EasyApache decides which Apache modules there are — suEXEC and suPHP,
    without which the Selector serves nothing — and its own hooks rewrite
    php.conf's handlers when a module goes. None of it raises a cPanel
    hook, so without this a pin of ours could go on deciding how its site
    runs until some unrelated trigger. Dispatched, never inline: the
    package transaction waits for this script."""
    if load_conf()["selector_to_multiphp"] != "on":
        log("EASYAPACHE-CHANGE ignored — selector-to-multiphp is off")
        return
    log("EASYAPACHE-CHANGE an EasyApache package changed; reconciling — "
        "every domain is judged against the new modules and handlers")
    spawn_reconcile("easyapache-change")


# --------------------------------------------------------------------------
# reporting
# --------------------------------------------------------------------------

def check_user_data(user, vhosts, default_pkg, raw_pins,
                    account_current, isolated, coverage, syncing=True):
    """One account's drift report as data. The table and the JSON print
    the same reading, judged by verdict_of — never assembled twice.

    The selector reading is the caller's to make and both parts are
    required: selector_state for one account, the bulk read for the walk.
    An account nothing could be read for is (None, {}) — a reading, not a
    missing argument. coverage is the box's Coverage, read once by the
    caller for the same reason, and syncing the write switch, read once
    for the same reason again.

    answered is False when nothing about the account could be judged:
    reported rather than dropped, because an account nothing can judge is
    itself a finding (absence of an answer is never an answer). unjudged
    says why — the selector did not answer, or the account's ownership
    record is unusable (RecordUnusable) — and is None otherwise."""
    data = {"user": user, "answered": account_current is not None,
            "selector_current": (None if account_current is OUTSIDE_CAGEFS
                                 else account_current),
            "domains": [], "verdicts": {}, "unjudged": None}
    if account_current is None:
        data["unjudged"] = "no selector state for %s" % user
        return data
    try:
        record = load_record(user)
    except RecordUnusable as e:
        data["answered"] = False
        data["unjudged"] = e.note()
        return data
    upstream = upstream_pins(vhosts, nosync_pins(raw_pins, record, default_pkg,
                                                 coverage.handlers))
    for v in sorted(vhosts, key=lambda x: x["vhost"]):
        r = domain_reading(v, account_current, isolated, default_pkg,
                           record, raw_pins, coverage, upstream)
        verdict, owner = verdict_of(r.entry, r.raw_pin, r.pin_read,
                                    r.target, default_pkg, r.inert,
                                    r.unroutable, syncing=syncing)
        data["domains"].append({
            "domain": r.dom, "selector_version": r.sel_cur,
            "pin": r.raw_pin, "pin_read": r.pin_read,
            "reported": r.reported, "fpm": r.fpm,
            "verdict": verdict, "ownership": owner,
            # null for a domain nothing is holding back. An admin's own
            # pin keeps its owned verdict and reports here too: their
            # domain is being served by nothing, at HTTP 200, and this is
            # the only place on the box that can say so.
            "reason": r.unroutable or r.inert,
            "deviation": deviation(r, verdict, record, raw_pins),
        })
        data["verdicts"][verdict] = data["verdicts"].get(verdict, 0) + 1
    return data


def deviation(r, verdict, record, raw_pins):
    """Why an alt-php pin of the sync's on the domain serves it otherwise
    than PHP Selector would, as the code the daily report counts it by
    (CLOS-7904), or None: out of coverage (the reason's code), a version
    the web server cannot route, or a mirror the Selector has moved past.

    Read from the pin standing, also where the reading took it for one
    nobody read (an unread parent: domain_reading). A pin the domain
    arrived with serves as it would without the sync, and is none."""
    pin = (raw_pins or {}).get(r.dom)
    row = effective_entry(record["domains"].get(r.dom, {}), pin)
    if from_pkg(pin) is None or row.get("owner") != "selector" \
            or row.get("version") != pin or row.get("was") == pin:
        return None
    if verdict == "out-of-coverage":
        return getattr(r.inert, "code", "other")
    return {"unroutable": "unroutable",
            "stale-mirror": "stale"}.get(verdict)


def check_envelope(default_pkg, users, coverage):
    """The report envelope both --json forms print and the daily snapshot
    stores. schema is versioned for its consumers (the validation-evidence
    collection; later the telemetry increment): additions are compatible,
    anything else bumps it."""
    totals = {}
    for data in users:
        for verdict, count in data["verdicts"].items():
            totals[verdict] = totals.get(verdict, 0) + count
    return {"schema": 1, "generated": time.strftime("%F %T"),
            "default_php": default_pkg,
            "suspended": selector_suspended(default_pkg),
            # why nothing is written on a box the Selector cannot serve
            # (every row then reads out-of-coverage), or null
            "selector_inert": coverage.inert,
            # what was true at walk time: downstream, a disabled box's
            # standing divergence must stay tellable from a broken sync's
            "conf": load_conf(),
            "users": users, "verdicts": totals}


SUSPENDED_BANNER = ("sync suspended: the selector is disabled by the system "
                    "default (%s)")
INERT_BANNER = ("sync suspended: PHP Selector serves nothing on this server "
                "(%s)")
WITHDRAW_BANNER = ("handing back every PHP version this server set in "
                   "MultiPHP Manager, to the version each domain had before")
WITHDRAW_WHILE_ON = ("selector-to-multiphp syncing is on — the versions "
                     "would be written again on the next pass; use "
                     "--disable to stop syncing and hand them back")
OFF_BANNER = "selector-to-multiphp syncing is off"
NO_WEB_SERVER = "no Apache module list (httpd -M unavailable)"


def off_banner():
    """What an admin who ran --disable looks at later: the switch, and
    whether any pin of ours still stands behind it — with the remedy,
    since --reconcile refuses while off.

    The fleet report's line only (check_all): it opens every account's
    ledger, which one account's interactive report has no business
    doing."""
    standing = standing_pins()
    if not standing:
        return OFF_BANNER
    pins, unusable = split_unusable(standing)
    banner = OFF_BANNER
    if pins:
        banner += ("; %d PHP version(s) this server set still stand — run "
                   "--withdraw to hand them back"
                   % sum(len(doms) for doms in pins.values()))
    if unusable:
        banner += ("; %d account(s) have an unusable ownership record — "
                   "repair or remove it" % len(unusable))
    return banner


def name_some(standing, limit=10):
    """`user: domain` for the first `limit` standing pins, and how many
    more — the residue goes to a terminal and to ONE log line, so a
    fleet-wide failure must not put thousands of domains in either."""
    names = ["%s: %s" % (user, dom)
             for user, doms in sorted(standing.items()) for dom in doms]
    shown = "; ".join(names[:limit])
    if len(names) > limit:
        shown += "; and %d more" % (len(names) - limit)
    return len(names), shown


def print_check_table(data):
    if not data["answered"]:
        # a snapshot written before `unjudged` existed says nothing of why
        print("%s — nothing can be judged"
              % (data.get("unjudged") or "no selector state for %s" % data["user"]))
        return
    print("%-24s %-16s %-16s %-4s %-34s %s" % (
        "DOMAIN", "SELECTOR-TARGET", "CPANEL-RECORD", "FPM", "OWNERSHIP",
        "VERDICT"))
    for d in data["domains"]:
        # judged by the raw pin actually read (whmapi resolves inherit
        # away); a pin nobody read is shown as the hole it is, next to the
        # resolved view, never guessed at
        shown_pin = d["pin"] if d["pin_read"] else "?"
        shown = (shown_pin if shown_pin == d["reported"]
                 else "%s(->%s)" % (shown_pin, d["reported"]))
        print("%-24s %-16s %-16s %-4s %-34s %s"
              % (d["domain"], d["selector_version"], shown,
                 str(d["fpm"]), d["ownership"], d["verdict"]))


def check(user, as_json=False):
    vhosts = vhosts_of(user)
    if vhosts is None:
        # said in both modes: a JSON caller gets a loud parse failure
        # rather than a plausible empty report
        print("no vhost list from cPanel — nothing can be judged")
        return
    default_pkg = system_default()
    if not default_pkg:
        # the same refusal fleet_walk makes: is_gateway compares pins
        # against the system default, so without it every default-pinned
        # domain reads owned-unrecorded instead of selector (unmirrored).
        # Said in both modes — a JSON caller must not parse a schema-valid
        # report whose verdicts are wrong.
        print("no system default from cPanel — nothing can be judged")
        return
    _, raw_pins = load_userdatadomains()
    # one account: the per-account query is the cheaper read here, and the
    # answer means the same thing either way. It already carries the
    # isolated websites, so passing them on saves reading each one twice.
    account_current, isolated = selector_state(user)
    coverage = read_coverage()
    if coverage is None:
        # said in both modes, as the refusals above are: a report that
        # cannot tell a covered domain from an uncovered one is not one
        print("%s — nothing can be judged" % NO_WEB_SERVER)
        return
    syncing = load_conf()["selector_to_multiphp"] == "on"
    data = check_user_data(user, vhosts, default_pkg, raw_pins,
                           account_current, isolated, coverage,
                           syncing=syncing)
    if as_json:
        print(json.dumps(check_envelope(default_pkg, [data], coverage),
                         indent=2, sort_keys=True))
        return
    # deliberately NOT gated by the suspension: drift on a suspended box is
    # still drift, and a sleeping sync should be visible rather than silent
    if selector_suspended(default_pkg):
        print(SUSPENDED_BANNER % default_pkg)
    if coverage.inert:
        print(INERT_BANNER % coverage.inert)
    if not syncing:
        # the plain banner: counting what stands fleet-wide opens every
        # account's ledger, and this is one account's interactive report.
        # The fleet run (check_all) is where that count belongs.
        print(OFF_BANNER)
    print_check_table(data)


def write_last_check(report):
    """Where the fleet report lands for collection (root-only, atomic):
    what the box looked like at the last answered run, without re-walking
    every account.

    Locked because the cron's flock does not cover a manual
    `--check --all-users` overlapping it, and save_json's shared tmp path
    is only safe under a lock — an unserialized pair can install a torn
    snapshot and crash the loser on the vanished tmp."""
    with path_lock(LAST_CHECK_PATH + ".lock"):
        save_json(LAST_CHECK_PATH, report)


def fleet_walk():
    """Read the whole box once: (envelope, None) over every account that
    has a vhost, or (None, why) naming the reading that went unanswered.

    Consumers persist nothing when why is set — a report built on a
    non-answer would replace real evidence with none:
      - a failed vhost query is indistinguishable from an empty box;
      - without the system default, gateway classification is skewed and
        every default-pinned domain would read owned-unrecorded;
      - without the pin map, every verdict would be not-in-userdata;
      - without the web server's modules, a domain PHP Selector serves is
        indistinguishable from one it does not."""
    vhosts = all_vhosts()
    if vhosts is None:
        return None, "no vhost list from cPanel"
    default_pkg = system_default()
    if not default_pkg:
        return None, "no system default from cPanel"
    _, raw_pins = load_userdatadomains()
    if raw_pins is None:
        if vhosts:
            return None, "no pin map (/etc/userdatadomains unreadable or empty)"
        # a box with no domains has an empty /etc/userdatadomains, which
        # reads as no map; cPanel has said there are no vhosts, so no
        # verdict needs a pin, and the empty report is the real answer
        raw_pins = {}
    by_user = {}
    for v in vhosts:
        if v.get("account"):
            by_user.setdefault(v["account"], []).append(v)
    versions = all_selector_versions(with_websites=True)
    if versions is None:
        return None, "no selector state for the box (selector unavailable)"
    coverage = read_coverage()
    if coverage is None:
        return None, NO_WEB_SERVER
    syncing = load_conf()["selector_to_multiphp"] == "on"
    users = [check_user_data(user, by_user[user], default_pkg, raw_pins,
                             *fleet_reading_of(user, by_user[user], raw_pins,
                                               versions.get(user, (None, {}))),
                             coverage=coverage, syncing=syncing)
             for user in sorted(by_user)]
    return check_envelope(default_pkg, users, coverage), None


def ledger_is_empty():
    """True while no pass has recorded anything for any account.

    The ownership records are the proof that the sync has acted: a pass
    writes an entry for every pin it wrote, every agreement it claimed and
    every foreign pin it found. An empty ledger therefore means the store
    still holds the pre-sync picture.
    """
    try:
        names = sorted(os.listdir(STATE_DIR))
    except OSError:
        return True  # no state directory at all: nothing has run
    for name in names:
        if not name.endswith(".json") or name.startswith("_"):
            continue  # "_" prefix: an engine file, never a record
        try:
            with open(os.path.join(STATE_DIR, name)) as f:
                if json.load(f).get("domains"):
                    return False
        except (OSError, ValueError, AttributeError):
            # AttributeError: valid JSON that is not an object (null, a
            # list, a string) has no .get — a shape load_record refuses
            # as unusable. None of these prove a pass has run, and none
            # may take `--enable` down with them.
            continue
    return True


def standing_pins(raw_pins=None):
    """{account: [domain, ...]} for every pin the ledger says is ours that
    the store does not contradict — what a withdrawal has left to do.

    A `selector` row whose pin has moved is an admin's now (the planner
    files it as takeover-as-found on the next covered pass; --check calls
    it UNEXPLAINED until then) and is not counted. A pin the map does not
    hold is unknown, not gone, so it is. With no map at all every row
    counts: nothing read, nothing proven gone. An account whose record is
    unusable counts too, as UNUSABLE_RECORD: what of ours stands there
    cannot be told, so nothing may say it has all been handed back."""
    if raw_pins is None:
        _, raw_pins = load_userdatadomains()
    standing = {}
    try:
        names = sorted(os.listdir(STATE_DIR))
    except OSError:
        return standing
    for name in names:
        if not name.endswith(".json") or name.startswith("_"):
            continue  # "_" prefix: an engine file, never a record
        user = name[:-len(".json")]
        try:
            entries = load_record(user)["domains"]
        except RecordUnusable:
            standing[user] = [UNUSABLE_RECORD]
            continue
        doms = sorted(dom for dom, entry in entries.items()
                      if _stands(dom, entry, raw_pins))
        if doms:
            standing[user] = doms
    return standing


# standing_pins' entry for an account whose record cannot be read
UNUSABLE_RECORD = "(its ownership record is unusable)"


def _stands(dom, entry, raw_pins):
    """Whether a pin of ours may stand on the domain: its row — read as
    effective_entry reads a write whose claim was lost — is ours, and the
    store does not contradict it. Unknown is not gone: with no pin read, a
    write still marked pending may have landed too."""
    if raw_pins is None or dom not in raw_pins:
        return (entry.get("owner") == "selector"
                or isinstance(entry.get("pending"), dict)
                or bool(entry.get("restored")))
    if entry.get("restored") and from_pkg(raw_pins[dom]) is not None:
        # a restore's flag nobody has judged (claim_restored): the pin may be
        # the sync's own, back from the backup
        return True
    row = effective_entry(entry, raw_pins[dom])
    return row.get("owner") == "selector" and row.get("version") == raw_pins[dom]


def write_baseline():
    """Record the fleet report once, before the sync's first write.

    Convergence destroys the pre-existing divergence picture, so enabling
    the write direction records it first. Kept forever, never overwritten.
    A walk that cannot be fully answered is skipped rather than blocking
    the enable; while the file is absent, the next enable retries."""
    if os.path.exists(BASELINE_PATH):
        return
    # The retry is for a first walk that could not be answered — but that
    # first enable still turned the write direction on, so by the time a
    # later enable retries, the fleet may already have converged. Freezing
    # that picture would be worse than having no baseline at all: it would
    # read as evidence of a pre-sync world that never looked like this.
    if not ledger_is_empty():
        log("BASELINE-ABORT the sync has already recorded ownership — the "
            "pre-sync picture no longer exists")
        print("the sync has already run — baseline not recorded")
        return
    report, why = fleet_walk()
    if report is None:
        log("BASELINE-ABORT %s — not recorded" % why)
        remember("pass-aborted", "baseline", why=why)
        print("%s — baseline not recorded" % why)
        return
    # A walk can answer for the box and still answer for no ACCOUNT —
    # selectorctl down at the first enable leaves every user unanswered.
    # This file is written once, so freezing that empty picture would
    # destroy the pre-sync evidence for good. An empty box is a real
    # answer, though: refuse only when accounts exist and none answered.
    if report["users"] and not any(u["answered"] for u in report["users"]):
        log("BASELINE-ABORT no account answered (%d walked) — not recorded"
            % len(report["users"]))
        remember("pass-aborted", "baseline", why="no account answered")
        print("no selector answers — baseline not recorded")
        return
    # A box PHP Selector serves nothing on is recorded like any other: the
    # pins and selector versions ARE the divergence picture, and they are
    # exactly as true there. Its verdicts all read out-of-coverage, which
    # the envelope's selector_inert explains — and refusing instead would
    # leave a box that later gains suEXEC with no baseline at all, since
    # the first event to record ownership closes the door above.
    with path_lock(BASELINE_PATH + ".lock"):
        if os.path.exists(BASELINE_PATH):
            return
        # Re-checked here, not just before the walk: the walk takes time,
        # and on a retry the write direction is already on — a mirror pass
        # or a hook can have recorded ownership since. The check is a
        # directory scan, so paying it twice costs nothing.
        if not ledger_is_empty():
            log("BASELINE-ABORT the sync recorded ownership during the "
                "walk — the picture is no longer the pre-sync one")
            print("the sync ran during the walk — baseline not recorded")
            return
        save_json(BASELINE_PATH, report)
    log("BASELINE recorded users=%d domains=%d verdicts=%s"
        % (len(report["users"]),
           sum(len(u["domains"]) for u in report["users"]),
           json.dumps(report["verdicts"], sort_keys=True)))
    print("baseline recorded: %s" % BASELINE_PATH)


def check_all(as_json=False):
    """The fleet report: every account that has a vhost, one envelope.

    Also the daily cron's entry point while a direction is on — the
    last-check snapshot and the CHECK-SUMMARY log line are the
    drift-evidence trail. The checker itself is deliberately not gated by
    the kill switches or the suspension, so an admin can run it on a box
    with the sync off: measuring divergence is the point, acting on it is
    not this code's job.

    The snapshot only ever holds a fully answered walk: a run whose vhost
    list, system default or pin map goes unanswered aborts and leaves the
    previous snapshot standing, because a report built on a non-answer
    replaces real evidence with none."""
    report, why = fleet_walk()
    if report is None:
        log("CHECK-ABORT %s — report not written" % why)
        remember("pass-aborted", "check", why=why)
        print("%s — report not written; the previous snapshot stands" % why)
        return
    users = report["users"]
    write_last_check(report)
    log("CHECK-SUMMARY users=%d unanswered=%d domains=%d verdicts=%s"
        % (len(users), sum(1 for u in users if not u["answered"]),
           sum(len(u["domains"]) for u in users),
           json.dumps(report["verdicts"], sort_keys=True)))
    if as_json:
        print(json.dumps(report, indent=2, sort_keys=True))
        return
    if report["suspended"]:
        print(SUSPENDED_BANNER % report["default_php"])
    if report["selector_inert"]:
        print(INERT_BANNER % report["selector_inert"])
    if report["conf"].get("selector_to_multiphp") != "on":
        print(off_banner())
    for data in users:
        print("== %s ==" % data["user"])
        print_check_table(data)
        print()


# --------------------------------------------------------------------------
# CLI
# --------------------------------------------------------------------------

def resolve_user(args):
    """The account a root CLI call names. Only root reaches main(), so the
    name is an operator's, but it still becomes a path under STATE_DIR."""
    if "--user" in args:
        i = args.index("--user") + 1
        if i >= len(args) or not ACCOUNT_NAME.match(args[i]):
            sys.exit("--user requires an account name")
        return args[i]
    sys.exit("--user required")


def resolve_users(args):
    """The accounts a root bulk call names: --users a,b,c."""
    i = args.index("--users") + 1
    users = args[i].split(",") if i < len(args) else []
    if not users or not all(ACCOUNT_NAME.match(u) for u in users):
        sys.exit("--users requires a comma-separated list of account names")
    return users


def resolve_token(args, name="--token"):
    """The change a call names (begin_change); never a path."""
    i = args.index(name) + 1 if name in args else len(args)
    if i >= len(args) or not CHANGE_TOKEN.match(args[i]):
        sys.exit("%s requires a change token" % name)
    return args[i]


# What the door takes besides no argument at all (a paced mirror pass):
# one of these and the token of the caller's own change, nothing else; or
# a read alone (READ_VERBS).
DOOR_VERBS = ("--release", "--after-change", "--end-change")
READ_VERBS = ("--owned-pins",)


def door_args(args):
    """The door's argv, checked: (), (verb, token) or (read verb,).
    Anything else is refused with no work done, since every word of it is
    the tenant's."""
    if not args:
        return ()
    if len(args) == 2 and args[0] in DOOR_VERBS and CHANGE_TOKEN.match(args[1]):
        return tuple(args)
    if len(args) == 1 and args[0] in READ_VERBS:
        return tuple(args)
    sys.exit("proxyexec entry takes no arguments but %s with a change token, "
             "or %s alone" % ("/".join(DOOR_VERBS), "/".join(READ_VERBS)))


def owned_pins(users):
    """{account: {domain: [pins]}} for the pins the ledger records as the
    sync's own, or None for an account whose record is unusable: what
    "Handled by" and selectorCompatible go by (clselectdomains). A version
    set in MultiPHP Manager stays MultiPHP's even where it equals the
    Selector's (decided 2026-10-12), and only the ledger tells it from a pin
    the sync wrote; the caller compares each domain's pin standing with it.
    A domain's pins are its claim (owner selector), and the version of a
    write of ours marked pending, which is the claim once it landed
    (effective_entry; found by Bugbot: a pass that died between its write
    and its claim left the mark, and the pin read as MultiPHP's). A
    takeover's stale mark is not. Read only, quiet and lock-free (the
    record is replaced atomically): a tenant can loop the door."""
    result = {}
    for user in users:
        try:
            rows = load_record(user, quiet=True)["domains"]
        except RecordUnusable:
            result[user] = None
            continue
        ours = {}
        for dom, row in rows.items():
            pins = set()
            if row.get("owner") == "selector" \
                    and isinstance(row.get("version"), str):
                pins.add(row["version"])
            pending = row.get("pending")
            if isinstance(pending, dict) \
                    and isinstance(pending.get("version"), str) \
                    and row.get("reason") not in ("takeover",
                                                  "takeover-as-found"):
                pins.add(pending["version"])
            if pins:
                ours[dom] = sorted(pins)
        result[user] = ours
    return result


def recorded_accounts():
    """The accounts with a record, none where the sync never ran: listing
    makes no state directory."""
    try:
        names = os.listdir(STATE_DIR)
    except OSError:
        return []
    return sorted(name[:-len(".json")] for name in names
                  if name.endswith(".json") and not name.startswith("_")
                  and name != os.path.basename(CONF_PATH))


def proxyexec_mirror(args=()):
    """Entry for the CageFS proxyexec alias MULTIPHP_SYNC: proxyexec takes
    the caller's uid from the socket's peer credentials (SO_PEERCRED —
    unforgeable) and passes it as PROXYEXEC_UID, cagefs.server checks the
    caller's cagefs token and executes this script as root. The
    environment is proxyexec's whitelist, not a scrub (see run()). The
    account is derived from that uid alone —
    never from argv, which cagefs.server forwards from the caller — so all
    an in-cage caller can request is for their own account: a mirror pass,
    or one step of their own PHP Selector change (door_args), each paced
    like the pass: a release waits out DOOR_PACE before it writes, the pass
    ending a change paces as any door pass does, and ending a change
    without a pass writes nothing."""
    raw = os.environ.get("PROXYEXEC_UID", "")
    if not raw.isdigit():
        sys.exit("PROXYEXEC_UID missing or malformed")
    uid = int(raw)
    if uid == 0:
        sys.exit("refusing uid 0: no selector account for root")
    try:
        user = pwd.getpwuid(uid).pw_name
    except KeyError:
        sys.exit("PROXYEXEC_UID %d: no such user" % uid)
    if not ACCOUNT_NAME.match(user):
        # passwd is root's, but the name becomes a path under STATE_DIR and
        # the argv of a detached pass: the rule an operator's --user meets
        sys.exit("PROXYEXEC_UID %d: %r is not an account name" % (uid, user))
    if args and args[0] in READ_VERBS:
        # the caller's own account alone, before the switches are read: a
        # read writes nothing, with the mirror on or off
        print(json.dumps({"ours": owned_pins([user])}, sort_keys=True))
        return
    verb, token = args if args else (None, None)
    if load_conf()["selector_to_multiphp"] != "on" and not (
            verb == "--release" and withdrawal_due()):
        # With the mirror off the pass would only refuse — except a release
        # while a hand-back is under way or due, which hands the account
        # back first (release). A change begun before, while the mirror ran
        # or by that release, ends all the same, with no pass: ending it
        # writes nothing (found by Bugbot: left in flight, it held the
        # account's passes, and the door's cap counted it, until it
        # expired). Said nowhere, not even in the log: a caged tenant can
        # loop this door, and a line per call would push the real audit
        # lines out of the rotation.
        if verb in ("--end-change", "--after-change"):
            end_change(user, token)
        return
    # cagefs.server leaves HOME pointing into the caller's home; children
    # (whmapi1, selectorctl) must never drop root-owned files there
    os.environ["HOME"] = "/root"
    if verb == "--end-change":
        end_change(user, token)
        return
    if verb is None:
        # Paced: this entry is tenant-triggered and a pass reads box-wide
        # cPanel state as root, so a change loop must not drive one pass —
        # and one Apache rebuild — straight after another.
        guarded_mirror(user, "user-selector-change", pace=True)
        return
    if tenant_step(user, verb, token):
        sys.exit(1)


def tenant_step(user, verb, token, reason="user-selector-change",
                owner=None):
    """One step of a tenant's PHP Selector change (`verb`: --release, or
    --after-change, the pass ending it), under the door's rules: through
    the door itself, and through the root CLI acting for a tenant
    (--paced: cagefsctl-user, lvemanager's own tenant toggle; found in
    review, those waited on the account's lock with no cap and logged every
    refusal, so a tenant could keep root processes waiting without bound).
    Returns 1 for a refused release, 0 otherwise.

    One of the tenant's steps at a time: a release, and the pass ending a
    change, may wait for the account's pass lock, and the door's waiting
    processes were bounded only by the tenant's LVE (found in review).
    While one runs, a release is refused at once, and a pass ending a
    change ends it and leaves its request for the step running, or the
    next pass. A release is capped (MAX_CHANGES) and quiet."""
    with path_lock_nb(door_lock_path(user)) as alone:
        if not alone:
            if verb == "--release":
                _refused(user, Why("another PHP version change of this "
                                   "account is in progress",
                                   "change-in-flight"), quiet=True)
                return 1
            end_change(user, token)
            leave_request(user, reason)
            return 0
        if verb == "--release":
            if not release(user, token, reason, pace=True, door=True,
                           owner=owner):
                return 1
        else:
            guarded_mirror(user, reason, pace=True, after_change=token)
    # The pass above may have deferred to another change that a step of
    # the tenant's then ended while this one held the door: that step left
    # its request for this one, which had already deferred (found in
    # review). With the door free, a request no change is left to serve
    # gets its pass — unless a pass holds the account, which serves it on
    # its way out: found in review, a tenant looping the door while a pass
    # of its own held the lock started a root pass, and logged, per call.
    if os.path.exists(pass_request_path(user)) and not pending_changes(user) \
            and not pass_running(user) and not restoring(user) \
            and not modifying(user):
        spawn_mirror(user, reason, paced=True)
    return 0


def first_run(reason="first-run", by="admin"):
    """Turn the sync on and converge — the enable verb, and the one that
    re-enables after --disable.

    The baseline first: convergence cannot recreate the picture it
    replaces, and write_baseline is write-once on its own, so re-running
    this is idempotent. Then both switches on — which clears `disabled_by`
    and records `by` as `enabled_by` — and what runs the sync by itself
    (refresh_triggers: the cPanel hooks, the boot catch-up, the daily
    check), then a fleet pass.

    Run by an administrator's --first-run and by apply_flag (by="remote").
    The boot catch-up only converges (--reconcile), which refuses while a
    switch is off; that is what lets this verb re-enable a box an operator
    disabled.

    The flag's own run is owed from before its switch change until its pass
    ends (FLAG_FIRST_RUN_PENDING): cut short in between, the sync reads on
    with its triggers part-made, and the flag asks nothing more of a server
    it turned on, so finish_first_run() completes it (found in review). An
    administrator's run cut short fails in front of them.
    """
    write_baseline()
    if by == "remote":
        open(FLAG_FIRST_RUN_PENDING, "w").close()
    set_conf("all", "on", by=by)
    refresh_triggers()
    reconcile(reason=reason)
    with contextlib.suppress(FileNotFoundError):
        os.unlink(FLAG_FIRST_RUN_PENDING)


def finish_first_run(reason):
    """Finish the flag's first run where one was cut short after its switch
    change: the triggers again, then the fleet pass. Whether it ran."""
    if not os.path.exists(FLAG_FIRST_RUN_PENDING):
        return False
    log("FLAG %s: finishing a first run cut short (reason=%s)"
        % (FLAG_NAME, reason))
    refresh_triggers()
    reconcile(reason=reason)
    with contextlib.suppress(FileNotFoundError):
        os.unlink(FLAG_FIRST_RUN_PENDING)
    return True


def flag_on():
    """The remote flag for this server, with the default the package ships:
    off."""
    from clflags import is_enabled
    return is_enabled(FLAG_NAME, default=False)


def php_selector_supported():
    """As the installer decides it: only a confident "not supported" counts,
    since the helper also answers False when the edition cannot be read."""
    from clcommon.const import Feature
    from clcommon.cpapi import (
        CLEditionDetectionError,
        get_supported_cl_features,
        is_panel_feature_supported,
    )
    try:
        get_supported_cl_features()
    except CLEditionDetectionError:
        return True
    return bool(is_panel_feature_supported(Feature.PHP_SELECTOR))


def flag_action(conf, conf_exists, wanted, opted_out):
    """"enable", "disable" or None: the remote flag's whole policy.

    `conf` is read_conf(); `wanted` is flag_on(); `opted_out`, the clflags
    opt-out marker. The flag turns off only a sync it turned on itself
    (`enabled_by` remote): an administrator's survives a partial rollout and
    a kill alike. It turns on only a server nobody ever turned the sync on
    or off for (no switches file), or one it turned off itself — never one
    an administrator turned off, and never past their opt-out.
    """
    on = "on" in (conf["selector_to_multiphp"], conf["multiphp_to_selector"])
    if on:
        if conf.get("enabled_by") == "remote" and not wanted:
            return "disable"
        return None
    if wanted and not opted_out and (
            not conf_exists or conf.get("disabled_by") == "remote"):
        return "enable"
    return None


def apply_flag(reason="remote-flag"):
    """Bring the sync in line with the remote flag, as flag_action() says.
    Run by cl-multiphp-sync-flag.service, which its .path unit starts when a
    flag file changes and its .timer after boot and every few minutes.

    The first run and the disable run inline: the service is already in the
    background, and one run at a time keeps two first runs from racing. A
    flag that changes meanwhile is obeyed at once by the write paths
    (effective_conf), a first run under way stops at its next chunk
    (fleet_write), and this run then applies it: the .path unit cannot
    start the service again while it runs. The switches change only if the
    flag still asks for it then (set_conf), so an admin's command meanwhile
    stands. Elsewhere than cPanel with PHP Selector it does nothing, and a
    box the flag leaves alone gets no state directory."""
    if not (os.path.isdir(CPANEL_DIR) and php_selector_supported()):
        return
    with flag_lock():
        for _ in range(FLAG_ACTIONS):
            acted_on = flag_step(reason)
            if acted_on is None or flag_on() == acted_on:
                return


def flag_step(reason):
    """One action of apply_flag's. Returns the flag it acted on, or None
    when it had nothing to do."""
    conf = read_conf()
    wanted = flag_on()
    action = flag_action(conf, os.path.exists(CONF_PATH), wanted,
                         os.path.exists(FLAG_OPT_OUT))
    try:
        if action == "enable":
            ensure_state_dir()  # the baseline takes its lock there first
            log("FLAG %s on: turning the sync on (reason=%s)"
                % (FLAG_NAME, reason))
            first_run(reason=reason, by="remote")
            # the sync is on again, so a hand-back left unfinished has
            # nothing more to do; not before, since a first run superseded
            # before its switch change leaves the switches off and that
            # hand-back still owed (found in review)
            with contextlib.suppress(FileNotFoundError):
                os.unlink(FLAG_WITHDRAW_PENDING)
        elif action == "disable":
            log("FLAG %s off: turning off the sync it turned on, and "
                "handing back (reason=%s)" % (FLAG_NAME, reason))
            # pending first: a hand-back cut short is retried too. With
            # when it began, which the retries' clock (the mtime) does
            # not keep (flag_withdraw_began)
            with open(FLAG_WITHDRAW_PENDING, "w") as mark:
                mark.write("%d\n" % time.time())
            try:
                if disable("all", reason=reason, by="remote"):
                    # an administrator's on during the walk has removed it
                    # already (found in review: the run then crashed)
                    with contextlib.suppress(FileNotFoundError):
                        os.unlink(FLAG_WITHDRAW_PENDING)
                else:
                    log("FLAG hand-back incomplete: retried while the flag "
                        "stays off")
            finally:
                # as after --disable, the daily cron goes with the switches.
                # Run here, not detached: the kill's run ends once its
                # report is sent, and the unit has no start timeout
                run_report()
        else:
            acted = False
            if not wanted and conf.get("disabled_by") == "remote":
                acted = retry_withdraw(reason)
            elif wanted and conf.get("enabled_by") == "remote":
                acted = finish_first_run(reason)
            # a retry or a finish runs for minutes: a flag that changes
            # meanwhile is applied by this run, as after a first run or a
            # disable (found by Bugbot: the run ended, and it waited for
            # the timer)
            return wanted if acted else None
    except FlagSuperseded:
        # raised before the switches change, so only the action's own mark
        # goes: a disable's switches are still on, an enable's still off
        pending = {"disable": FLAG_WITHDRAW_PENDING,
                   "enable": FLAG_FIRST_RUN_PENDING}.get(action)
        if pending:
            with contextlib.suppress(FileNotFoundError):
                os.unlink(pending)
        log("FLAG %s: the switches or the flag changed meanwhile; the "
            "next run decides again" % FLAG_NAME)
        return None
    return wanted


@contextmanager
def flag_lock():
    """The units run one apply_flag at a time; this covers one started by
    hand meanwhile."""
    fd = os.open(FLAG_LOCK, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
    with os.fdopen(fd, "r+") as lock_file:
        fcntl.flock(lock_file, fcntl.LOCK_EX)
        try:
            yield
        finally:
            fcntl.flock(lock_file, fcntl.LOCK_UN)


def flag_withdraw_began():
    """When the hand-back the flag's kill left unfinished began: the time
    the kill wrote into its mark, which retry_withdraw's clock (the
    mark's mtime, moved at every try) does not keep; the mtime for a
    mark without it. Found in the final review: judged by the mtime, the
    daily report could never call it stuck. Raises OSError without one."""
    try:
        with open(FLAG_WITHDRAW_PENDING) as f:
            return float(f.read().strip())
    except ValueError:
        return os.path.getmtime(FLAG_WITHDRAW_PENDING)


def retry_withdraw(reason):
    """Retry a hand-back the flag's disable left unfinished, at most every
    FLAG_WITHDRAW_RETRY seconds; the pending file's age is the clock, reset
    before the attempt so one that dies part-way still waits its turn.
    Whether it tried."""
    try:
        age = time.time() - os.stat(FLAG_WITHDRAW_PENDING).st_mtime
    except FileNotFoundError:
        return False
    if age < FLAG_WITHDRAW_RETRY:
        return False
    os.utime(FLAG_WITHDRAW_PENDING, None)
    try:
        if withdraw(reason=reason):
            # gone already when an administrator turned the mirror on
            # meanwhile
            with contextlib.suppress(FileNotFoundError):
                os.unlink(FLAG_WITHDRAW_PENDING)
    finally:
        # the daily cron went with the switches, so each try reports in its
        # place, as the kill did: a hand-back still owed is counted, called
        # stuck once a day past, and its failures sent (found in review)
        run_report()
    return True


def admin_flag_on(note=True):
    """Turned on by hand: the flag's switch file says so, and the opt-out
    goes. What keeps the rollout away is `enabled_by` admin; the switch is
    for `cloudlinux-server-flags list` and telemetry, and while a cl-settings
    entry names the flag the bridge rewrites it to the entry's answer."""
    remove_flag_marker(FLAG_OPT_OUT)
    write_flag_marker(FLAG_SWITCH)
    if note and os.path.exists(FLAG_REMOTE_OFF):
        print("note: CloudLinux has switched the %s flag off for this "
              "server. Turned on by hand, the sync stays on until you turn "
              "it off with --disable." % FLAG_NAME)


def admin_flag_off():
    """Turned off by hand: the clflags opt-out, which no cl-settings entry
    overrides, and the switch file goes."""
    write_flag_marker(FLAG_OPT_OUT)
    remove_flag_marker(FLAG_SWITCH)


def write_flag_marker(path):
    """Only inside a directory cllib made: without it there is no flag."""
    if not os.path.isdir(os.path.dirname(path)) or os.path.isfile(path):
        return
    try:
        fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o644)
        os.close(fd)
    except OSError as e:
        print("could not write %s: %s" % (path, e))
        log("FLAG could not write %s: %s" % (path, e))


def remove_flag_marker(path):
    try:
        os.unlink(path)
    except FileNotFoundError:
        pass
    except OSError as e:
        print("could not remove %s: %s" % (path, e))
        log("FLAG could not remove %s: %s" % (path, e))


def migrate_to_flag():
    """Record a pre-flag box's switches in the flag's terms; the package
    runs it once, before it first starts the flag's units. No released
    package ever turned the sync on by itself, so a direction on is an
    administrator's (`enabled_by` admin, and the switch file), and both off
    by an administrator is their opt-out. A box with no switches file gets
    nothing."""
    if not os.path.exists(CONF_PATH):
        return
    with path_lock(conf_lock_path()):
        conf = read_conf()
        on = "on" in (conf["selector_to_multiphp"],
                      conf["multiphp_to_selector"])
        if on and "enabled_by" not in conf:
            conf["enabled_by"] = "admin"
            write_conf(conf)
    if on:
        if conf.get("enabled_by") == "admin":
            admin_flag_on(note=False)
    elif conf.get("disabled_by", "admin") == "admin":
        admin_flag_off()


def withdraw(dry_run=False, reason="withdraw"):
    """Hand every pin of ours back, and say whether it all landed.

    The pass is reconcile's, with the coverage withdrawn. What is left
    afterwards is the ledger's `selector` rows the store still confirms —
    a document-root group blocked by an unread pin, a write cPanel
    refused. They are the designed retry proof (record_released drops a
    row only once its write lands), so this is re-runnable until clean,
    and it works with the sync off, which is the only time it runs at
    all. Returns True when nothing of ours stands.

    The switch decides whether this may run, BEFORE what is standing: the
    verb is defined as "only while syncing is off", and asking the ledger
    first meant the same command answered "nothing to hand back" on a box
    where syncing was on and would simply have rewritten the pins.
    """
    if not dry_run and load_conf()["selector_to_multiphp"] == "on":
        print(WITHDRAW_WHILE_ON)
        log("WITHDRAW refused — selector-to-multiphp is on")
        return False
    if not dry_run:
        # a restore's flags its end could not judge (claim_restored), save
        # an account still being restored, whose end judges them
        for user in restored_accounts():
            if not os.path.exists(restoring_path(user)):
                claim_restored(user)
    if not standing_pins():
        # a box that never mirrored, or one already withdrawn: a walk that
        # could only skip every domain is not run for it
        print("nothing to hand back — this server has set no PHP version")
        if not dry_run:
            clear_withdraw_pending()
        return True
    if not dry_run:
        mark_withdraw_pending()
    if not reconcile(dry_run=dry_run, reason=reason, withdraw=True):
        return False  # refused, suspended or deferred: the pass said why
    if dry_run:
        return True
    standing = standing_pins()
    if not standing:
        print("every PHP version this server set has been handed back")
        log("WITHDRAW complete — no pin of ours stands (reason=%s)" % reason)
        clear_withdraw_pending()
        return True
    pins, unusable = split_unusable(standing)
    if pins:
        count, left = name_some(pins)
        print("%d PHP version(s) this server set still stand (%s) — a "
              "document-root group was blocked or a write failed; run "
              "--withdraw again" % (count, left))
        log("WITHDRAW incomplete — %d pin(s) of ours still stand: %s "
            "(reason=%s)" % (count, left, reason))
        remember("handback-failed", "pins-standing", pins=count, change=reason)
    if unusable:
        # a retry changes nothing for these: what stands there cannot be
        # told until the record is back
        shown = ", ".join(unusable[:10]) + (
            ", and %d more" % (len(unusable) - 10) if len(unusable) > 10 else "")
        print("%d account(s) have an unusable ownership record (%s): what "
              "this server set for them cannot be told, and they were left "
              "alone — repair or remove each file (the log names it), then "
              "run --withdraw again" % (len(unusable), shown))
        log("WITHDRAW incomplete — unusable ownership record for %s "
            "(reason=%s)" % (shown, reason))
        remember("handback-failed", "record-unusable",
                 accounts=len(unusable), change=reason)
    return False


def withdrawal_due():
    """Whether the pins of ours are being handed back, or are about to be,
    while the mirror reads off: --disable's walk is under way
    (WITHDRAW_PENDING), or the remote flag killed a sync it turned on and
    --apply-flag has yet to turn the switches off and walk (effective_conf
    reads it off already). A PHP Selector change then hands its account
    back first, as that walk will (release); found in review for the kill."""
    return os.path.exists(WITHDRAW_PENDING) or \
        read_conf()["selector_to_multiphp"] == "on"


def mark_withdraw_pending():
    """A hand-back is under way (WITHDRAW_PENDING), and the public copy of
    the switch says so once the switch is off."""
    try:
        ensure_state_dir()
        with open_private(WITHDRAW_PENDING, "w"):
            pass
    except OSError as e:
        log("WITHDRAW-PENDING could not be recorded: %s" % e)


def clear_withdraw_pending():
    """Nothing of ours stands any more: a PHP Selector change has nothing
    to hand back, and the public copy says "off" again."""
    try:
        os.unlink(WITHDRAW_PENDING)
    except FileNotFoundError:
        return
    except OSError as e:
        log("WITHDRAW-PENDING could not be removed: %s" % e)
        return
    republish_state()


def split_unusable(standing):
    """standing_pins' answer as ({account: [domain, ...]}, [account whose
    record is unusable, ...])."""
    pins = {user: doms for user, doms in standing.items()
            if doms != [UNUSABLE_RECORD]}
    return pins, sorted(user for user in standing if user not in pins)


def disable(direction, reason="disable", dry_run=False, by="admin"):
    """Stop syncing, and hand every pin of ours back.

    `by` is kept as `disabled_by` (set_conf).

    The switch goes off FIRST. That makes the withdrawal the only writer:
    a Selector change arriving mid-way finds the mirror refusing, where
    withdrawing first let its pass re-pin a domain the walk had just
    handed back, and the flip then left that pin standing. Nothing needs
    the hook to see the hand-backs while on — their intents are retired
    whatever the reverse switch says (handle_event.retire_echoes).

    Why hand back at all: a mirror pin left standing decides what is
    served — PHP Selector governs only domains on the system default — so
    a stopped sync with pins standing leaves the Selector non-functional
    for every synced domain (measured: pin alt-php85, Selector moved to
    8.4, site kept serving 8.5; unpinned, 8.4 at once). Stopping only the
    reverse direction hands nothing back: that direction only records
    who owns a pin, and writes neither MultiPHP nor the Selector.

    Returns True when nothing of ours stands afterwards; the withdrawal
    reports what does, and --withdraw finishes it.
    """
    handing_back = "selector_to_multiphp" in direction_keys(direction)
    if dry_run:
        if not handing_back:
            print("would turn %s off; nothing to hand back" % direction)
            return True
        return withdraw(dry_run=True, reason=reason)
    if handing_back:
        # before the switch, so its public copy says "withdrawing" from the
        # first moment: a PHP Selector change the walk has not reached yet
        # hands its account back first (release)
        mark_withdraw_pending()
    set_conf(direction, "off", by=by)
    # With both directions off, nothing is left to run the sync by itself:
    # the hooks, the boot catch-up and the daily check go now, before the
    # hand-back, which needs none of them — its intents retire without the
    # hook, and nothing classifies with the listener off.
    refresh_triggers()
    if not handing_back:
        return True
    return withdraw(reason=reason)


# What an administrator sees. The module docstring above documents the design
# for whoever maintains this file; it is not help text, so the CLI prints
# these instead.
USAGE = """Usage: cloudlinux-multiphp-sync <command> [options]

Keeps the PHP version set in cPanel's MultiPHP Manager and the version set
in CloudLinux PHP Selector in agreement, in both directions. Root only.
Syncing ships off. CloudLinux may turn it on gradually, but only on servers
where nobody turned it on or off here: what you turn on or off by hand
stays as you left it.

Commands:
  --check (--user USER | --all-users)  report each domain's PHP version and
                                       which manager controls it; read-only,
                                       add --json for machine-readable output
  --first-run                          turn syncing on and bring every
                                       account into agreement
  --reconcile [--dry-run]              bring every account into agreement;
                                       --dry-run changes nothing
  --mirror --user USER [--dry-run]     apply one account's PHP Selector
                                       versions to MultiPHP Manager
  --disable [WHAT] [--dry-run]         turn syncing off, then hand every PHP
                                       version this server set back to the
                                       version the domain had before
  --enable  [WHAT]                     turn syncing on without reconciling
        WHAT is selector-to-multiphp, multiphp-to-selector or all (default)
  --withdraw [--dry-run]               hand back what --disable hands back,
                                       again — for versions a blocked group
                                       or a failed write left standing;
                                       only while selector-to-multiphp is off

Any command also takes --reason TEXT, recorded in the log for that run.
Log: /var/log/cloudlinux/cl-multiphp-sync.log"""

VERDICT_LEGEND = """What the VERDICT column in --check means:

  Normal
    mirrored-ok            PHP Selector controls the version, MultiPHP agrees
    owned-ok               MultiPHP Manager controls it; recorded, left alone
    selector (unmirrored)  left to PHP Selector, not yet applied to MultiPHP
    released               handed back to MultiPHP Manager when syncing was
                           turned off; keeps the version it had before
    out-of-coverage        not synced: PHP-FPM is on for this domain, or the
                           web server does not run its PHP as the user

  Recorded on the next run, nothing to do
    mirrored-unrecorded    both agree, and this server's record of setting it
                           is missing or names an older version
    owned-unrecorded       set in MultiPHP Manager, not by this server

  Worth a look
    unroutable             this web server has no handler for that PHP
                           version, so the domain is left to PHP Selector;
                           upgrade the web server or pick another version
    stale-mirror           PHP Selector changed and MultiPHP was not updated;
                           run --mirror --user USER for its account
    DRIFT(owned)           a MultiPHP-controlled version was changed outside
                           MultiPHP Manager, so the record is out of date
    not-in-userdata        this domain's version could not be read, so
                           nothing was judged or changed
    UNEXPLAINED            a version this server set has since been
                           contradicted; please report it"""


def main():
    try:
        run_cli()
    except Exception as e:
        # a detached pass runs with stderr closed, and the door's stderr
        # goes to a tenant: the log is the one place a crash must reach,
        # or a pass that died mid-fleet is indistinguishable from one that
        # never ran. And the daily report (remember): the door's argv is the
        # tenant's, so it names no verb there
        tb = traceback.format_exc()
        log("ENGINE ERROR: %s" % tb)
        door = os.environ.get("PROXYEXEC_UID") is not None
        remember("crash", type(e).__name__,
                 entry="door" if door else "engine",
                 verb="door" if door else next(
                     (a for a in sys.argv[1:] if a.startswith("--")), ""),
                 tb=tb)
        raise


def run_cli():
    # Both ids, not just the effective one: every legitimate caller is root
    # outright — a root shell, the packaged cron, the systemd units, and
    # the CageFS door, where cagefs.server setuid(0)s before exec. Only a
    # setuid-root wrapper arrives with euid 0 and a tenant's real uid, and
    # it would forward that tenant's argv into this CLI.
    if os.geteuid() != 0 or os.getuid() != 0:
        sys.exit("root required")
    args = sys.argv[1:]

    def arg(name, default=None):
        if name not in args:
            return default
        i = args.index(name) + 1
        # a trailing or missing value falls back to the default instead of
        # tracebacking: `--enable` alone is documented usage
        if i >= len(args) or args[i].startswith("--"):
            return default
        return args[i]

    # The CageFS proxyexec door (PROXYEXEC_UID is set only by cagefs.server).
    # cagefs.server FORWARDS any argv the in-cage caller appended after the
    # protocol arguments, so argv on this entry is tenant-controlled: the door
    # therefore takes no command line of the root CLI's at all, only the
    # steps of the caller's own PHP Selector change (door_args). Honouring
    # more would hand a tenant the root CLI — disabling the sync fleet-wide,
    # or reading and mirroring another account. Routed before the state
    # directory is made: a pass makes what it needs, and a door that refuses
    # (the mirror off) must leave nothing behind.
    if os.environ.get("PROXYEXEC_UID") is not None:
        proxyexec_mirror(door_args(args))
        return

    # The package's own calls, before the state directory is made too: on a
    # box nobody turned the sync on for, an install must create nothing.
    if "--refresh-triggers" in args:
        # and the public copy of the mirror switch: a box whose sync was on
        # before the copy existed gets it, and a copy the switches no
        # longer back goes (neither creates anything on a box with no
        # switches file)
        republish_state()
        refresh_triggers()
        # and the fleet judged again by the rules this package brings: what
        # an older one left standing (a nested site under an admin's pin,
        # a handler mismatch) would otherwise stand until the daily run
        # (found in review). Only where the mirror runs: nothing is
        # dispatched on a box that never turned it on.
        if load_conf()["selector_to_multiphp"] == "on":
            spawn_reconcile("package-update")
        return
    if "--remove-triggers" in args:
        with triggers_lock():
            remove_triggers(package_removal=True)
        return
    # the flag's units, on every server, and the package once
    if "--apply-flag" in args:
        apply_flag(arg("--reason", "remote-flag"))
        return
    if "--migrate-flag" in args:
        migrate_to_flag()
        return
    # the EasyApache hook's call: it exists only while the sync is on
    if "--easyapache-change" in args:
        handle_easyapache_change()
        return
    # the daily report (spawn_report): it reads and keeps what the state
    # directory holds, so it makes none
    if "--report" in args:
        wait_out(arg("--after"))
        run_report(test="--test" in args)
        return
    # what the UI's "Handled by" asks as root (clselectdomains): a read, so
    # it makes no state directory either
    if "--owned-pins" in args:
        if "--user" in args:
            user = arg("--user", "")
            if not ACCOUNT_NAME.match(user):
                sys.exit("--owned-pins --user takes an account name")
            users = [user]
        else:
            users = recorded_accounts()
        print(json.dumps({"ours": owned_pins(users)}, sort_keys=True))
        return

    ensure_state_dir()

    if "--help" in args or "-h" in args:
        print(USAGE)
        print()
        print(VERDICT_LEGEND)
    elif "--release" in args:
        # the PHP Selector change protocol (clselect.multiphp_sync_client):
        # step aside before the switch; --mirror --after-change and
        # --end-change end the change after it
        token = resolve_token(args)
        reason = arg("--reason", "selector-change")
        # the change lasts while the client's caller does (begin_change)
        owner = os.getppid()
        if "--users" in args:
            refused = release_many(resolve_users(args), token, reason,
                                   owner=owner)
            for user in sorted(refused):
                print("RELEASE-REFUSED %s %s" % (user, refused[user]))
            if refused:
                sys.exit(2)
        elif "--paced" in args:
            # acting for a tenant: the door's rules (tenant_step)
            if tenant_step(resolve_user(args), "--release", token, reason,
                           owner=owner):
                sys.exit(1)
        elif not release(resolve_user(args), token, reason, owner=owner):
            sys.exit(1)
    elif "--end-change" in args:
        token = resolve_token(args)
        users = (resolve_users(args) if "--users" in args
                 else [resolve_user(args)])
        for user in users:
            end_change(user, token)
    elif "--finish-rename" in args:
        # a rename's moves a pass held up (spawn_finish_rename)
        finish_rename(resolve_user(args), arg("--to"), arg("--domain"),
                      arg("--main"), arg("--after"))
    elif "--mirror" in args:
        if "--dry-run" in args:
            # a preview changes nothing, so it needs no exclusion — and
            # must never defer, or it would be silently incomplete
            mirror(resolve_user(args), reason=arg("--reason", "manual"),
                   dry_run=True)
        else:
            # --paced: the caller is acting for a tenant, so the pass
            # takes the same throttle the in-cage door applies. A
            # tenant-initiated action served by the root CLI (an
            # isolation toggle, and the convergence that follows a bulk
            # one) reaches this branch instead of the door, and
            # unthrottled it could drive one pass — and one Apache
            # rebuild — straight after another.
            user = resolve_user(args)
            wait_out(arg("--after"))
            fresh = "--settle" in args and \
                settle(new_pending_path(user), NEW_DOMAIN_SETTLE)
            if "--after-change" in args and "--paced" in args:
                # acting for a tenant: the door's rules (tenant_step)
                tenant_step(user, "--after-change",
                            resolve_token(args, "--after-change"),
                            arg("--reason", "manual"))
            else:
                guarded_mirror(user,
                               arg("--reason", "manual"),
                               pace="--paced" in args,
                               after_change=(resolve_token(args,
                                                           "--after-change")
                                             if "--after-change" in args
                                             else None))
            if fresh:
                reason = arg("--reason", "manual")
                debounce(new_pending_path(user),
                         lambda: spawn_mirror(user, reason, paced=True,
                                              settle=True))
    elif "--daily" in args:
        # the daily cron: converge first, so a change no hook reported is
        # caught within a day, then the read-only check the evidence trail
        # rests on, which also records what the pass left; and then the
        # daily report, also after a crash
        try:
            reconcile(reason="daily")
            check_all(as_json=True)
        finally:
            spawn_report()
    elif "--reconcile" in args:
        fresh = "--settle" in args and \
            settle(new_accounts_pending_path(), NEW_ACCOUNT_SETTLE)
        reconcile(dry_run="--dry-run" in args,
                  reason=arg("--reason", "reconcile"))
        if fresh:
            debounce(new_accounts_pending_path(),
                     lambda: spawn_reconcile(arg("--reason", "reconcile"),
                                             settle=True))
    elif "--check" in args:
        if "--all-users" in args:
            check_all(as_json="--json" in args)
        else:
            check(resolve_user(args), as_json="--json" in args)
    elif "--first-run" in args:
        first_run(arg("--reason", "first-run"), by="admin")
    elif "--withdraw" in args:
        # exit 2 while a pin of ours still stands: the message names it
        # and the remedy, and a caller that scripts this can tell
        if not withdraw(dry_run="--dry-run" in args,
                        reason=arg("--reason", "withdraw")):
            sys.exit(2)
    elif "--enable" in args:
        direction = arg("--enable", "all")
        if direction in ("selector-to-multiphp", "all"):
            # preserve the pre-sync divergence picture while it still
            # exists — convergence cannot recreate it
            write_baseline()
        set_conf(direction, "on", by="admin")
        refresh_triggers()
    elif "--publish-state" in args:
        # the package installer, on every install and upgrade: a box whose
        # sync was on before the public copy existed gets it now
        republish_state()
    elif "--disable" in args:
        # disable() brings the triggers along with the switch itself, and
        # the daily cron goes with them: the report says now what the hand-
        # back left
        dry_run = "--dry-run" in args
        try:
            if not disable(arg("--disable", "all"),
                           reason=arg("--reason", "disable"),
                           dry_run=dry_run, by="admin"):
                sys.exit(2)
        finally:
            if not dry_run:
                spawn_report()
    else:
        print(USAGE)
        print("\nRun --help for what each value in the report means.")


if __name__ == "__main__":
    main()

Directory Contents

Dirs: 0 × Files: 660

Name Size Perms Modified Actions
12.59 KB lrwxr-xr-x 2021-10-08 13:04:46
Edit Download
13.69 KB lrwxr-xr-x 2019-10-21 16:09:19
Edit Download
179.27 KB lrwxr-xr-x 2023-03-31 18:37:57
Edit Download
3.00 KB lrwxr-xr-x 2018-12-11 07:44:33
Edit Download
23.73 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
148.16 KB lrwxr-xr-x 2025-12-18 13:51:04
Edit Download
61.22 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
36.66 KB lrwxr-xr-x 2023-10-14 22:48:04
Edit Download
40.99 KB lrwxr-xr-x 2024-04-06 11:40:05
Edit Download
4.69 KB lrwxr-xr-x 2026-11-11 20:58:07
Edit Download
2.17 KB lrwxr-xr-x 2017-12-18 12:28:32
Edit Download
64.71 KB lrwxr-xr-x 2020-08-30 17:47:39
Edit Download
109.52 KB lrwxr-xr-x 2024-05-23 08:36:02
Edit Download
28.74 KB lrwxr-xr-x 2023-10-14 17:19:01
Edit Download
32.63 KB lrwxr-xr-x 2022-10-10 10:23:17
Edit Download
67 B lrwxr-xr-x 2022-10-10 10:23:17
Edit Download
45.04 KB lrwxr-xr-x 2025-07-15 09:41:57
Edit Download
151.73 KB lrwxr-xr-x 2025-07-15 09:41:57
Edit Download
4.04 KB lrwxr-xr-x 2025-07-15 09:41:56
Edit Download
122.35 KB lrwxr-xr-x 2025-07-15 09:41:57
Edit Download
130.36 KB lrwxr-xr-x 2025-07-15 09:41:57
Edit Download
16.54 KB lrwxr-x--- 2025-07-15 09:41:57
Edit Download
16.40 KB lrwxr-xr-x 2026-02-10 14:26:37
Edit Download
32.59 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
21.45 KB lrwxr-xr-x 2024-04-06 13:04:35
Edit Download
46.16 KB lrwxr-xr-x 2019-10-18 20:07:58
Edit Download
15.97 KB lr-xr-xr-x 2026-01-23 07:31:10
Edit Download
27.80 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
97.45 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
53.47 KB lrwxr-xr-x 2026-07-08 15:02:55
Edit Download
56.64 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
56.63 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
2.74 MB lrwxr-xr-x 2026-11-09 13:26:14
Edit Download
158.25 KB lrwxr-xr-x 2024-05-23 08:36:02
Edit Download
29.08 KB lr-xr-xr-x 2026-08-17 19:22:01
Edit Download
839.02 KB lrwx------ 2026-11-09 08:36:18
Edit Download
1.43 MB lrwxr-xr-x 2022-10-08 12:29:36
Edit Download
1.43 MB lrwxr-xr-x 2022-10-08 12:29:36
Edit Download
1.43 MB lrwxr-xr-x 2022-10-08 12:29:36
Edit Download
1.43 MB lrwxr-xr-x 2022-10-08 12:29:36
Edit Download
1.43 MB lrwxr-xr-x 2022-10-08 12:29:36
Edit Download
1.43 MB lrwxr-xr-x 2022-10-08 12:29:36
Edit Download
15.48 KB lrwxr-xr-x 2026-10-29 13:48:01
Edit Download
665 B lrwxr-xr-x 2026-10-29 13:47:57
Edit Download
23.51 KB lrwxr-xr-x 2026-10-29 13:47:57
Edit Download
1.83 KB lrwxr-xr-x 2026-10-29 13:47:57
Edit Download
37.38 KB lrwxr-xr-x 2026-10-15 16:33:16
Edit Download
32.45 KB lrwxr-xr-x 2026-05-04 20:33:46
Edit Download
97.19 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
27.60 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
69.69 KB lrwxr-xr-x 2025-12-18 13:51:04
Edit Download
45.11 KB lrwxr-xr-x 2023-10-14 22:48:04
Edit Download
61.42 KB lrwxr-xr-x 2025-12-18 13:51:04
Edit Download
375.66 KB lrwxr-xr-x 2024-11-05 07:47:21
Edit Download
41.21 KB lrwxr-xr-x 2026-09-22 11:04:35
Edit Download
7.34 KB lrwxr-xr-x 2026-10-29 13:51:23
Edit Download
48.56 KB lrwxr-xr-x 2026-10-29 10:56:28
Edit Download
6.15 KB lrwxr-xr-x 2026-10-29 13:51:23
Edit Download
2.17 KB lrwxr-xr-x 2026-10-29 13:51:23
Edit Download
1.93 KB lrwxr-xr-x 2026-10-29 13:51:22
Edit Download
1.93 KB lrwxr-xr-x 2026-10-29 13:51:22
Edit Download
3.55 KB lrwxr-xr-x 2026-10-29 13:51:23
Edit Download
63.98 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
20.43 KB lrwxr-xr-x 2023-10-14 17:19:01
Edit Download
382 B lrwxr-xr-x 2026-09-17 10:46:25
Edit Download
5.29 KB lrwxr-xr-x 2026-10-29 10:56:28
Edit Download
2.71 KB lrwx------ 2025-11-10 10:40:16
Edit Download
569 B lrwxr-xr-x 2026-11-12 13:20:52
Edit Download
569 B lrwxr-xr-x 2026-11-12 13:20:52
Edit Download
2.97 KB lrwxr-xr-x 2026-11-12 13:30:45
Edit Download
2.30 KB lrwxr-xr-x 2026-11-12 13:30:45
Edit Download
569 B lrwxr-xr-x 2026-11-12 13:20:52
Edit Download
569 B lrwxr-xr-x 2026-11-12 13:20:52
Edit Download
569 B lrwxr-xr-x 2026-11-12 13:20:52
Edit Download
499.79 KB lrwxr-xr-x 2026-10-29 10:56:28
Edit Download
569 B lrwxr-xr-x 2026-11-12 13:20:52
Edit Download
654 B lrwxr-xr-x 2026-10-29 10:56:28
Edit Download
4.03 KB lrwxr-xr-x 2026-10-29 13:16:55
Edit Download
374 B lrwxr-xr-x 2026-09-17 10:46:25
Edit Download
378 B lrwxr-xr-x 2026-09-17 10:46:25
Edit Download
10.46 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
492 B lrwxr-xr-x 2026-11-04 16:06:02
Edit Download
10.46 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
2.24 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
492 B lrwxr-xr-x 2026-11-04 16:06:02
Edit Download
2.24 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
569 B lrwxr-xr-x 2026-11-12 13:20:52
Edit Download
1.35 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
492 B lrwxr-xr-x 2026-11-04 16:06:02
Edit Download
1.35 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
4.30 KB lrwxr-xr-x 2026-10-29 13:47:57
Edit Download
863 B lrwxr-xr-x 2026-11-12 13:30:45
Edit Download
807 B lrwxr-xr-x 2026-10-29 10:56:28
Edit Download
11.88 KB lrwxr-xr-x 2025-11-10 10:42:43
Edit Download
78.68 KB lrwxr-xr-x 2021-10-09 07:08:37
Edit Download
13.05 KB lrwxr-xr-x 2019-10-12 00:47:15
Edit Download
251 B lrwxr-xr-x 2019-10-12 00:47:14
Edit Download
13.05 KB lrwxr-xr-x 2019-10-12 00:47:15
Edit Download
9.03 KB lrwxr-xr-x 2019-10-12 00:47:15
Edit Download
990 B lrwxr-xr-x 2019-10-12 00:47:14
Edit Download
1.43 MB lrwxr-xr-x 2026-03-02 08:19:02
Edit Download
1.48 MB lrwxr-xr-x 2026-11-19 12:05:52
Edit Download
10.03 KB lrwxr-xr-x 2026-11-19 12:05:45
Edit Download
73.94 KB lrwxr-xr-x 2024-04-06 11:40:05
Edit Download
147.42 KB lrwxr-xr-x 2023-10-15 03:50:57
Edit Download
319.56 KB lrwx------ 2026-11-10 00:44:27
Edit Download
23.56 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
25.33 KB lrwxr-xr-x 2024-05-23 08:36:03
Edit Download
10.20 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
492 B lrwxr-xr-x 2026-11-04 16:06:02
Edit Download
10.20 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
155.04 KB lrwxr-xr-x 2024-05-23 08:36:02
Edit Download
19.41 KB lrwxr-xr-x 2026-11-02 17:04:46
Edit Download
231.63 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
23.73 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
159.98 KB lrwxr-xr-x 2024-04-22 16:52:46
Edit Download
215.87 KB lrwxr-xr-x 2024-05-23 08:36:02
Edit Download
45.08 KB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
24.55 KB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
141.80 KB lrwxr-xr-x 2024-04-06 13:04:35
Edit Download
158.64 KB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
158.64 KB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
398.40 KB lrwxr-xr-x 2026-09-09 13:16:18
Edit Download
936 B lrwxr-xr-x 2026-11-02 17:04:38
Edit Download
938 B lrwxr-xr-x 2026-11-02 17:04:38
Edit Download
59.71 KB lrwxr-xr-x 2026-11-02 17:04:46
Edit Download
59.73 KB lrwxr-xr-x 2026-11-02 17:04:46
Edit Download
63.70 KB lrwxr-xr-x 2026-11-02 17:04:46
Edit Download
71.73 KB lrwxr-xr-x 2026-11-02 17:04:46
Edit Download
934 B lrwxr-xr-x 2026-11-02 17:04:38
Edit Download
55.70 KB lrwxr-xr-x 2026-11-02 17:04:46
Edit Download
59.72 KB lrwxr-xr-x 2026-11-02 17:04:46
Edit Download
116.08 KB lrwxr-xr-x 2026-11-02 17:04:46
Edit Download
51.71 KB lrwxr-xr-x 2026-11-02 17:04:46
Edit Download
65.13 KB lrwxr-xr-x 2019-10-12 00:48:04
Edit Download
61.10 KB lrwxr-xr-x 2019-10-12 00:48:04
Edit Download
162.18 KB lrwxr-xr-x 2026-08-31 15:58:38
Edit Download
3.27 KB lrwxr-xr-x 2026-08-31 00:00:00
Edit Download
12.11 KB lrwxr-xr-x 2021-12-15 12:46:10
Edit Download
29.15 KB lrwxr-xr-x 2019-10-21 16:09:19
Edit Download
25.02 KB lrwxr-xr-x 2019-10-21 16:09:19
Edit Download
32.52 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
16.42 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
328.52 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
36.61 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
110.63 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
32.52 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
20.38 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
24.55 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
28.49 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
220.80 KB lrwxr-xr-x 2024-04-02 18:37:43
Edit Download
220.80 KB lrwxr-xr-x 2024-04-02 18:37:43
Edit Download
220.80 KB lrwxr-xr-x 2024-04-02 18:37:43
Edit Download
91.24 KB lrwxr-xr-x 2021-10-09 07:08:37
Edit Download
1.43 MB lrwxr-xr-x 2022-10-08 12:29:36
Edit Download
1.43 MB lrwxr-xr-x 2022-10-08 12:29:36
Edit Download
1.43 MB lrwxr-xr-x 2022-10-08 12:29:36
Edit Download
1.43 MB lrwxr-xr-x 2022-10-08 12:29:36
Edit Download
73.99 KB lrwxr-xr-x 2020-08-30 17:47:39
Edit Download
557.79 KB lrwxr-xr-x 2022-10-08 17:27:36
Edit Download
11.10 KB lrwxr-xr-x 2026-11-25 22:27:50
Edit Download
11.44 KB lrwxr-xr-x 2026-11-25 22:27:50
Edit Download
1.63 MB lrwxr-xr-x 2026-11-25 22:27:50
Edit Download
148.97 KB lrwxr-xr-x 2026-11-25 22:27:50
Edit Download
4.83 KB lrwxr-xr-x 2026-11-25 22:27:50
Edit Download
24.11 KB lrwxr-xr-x 2026-11-25 22:27:50
Edit Download
58.70 KB lrwxr-xr-x 2026-11-25 22:27:50
Edit Download
64.12 KB lrwxr-xr-x 2026-11-25 22:27:50
Edit Download
26.59 KB lrwxr-xr-x 2026-11-25 22:27:50
Edit Download
54.80 KB lrwxr-xr-x 2026-11-25 22:27:50
Edit Download
8.03 KB lrwxr-xr-x 2026-11-25 22:27:50
Edit Download
6.58 KB lrwxr-xr-x 2026-11-25 22:27:50
Edit Download
6.29 KB lrwxr-xr-x 2026-11-25 22:27:50
Edit Download
4.42 KB lrwxr-xr-x 2026-11-25 22:27:50
Edit Download
82.38 KB lrwxr-xr-x 2026-07-08 15:02:55
Edit Download
20.52 KB lrwxr-xr-x 2026-08-18 13:12:49
Edit Download
61.10 KB lrwxr-xr-x 2019-10-12 00:48:04
Edit Download
1.41 MB lrwxr-xr-x 2026-04-17 16:38:56
Edit Download
1.47 MB lrwxr-xr-x 2026-04-17 16:38:56
Edit Download
11.32 KB lrwxr-xr-x 2026-11-11 20:59:06
Edit Download
31.94 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
129.65 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
16.46 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
11.30 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
2.27 MB lrwxr-xr-x 2026-04-17 16:38:57
Edit Download
6.92 KB lrwxr-xr-x 2026-11-23 20:39:33
Edit Download
7.84 KB lrwxr-xr-x 2022-04-18 17:09:02
Edit Download
10.48 KB lrwxr-xr-x 2024-07-02 21:04:19
Edit Download
24.00 KB lr-xr-xr-x 2026-01-23 07:31:10
Edit Download
56.33 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
40.12 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
328.52 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
328.52 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
328.52 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
65.13 KB lrwxr-xr-x 2019-10-12 00:48:04
Edit Download
101.55 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
65.13 KB lrwxr-xr-x 2019-10-12 00:48:04
Edit Download
65.13 KB lrwxr-xr-x 2019-10-12 00:48:04
Edit Download
1.92 KB lrwxr-xr-x 2026-11-21 17:56:08
Edit Download
15.31 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
52.49 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
70.39 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
38.14 KB lrwxr-xr-x 2020-11-06 14:24:16
Edit Download
189.76 KB lrwxr-xr-x 2026-01-16 01:48:25
Edit Download
29.27 KB lrwxr-xr-x 2024-07-02 21:04:21
Edit Download
11.88 KB lrwxr-xr-x 2025-11-10 10:42:43
Edit Download
121.41 KB lrwxr-xr-x 2024-05-23 08:36:02
Edit Download
11.30 KB lrwxr-xr-x 2026-11-02 17:04:46
Edit Download
12.35 KB lrwxr-xr-x 2026-05-04 20:33:46
Edit Download
7.84 KB lrwxr-xr-x 2026-02-10 14:26:37
Edit Download
738 B lrwxr-xr-x 2026-10-29 13:16:56
Edit Download
12.27 KB lrwxr-xr-x 2026-05-04 20:33:46
Edit Download
11.87 KB lrwxr-xr-x 2026-02-10 14:26:37
Edit Download
95.34 KB lrwxr-xr-x 2025-12-18 13:51:04
Edit Download
91.09 KB lrwxr-xr-x 2025-12-18 13:51:04
Edit Download
61.48 KB lrwxr-xr-x 2025-12-18 13:51:04
Edit Download
99.38 KB lrwxr-xr-x 2025-12-18 13:51:04
Edit Download
61.47 KB lrwxr-xr-x 2025-12-18 13:51:04
Edit Download
57.27 KB lrwxr-xr-x 2025-12-18 13:51:04
Edit Download
57.26 KB lrwxr-xr-x 2025-12-18 13:51:04
Edit Download
1.16 MB lrwxr-xr-x 2026-11-24 21:04:49
Edit Download
2.68 KB lrwxr-xr-x 2026-11-24 21:04:46
Edit Download
1.44 MB lrwxr-xr-x 2026-11-24 21:04:49
Edit Download
1.14 MB lrwxr-xr-x 2026-11-24 21:04:49
Edit Download
8.68 KB lrwxr-xr-x 2026-11-24 21:04:46
Edit Download
245.33 KB lrwxr-xr-x 2026-11-24 21:04:49
Edit Download
1.16 MB lrwxr-xr-x 2026-11-24 21:04:49
Edit Download
3.99 KB lrwxr-xr-x 2026-11-24 21:04:46
Edit Download
282.16 KB lrwxr-xr-x 2026-11-24 21:04:49
Edit Download
15.36 KB lrwxr-xr-x 2026-11-24 21:04:49
Edit Download
3.45 KB lrwxr-xr-x 2026-11-24 21:04:46
Edit Download
3.05 KB lrwxr-xr-x 2026-11-24 21:04:46
Edit Download
3.05 KB lrwxr-xr-x 2026-11-24 21:04:46
Edit Download
1.16 MB lrwxr-xr-x 2026-11-24 21:04:49
Edit Download
8.60 KB lrwxr-xr-x 2026-11-24 21:04:46
Edit Download
260 B lrwxr-xr-x 2026-07-28 19:53:26
Edit Download
24.61 KB lrwxr-xr-x 2026-05-13 06:34:25
Edit Download
132.08 KB lrwxr-xr-x 2022-10-08 08:02:59
Edit Download
217.16 KB lrwxr-xr-x 2026-11-24 08:16:04
Edit Download
17.09 KB lrwxr-xr-x 2019-10-15 21:49:06
Edit Download
131.91 KB lrwxr-xr-x 2021-10-08 19:47:35
Edit Download
35.48 KB lrwxr-xr-x 2026-11-11 20:59:06
Edit Download
692.36 KB lrwxr-xr-x 2026-11-11 20:59:06
Edit Download
63.98 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
2.08 KB lrwxr-xr-x 2026-10-29 13:51:23
Edit Download
31.84 KB lrwxr-xr-x 2026-11-09 08:36:18
Edit Download
80.86 KB lrwxr-xr-x 2020-08-30 17:47:39
Edit Download
2.07 KB lrwxr-xr-x 2025-09-23 08:27:35
Edit Download
24.95 KB lrwxr-xr-x 2023-10-14 17:19:01
Edit Download
117.67 KB lrwxr-xr-x 2024-05-23 08:36:02
Edit Download
5.33 KB lrwxr-xr-x 2025-09-23 08:27:35
Edit Download
10.79 MB lrwxr-xr-x 2026-11-03 08:49:37
Edit Download
1.54 MB lrwxr-xr-x 2026-11-24 08:16:04
Edit Download
159.98 KB lrwxr-xr-x 2024-04-22 16:52:46
Edit Download
50.23 KB lrwxr-xr-x 2022-04-18 17:09:26
Edit Download
323 B lrwxr-xr-x 2026-07-28 19:53:26
Edit Download
14.55 KB lrwxr-xr-x 2026-11-09 13:26:14
Edit Download
693.30 KB lrwxr-xr-x 2024-05-23 08:36:03
Edit Download
220.80 KB lrwxr-xr-x 2024-04-02 18:37:43
Edit Download
6.89 KB lrwxr-xr-x 2024-04-02 18:37:41
Edit Download
220.80 KB lrwxr-xr-x 2024-04-02 18:37:43
Edit Download
220.80 KB lrwxr-xr-x 2024-04-02 18:37:43
Edit Download
220.80 KB lrwxr-xr-x 2024-04-02 18:37:43
Edit Download
220.80 KB lrwxr-xr-x 2024-04-02 18:37:43
Edit Download
21.00 KB lrwxr-xr-x 2020-08-30 17:47:39
Edit Download
408.03 KB lrwxr-xr-x 2020-08-30 07:37:42
Edit Download
137.57 KB lrwxr-xr-x 2020-08-30 07:37:42
Edit Download
129.30 KB lrwxr-xr-x 2020-08-30 07:37:42
Edit Download
125.28 KB lrwxr-xr-x 2020-08-30 07:37:42
Edit Download
2.18 KB lrwxr-xr-x 2020-05-08 14:19:42
Edit Download
129.30 KB lrwxr-xr-x 2020-08-30 07:37:42
Edit Download
9.01 KB lrwxr-xr-x 2019-11-12 14:33:33
Edit Download
220.80 KB lrwxr-xr-x 2024-04-02 18:37:43
Edit Download
6.89 KB lrwxr-xr-x 2024-04-02 18:37:41
Edit Download
220.80 KB lrwxr-xr-x 2024-04-02 18:37:43
Edit Download
220.80 KB lrwxr-xr-x 2024-04-02 18:37:43
Edit Download
220.80 KB lrwxr-xr-x 2024-04-02 18:37:43
Edit Download
220.80 KB lrwxr-xr-x 2024-04-02 18:37:43
Edit Download
92.05 KB lrwxr-xr-x 2019-10-15 21:54:06
Edit Download
25.00 KB lrwxr-xr-x 2020-08-30 17:47:39
Edit Download
62.28 KB lrwxr-xr-x 2023-10-14 17:57:46
Edit Download
41.29 KB lrwxr-xr-x 2023-10-14 17:57:46
Edit Download
11.28 KB lrwxr-xr-x 2026-11-02 17:04:46
Edit Download
13.04 KB lrwxr-xr-x 2026-11-12 13:20:52
Edit Download
194.98 KB lrwxr-xr-x 2026-02-10 17:24:36
Edit Download
24.52 KB lrwxr-xr-x 2021-10-08 13:50:55
Edit Download
788 B lrwxr-xr-x 2026-11-12 13:20:52
Edit Download
49.05 KB lrwxr-xr-x 2026-05-05 11:28:24
Edit Download
17.29 KB lrwxr-xr-x 2026-10-02 12:13:50
Edit Download
16.41 KB lrwxr-xr-x 2024-09-24 02:24:38
Edit Download
31.79 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
983.79 KB lrwxr-xr-x 2026-11-09 08:36:18
Edit Download
101.16 KB lrwxr-xr-x 2023-10-14 22:53:07
Edit Download
101.11 KB lrwxr-xr-x 2023-10-14 22:53:07
Edit Download
479.93 KB lrwx------ 2026-11-10 00:44:27
Edit Download
11.88 KB lrwxr-xr-x 2024-09-24 02:24:38
Edit Download
11.88 KB lrwxr-xr-x 2024-09-24 02:24:38
Edit Download
19.88 KB lrwxr-xr-x 2024-09-24 02:24:38
Edit Download
16.27 KB lrwxr-xr-x 2024-09-24 02:24:38
Edit Download
19.87 KB lrwxr-xr-x 2024-09-24 02:24:38
Edit Download
25.33 KB lrwxr-xr-x 2024-05-23 08:36:03
Edit Download
12.28 KB lrwxr-xr-x 2024-07-02 21:04:21
Edit Download
93.03 KB lrwxr-xr-x 2023-04-02 00:29:07
Edit Download
16.41 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
89.40 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
20.35 KB lrwxr-xr-x 2024-09-24 02:24:38
Edit Download
969.55 KB lrwxr-xr-x 2025-10-07 08:50:28
Edit Download
159.98 KB lrwxr-xr-x 2024-04-22 16:52:46
Edit Download
94.85 KB lrwxr-xr-x 2023-03-31 21:30:18
Edit Download
19.88 KB lrwxr-xr-x 2024-09-24 02:24:38
Edit Download
15.88 KB lrwxr-xr-x 2024-09-24 02:24:38
Edit Download
19.88 KB lrwxr-xr-x 2024-09-24 02:24:38
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
683 B lrwxr-xr-x 2026-11-12 13:20:52
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
5.42 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
492 B lrwxr-xr-x 2026-11-04 16:06:02
Edit Download
5.42 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
5.42 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
492 B lrwxr-xr-x 2026-11-04 16:06:02
Edit Download
5.42 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
6.62 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
492 B lrwxr-xr-x 2026-11-04 16:06:02
Edit Download
6.62 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
2.65 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
492 B lrwxr-xr-x 2026-11-04 16:06:02
Edit Download
2.65 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
14.20 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
492 B lrwxr-xr-x 2026-11-04 16:06:02
Edit Download
14.20 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
65.83 KB lrwxr-xr-x 2026-11-12 13:20:52
Edit Download
10.54 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
492 B lrwxr-xr-x 2026-11-04 16:06:02
Edit Download
10.54 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
41.70 KB lrwxr-xr-x 2026-11-12 13:30:46
Edit Download
1.91 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
492 B lrwxr-xr-x 2026-11-04 16:06:02
Edit Download
1.91 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
17.04 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
492 B lrwxr-xr-x 2026-11-04 16:06:02
Edit Download
17.04 MB lrwxr-xr-x 2026-11-10 13:51:34
Edit Download
37 B lrwxr-xr-x 2026-11-12 13:20:52
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
151.34 KB lrwxr-xr-x 2026-10-15 13:01:13
Edit Download
74.02 KB lrwxr-xr-x 2026-10-15 13:01:13
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
10.12 KB lr-xr-xr-x 2026-01-23 07:31:10
Edit Download
200.70 KB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
23.14 KB lr-xr-xr-x 2026-01-23 07:31:10
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
839.76 KB lrwxr-xr-x 2026-11-02 17:04:46
Edit Download
425.19 KB lrwxr-xr-x 2026-02-10 17:24:36
Edit Download
12.37 KB lrwxr-xr-x 2026-02-10 14:26:37
Edit Download
206.30 KB lrwxr-xr-x 2024-04-06 12:45:10
Edit Download
620.49 KB lrwxr-xr-x 2026-09-29 17:49:51
Edit Download
379.25 KB lrwxr-xr-x 2026-09-29 17:49:51
Edit Download
25.40 KB lrwxr-xr-x 2020-08-30 17:47:39
Edit Download
21.03 KB lrwxr-xr-x 2020-08-30 17:47:39
Edit Download
251 B lrwxr-xr-x 2019-10-12 00:47:14
Edit Download
39.07 KB lrwxr-xr-x 2019-10-12 00:48:04
Edit Download
12.68 KB lrwxr-xr-x 2026-02-10 17:24:35
Edit Download
138.45 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
2.23 KB lrwxr-xr-x 2026-02-10 17:24:35
Edit Download
15.33 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
40.01 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
138.45 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
138.45 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
138.45 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
39.07 KB lrwxr-xr-x 2019-10-12 00:48:04
Edit Download
89.38 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
39.07 KB lrwxr-xr-x 2019-10-12 00:48:04
Edit Download
39.07 KB lrwxr-xr-x 2019-10-12 00:48:04
Edit Download
474.80 KB lrwxr-xr-x 2026-11-21 17:56:15
Edit Download
24.44 KB lrwxr-xr-x 2026-08-18 13:12:49
Edit Download
11.86 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
186.83 KB lrwxr-xr-x 2024-04-06 14:17:10
Edit Download
85.25 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
159.98 KB lrwxr-xr-x 2024-04-22 16:52:46
Edit Download
159.98 KB lrwxr-xr-x 2024-04-22 16:52:46
Edit Download
25.83 KB lrwxr-x--- 2024-05-22 16:19:58
Edit Download
15.94 KB lrwxr-xr-x 2024-04-06 11:32:54
Edit Download
197.24 KB lrwxr-xr-x 2026-07-08 15:02:55
Edit Download
197.24 KB lrwxr-xr-x 2026-07-08 15:02:55
Edit Download
42.22 KB lrwxr-xr-x 2026-07-08 15:02:25
Edit Download
110.92 KB lrwxr-xr-x 2019-12-15 02:52:41
Edit Download
58.30 KB lrwxr-xr-x 2019-12-15 02:52:41
Edit Download
63.03 MB lrwxr-xr-x 2026-04-07 17:09:08
Edit Download
839.76 KB lrwxr-xr-x 2026-11-02 17:04:46
Edit Download
39.66 KB lrwxr-xr-x 2026-11-02 17:04:46
Edit Download
35.59 KB lrwxr-xr-x 2026-11-02 17:04:46
Edit Download
35.59 KB lrwxr-xr-x 2026-11-02 17:04:46
Edit Download
11.27 KB lrwxr-xr-x 2026-11-02 17:04:46
Edit Download
16.98 KB lrwxr-xr-x 2020-08-30 17:47:39
Edit Download
3.41 MB lrwxr-xr-x 2026-08-24 06:01:51
Edit Download
107.23 KB lrwxr-xr-x 2025-12-18 13:51:04
Edit Download
37.48 KB lrwxr-xr-x 2026-07-08 15:02:55
Edit Download
13.03 KB lrwxr-xr-x 2026-07-08 15:02:55
Edit Download
65.87 KB lrwxr-xr-x 2026-07-08 15:02:55
Edit Download
10.00 KB lrwxr-xr-x 2026-07-08 15:02:25
Edit Download
9.02 KB lrwxr-xr-x 2026-07-08 15:02:25
Edit Download
49.78 KB lrwxr-xr-x 2026-07-08 15:02:55
Edit Download
45.36 KB lrwxr-xr-x 2026-07-08 15:02:55
Edit Download
23.36 KB lrwxr-xr-x 2026-07-08 15:02:25
Edit Download
65.80 KB lrwxr-xr-x 2026-07-08 15:02:55
Edit Download
35.52 KB lrwxr-xr-x 2026-07-08 15:02:55
Edit Download
24.41 KB lrwxr-xr-x 2026-08-18 13:03:55
Edit Download
11.27 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
2.23 KB lrwxr-xr-x 2026-10-29 13:51:23
Edit Download
155.16 KB lrwxr-xr-x 2026-11-09 08:36:18
Edit Download
11.30 KB lrwxr-xr-x 2026-11-02 17:04:46
Edit Download
113.57 KB lrwxr-xr-x 2024-05-23 08:36:03
Edit Download
721.38 KB lrwxr-xr-x 2026-04-14 18:44:32
Edit Download
12.40 KB lrwxr-xr-x 2024-04-06 13:04:35
Edit Download
13.05 KB lrwxr-xr-x 2019-10-12 00:47:15
Edit Download
45.20 KB lrwxr-xr-x 2026-08-18 13:12:49
Edit Download
11.87 KB lrwxr-xr-x 2026-08-18 13:12:49
Edit Download
4.07 KB lrwxr-xr-x 2019-10-12 20:09:13
Edit Download
85.60 KB lrwxr-xr-x 2021-10-08 15:43:26
Edit Download
16.39 KB lrwxr-xr-x 2021-10-08 15:43:26
Edit Download
93.32 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
1.43 MB lrwxr-xr-x 2022-10-08 12:29:36
Edit Download
7.19 MB lrwxr-xr-x 2026-10-23 17:23:21
Edit Download
16.70 KB lrwxr-xr-x 2023-10-14 20:31:02
Edit Download
66.13 KB lrwxr-xr-x 2023-10-14 17:19:01
Edit Download
66.13 KB lrwxr-xr-x 2023-10-14 17:19:01
Edit Download
11.31 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
12.71 KB lrwxr-xr-x 2020-08-30 17:47:39
Edit Download
3.05 KB lrwxr-xr-x 2024-02-27 08:24:43
Edit Download
217.16 KB lrwxr-xr-x 2026-11-24 08:16:04
Edit Download
3.19 KB lrwxr-xr-x 2026-11-12 13:20:52
Edit Download
25.44 KB lr-xr-xr-x 2026-08-17 19:22:01
Edit Download
19.23 KB lrwxr-xr-x 2025-06-06 14:16:26
Edit Download
19.14 KB lrwxr-xr-x 2025-06-06 14:16:26
Edit Download
4.64 KB lrwxr-xr-x 2025-06-06 14:14:43
Edit Download
182.07 KB lrwxr-xr-x 2025-06-06 14:16:26
Edit Download
26.83 KB lrwxr-xr-x 2025-06-06 14:16:26
Edit Download
11.16 KB lrwxr-xr-x 2025-06-06 14:16:26
Edit Download
18.82 KB lrwxr-xr-x 2025-06-06 14:16:26
Edit Download
19.08 KB lrwxr-xr-x 2025-06-06 14:16:26
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
57.27 KB lrwxr-xr-x 2025-12-18 13:51:04
Edit Download
53.10 KB lrwxr-xr-x 2025-12-18 13:51:04
Edit Download
20.43 KB lrwxr-xr-x 2026-08-18 13:12:49
Edit Download
53.13 KB lrwxr-xr-x 2025-12-18 13:51:04
Edit Download
78.67 KB lrwxr-xr-x 2021-10-09 07:08:37
Edit Download
115.75 KB lrwxr-xr-x 2021-10-09 07:08:37
Edit Download
83.16 KB lrwxr-xr-x 2021-10-09 07:08:37
Edit Download
83.16 KB lrwxr-xr-x 2021-10-09 07:08:37
Edit Download
16.54 KB lrwxr-xr-x 2021-10-09 07:08:37
Edit Download
3.70 KB lrwxr-xr-x 2026-09-29 17:43:39
Edit Download
24.55 KB lrwxr-xr-x 2023-10-14 17:19:01
Edit Download
187.38 KB lrwxr-xr-x 2024-05-23 08:36:02
Edit Download
19.40 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
144.26 KB lrwxr-xr-x 2024-04-06 12:45:51
Edit Download
217.16 KB lrwxr-xr-x 2026-11-24 08:16:04
Edit Download
83.24 KB lrwxr-xr-x 2021-10-09 07:08:37
Edit Download
24.38 KB lrwxr-xr-x 2021-10-08 13:50:55
Edit Download
64.91 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
48.45 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
194.37 KB lrwxr-xr-x 2026-11-24 08:16:04
Edit Download
20.53 KB lrwxr-xr-x 2024-07-02 21:04:21
Edit Download
16.41 KB lrwxr-xr-x 2024-07-02 21:04:21
Edit Download
52.23 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
7.30 KB lrwxr-xr-x 2026-10-29 13:51:22
Edit Download
7.30 KB lrwxr-xr-x 2026-10-29 13:51:22
Edit Download
4.26 KB lrwxr-xr-x 2026-10-29 13:51:22
Edit Download
4.26 KB lrwxr-xr-x 2026-10-29 13:51:22
Edit Download
159.98 KB lrwxr-xr-x 2024-04-22 16:52:46
Edit Download
35.38 KB lrwxr-xr-x 2026-11-02 17:04:46
Edit Download
19.40 KB lrwxr-xr-x 2026-11-02 17:04:46
Edit Download
23.39 KB lrwxr-xr-x 2026-11-11 20:59:06
Edit Download
67.63 KB lrwxr-xr-x 2020-08-30 17:47:39
Edit Download
106.54 KB lrwxr-xr-x 2026-07-08 15:02:55
Edit Download
61.73 KB lrwxr-xr-x 2026-07-08 15:02:55
Edit Download
163.04 KB lrwxr-xr-x 2026-07-08 15:02:55
Edit Download
49.92 KB lrwxr-xr-x 2026-07-08 15:02:55
Edit Download
103.30 KB lrwxr-xr-x 2026-07-08 15:02:55
Edit Download
60.41 KB lrwxr-xr-x 2026-10-15 13:40:53
Edit Download
9.41 KB lrwxr-xr-x 2026-07-08 15:02:25
Edit Download
19.38 KB lrwxr-xr-x 2026-07-08 15:02:55
Edit Download
31.59 KB lrwxr-xr-x 2026-10-15 13:40:53
Edit Download
723.50 KB lrwxr-xr-x 2026-10-12 15:31:43
Edit Download
46.94 KB lrwxr-xr-x 2024-05-23 08:36:02
Edit Download
48.08 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
117.27 KB lrwxr-xr-x 2024-05-23 08:36:02
Edit Download
25.33 KB lrwxr-xr-x 2024-05-23 08:36:03
Edit Download
217.16 KB lrwxr-xr-x 2026-11-24 08:16:04
Edit Download
1.63 MB lrwxr-xr-x 2026-11-25 22:27:50
Edit Download
47.71 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
46.62 KB lrwxr-xr-x 2019-10-21 16:09:19
Edit Download
20.77 KB lrwxr-xr-x 2022-02-23 20:13:56
Edit Download
16.42 KB lrwxr-xr-x 2022-02-23 20:13:56
Edit Download
20.52 KB lrwxr-xr-x 2024-04-06 13:44:54
Edit Download
65.35 KB lrwxr-xr-x 2026-02-10 14:26:37
Edit Download
12.28 KB lrwxr-xr-x 2026-02-10 14:26:37
Edit Download
12.27 KB lrwxr-xr-x 2026-02-10 14:26:37
Edit Download
11.89 KB lrwxr-xr-x 2026-02-10 14:26:37
Edit Download
11.88 KB lrwxr-xr-x 2026-02-10 14:26:37
Edit Download
11.88 KB lrwxr-xr-x 2026-02-10 14:26:37
Edit Download
11.88 KB lrwxr-xr-x 2026-02-10 14:26:37
Edit Download
7.84 KB lrwxr-xr-x 2026-02-10 14:26:37
Edit Download
11.86 KB lrwxr-xr-x 2026-02-10 14:26:37
Edit Download
12.36 KB lrwxr-xr-x 2026-02-10 14:26:37
Edit Download
41.18 KB lrwxr-xr-x 2024-07-02 21:08:27
Edit Download
29.27 KB lrwxr-xr-x 2024-07-02 21:04:21
Edit Download
16.91 KB lrwxr-xr-x 2026-11-25 22:27:50
Edit Download
3.64 KB lrwxr-xr-x 2025-09-23 08:27:35
Edit Download
20.41 KB lrwxr-xr-x 2024-07-02 21:04:21
Edit Download
16.27 KB lrwxr-xr-x 2026-05-04 20:33:46
Edit Download
12.27 KB lrwxr-xr-x 2026-02-10 14:26:37
Edit Download
20.53 KB lrwxr-xr-x 2024-07-02 21:04:21
Edit Download
28.56 KB lrwxr-xr-x 2023-03-31 21:30:18
Edit Download
91.38 KB lrwxr-xr-x 2021-10-09 07:08:37
Edit Download
3.34 KB lrwxr-xr-x 2024-04-06 13:44:45
Edit Download
16.38 KB lrwxr-xr-x 2024-07-02 21:04:21
Edit Download
117.30 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
21.06 KB lrwxr-xr-x 2026-07-08 15:02:55
Edit Download
217.16 KB lrwxr-xr-x 2026-11-24 08:16:04
Edit Download
11.87 KB lrwxr-xr-x 2026-05-13 06:34:25
Edit Download
43.76 KB lrwxr-xr-x 2020-08-30 17:47:39
Edit Download
78.13 KB lrwxr-xr-x 2026-07-08 15:02:55
Edit Download
902.46 KB lrwxr-xr-x 2026-09-08 13:02:12
Edit Download
724.59 KB lrwxr-xr-x 2026-09-08 13:02:12
Edit Download
627 B lrwxr-xr-x 2026-11-20 03:09:30
Edit Download
127 B lrwxr-xr-x 2026-11-20 03:09:30
Edit Download
117 B lrwxr-xr-x 2026-11-20 03:09:30
Edit Download
191.30 KB lrwxr-xr-x 2024-05-23 08:36:02
Edit Download
872.54 KB lrwxr-xr-x 2026-11-23 05:38:57
Edit Download
71.85 KB lrwxr-xr-x 2026-11-23 21:35:57
Edit Download
59.95 KB lrwxr-xr-x 2026-11-23 21:35:57
Edit Download
838 B lrwxr-xr-x 2018-09-06 18:09:08
Edit Download
45.98 KB lrwxr-xr-x 2021-12-15 12:46:22
Edit Download
19.35 KB lrwxr-x--- 2026-11-11 20:59:06
Edit Download
47.96 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
213.97 KB lrwxr-x--- 2026-11-24 07:35:09
Edit Download
22.84 MB lrwxr-xr-x 1990-01-01 12:00:00
Edit Download
15.36 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
19.52 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
48.12 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
15.35 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
28.88 KB lrwxr-xr-x 2023-10-14 20:31:02
Edit Download
415 B lrwxr-xr-x 2025-07-15 09:13:46
Edit Download
309.72 KB lrwxr-xr-x 2024-04-06 12:42:24
Edit Download
217.16 KB lrwxr-xr-x 2026-11-24 08:16:04
Edit Download
1.43 MB lrwxr-xr-x 2022-10-08 12:29:36
Edit Download
1.43 MB lrwxr-xr-x 2022-10-08 12:29:36
Edit Download
1.43 MB lrwxr-xr-x 2022-10-08 12:29:36
Edit Download
1.43 MB lrwxr-xr-x 2022-10-08 12:29:36
Edit Download
907.47 KB lrwxr-xr-x 2022-10-08 12:29:34
Edit Download
1.43 MB lrwxr-xr-x 2022-10-08 12:29:36
Edit Download
895.45 KB lrwxr-xr-x 2022-10-08 12:29:34
Edit Download
1.43 MB lrwxr-xr-x 2022-10-08 12:29:36
Edit Download
1.43 MB lrwxr-xr-x 2022-10-08 12:29:36
Edit Download
1.43 MB lrwxr-xr-x 2022-10-08 12:29:36
Edit Download
1.43 MB lrwxr-xr-x 2022-10-08 12:29:36
Edit Download
33.43 KB lrwxr-xr-x 2019-10-16 17:24:08
Edit Download
163.07 KB lrwxr-xr-x 2024-05-23 08:36:02
Edit Download
35.47 KB lrwxr-xr-x 2019-10-12 11:32:29
Edit Download
20.44 KB lrwxr-xr-x 2023-10-14 17:19:01
Edit Download
20.44 KB lrwxr-xr-x 2023-10-14 17:19:01
Edit Download
19.41 KB lrwxr-xr-x 2026-11-02 17:04:46
Edit Download
110.63 KB lrwxr-xr-x 2025-10-07 07:08:06
Edit Download
3.88 KB lrwxr-xr-x 2024-02-22 12:23:28
Edit Download
6.50 KB lrwxr-xr-x 2024-02-22 12:23:28
Edit Download
423.20 KB lrwxr-xr-x 2026-11-24 08:16:04
Edit Download
197.24 KB lrwxr-xr-x 2026-07-08 15:02:55
Edit Download
197.24 KB lrwxr-xr-x 2026-07-08 15:02:55
Edit Download
56.21 KB lrwxr-xr-x 2026-11-19 19:48:34
Edit Download
36.86 KB lrwxr-xr-x 2026-08-18 13:12:49
Edit Download
36.86 KB lrwx------ 2026-08-18 13:12:49
Edit Download
99.57 KB lrwxr-xr-x 2024-04-06 14:17:10
Edit Download
36.66 KB lrwxr-xr-x 2023-10-14 22:48:04
Edit Download
1.71 KB lrwxr-xr-x 2023-03-31 21:30:18
Edit Download
14.44 KB lrwxr-xr-x 2026-09-08 13:02:10
Edit Download
148.16 KB lrwxr-xr-x 2025-12-18 13:51:04
Edit Download
107.29 KB lrwxr-xr-x 2025-12-18 13:51:04
Edit Download
44.86 KB lrwx--x--x 2021-10-08 19:29:24
Edit Download
144.11 KB lrwxr-xr-x 2025-12-18 13:51:04
Edit Download
12.42 KB lrwxr-xr-x 2025-11-10 10:42:43
Edit Download
15.88 KB lrwxr-xr-x 2026-05-13 06:34:25
Edit Download
118.04 KB lrwxr-xr-x 2024-05-23 08:36:02
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
2.61 MB lr-xr-xr-x 2026-01-23 07:31:14
Edit Download
68.05 KB lrwxr-xr-x 2025-12-18 13:51:04
Edit Download
68.05 KB lrwxr-xr-x 2025-12-18 13:51:04
Edit Download
14.22 KB lrwxr-xr-x 2023-10-14 20:52:05
Edit Download
238.62 KB lrwxr-xr-x 2026-10-06 01:06:09
Edit Download
28.58 KB lrwxr-xr-x 2026-02-10 17:24:36
Edit Download
16.47 KB lrwxr-xr-x 2024-04-06 13:04:35
Edit Download
39.35 KB lrwxr-xr-x 2024-04-22 16:52:46
Edit Download
3.35 MB lrwxr-xr-x 2026-11-13 07:16:12
Edit Download
3.35 MB lrwxr-xr-x 2026-11-13 07:16:12
Edit Download
2.33 KB lrwxr-xr-x 2023-06-06 14:41:48
Edit Download
39.88 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download
308.02 KB lrwxr-xr-x 2026-07-29 02:18:05
Edit Download
66.92 KB lrwxr-xr-x 2026-07-29 02:18:05
Edit Download
369.39 KB lrwxr-xr-x 2026-07-29 02:18:05
Edit Download
2.69 KB lrwxr-xr-x 2026-11-21 17:56:08
Edit Download
695 B lrwxr-xr-x 2026-11-21 17:56:09
Edit Download
433.34 KB lrwxr-xr-x 2026-11-21 17:56:15
Edit Download
759.34 KB lrwxr-xr-x 2026-11-21 17:56:15
Edit Download
11.33 KB lrwxr-xr-x 2026-11-21 17:56:15
Edit Download
800 B lrwxr-xr-x 2026-11-21 17:56:09
Edit Download
52.21 KB lrwxr-xr-x 2026-11-21 17:56:15
Edit Download
421.29 KB lrwxr-xr-x 2026-11-21 17:56:15
Edit Download
1.26 KB lrwxr-xr-x 2026-11-21 17:56:10
Edit Download
187.09 KB lrwxr-xr-x 2026-11-21 17:56:15
Edit Download
453.53 KB lrwxr-xr-x 2026-11-21 17:56:15
Edit Download
408.86 KB lrwxr-xr-x 2026-11-21 17:56:15
Edit Download
782 B lrwxr-xr-x 2026-11-21 17:56:08
Edit Download
1.02 KB lrwxr-xr-x 2026-11-21 17:56:09
Edit Download
685 B lrwxr-xr-x 2026-11-21 17:56:08
Edit Download
92.79 KB lrwxr-xr-x 2026-11-21 17:56:15
Edit Download
714.02 KB lrwxr-xr-x 2026-11-21 17:56:15
Edit Download
15.32 KB lrwxr-xr-x 2026-11-21 17:56:15
Edit Download
44.23 KB lrwxr-xr-x 2026-11-21 17:56:15
Edit Download
16.45 KB lrwxr-xr-x 2021-10-09 07:08:37
Edit Download
220.80 KB lrwxr-xr-x 2024-04-02 18:37:43
Edit Download
220.80 KB lrwxr-xr-x 2024-04-02 18:37:43
Edit Download
19.49 KB lrwxr-xr-x 2026-11-09 08:36:18
Edit Download
51.75 KB lrwxr-xr-x 2026-11-09 08:36:18
Edit Download
101.92 KB lrwxr-xr-x 2026-11-09 10:27:50
Edit Download

If ZipArchive is unavailable, a .tar will be created (no compression).