# Account deletion retention

All deletion marking retains the company, users, relationships, business rows, queued data, files and statistics. The retention clock starts at the actual persisted `deleted_at`. Repeated marking leaves that timestamp unchanged. Restoration clears it and returns the company to active status. Payment-method cancellation and billing/notification actions performed during cancellation are not undone by restoration.

Permanent cleanup requires a freshly loaded, still-deleted, non-active company and a time strictly later than `deleted_at + 12 calendar months`. The exact anniversary is retained. Calendar addition clamps leap-day anniversaries to the last day of February; it does not use registration age, expiry age or a fixed number of days.

`CompanyRetention` coordinates marking, restoration, model-level and Eloquent bulk deletion and permanent cleanup using a row lock on the company's database connection. Permanent cleanup holds that lock through the destructive callback, with automatic transaction retries disabled. A normal restoration waits for that lock and checks whether the company still exists. Login, API login-token issuance/consumption and approved MCP grant use check availability before success or usage writes. Missing MCP approvers fail closed. Receiver import processing, stale import-deletion jobs and old media-file cleanup retain marked accounts and their child data. Direct newsletter test/debug mail and actual SMTP/email/SMS send methods use the same company lock and refuse deleted or missing accounts. Web access and account API sending also refuse those accounts. Existing queues are preserved during marking.

MCP bearer authorization and its usage write commit before the downstream tool request runs. An already admitted read may finish after marking; later authorization fails closed. `whileAvailable` and its `whileAvailableShared` alias take a shared company row lock. This permits independent statistics foreign-key checks and other senders while excluding the exclusive marking/restoration/purge lock. Actual-send callbacks retain that shared guard through transport, so marking still waits for admitted sends. These callbacks never update the company or upgrade/nest an exclusive company guard. `ImportReceivers` explicitly uses `whileAvailableExclusive` because quota publication obtains a company FOR UPDATE, matching receiver edits/API creation; its existing import serialization remains in place. Other availability callers were audited and do not write or exclusively lock the company row. New company-mutating callbacks must use the exclusive variant directly.

Shared callback depth is tracked per actual connection object. In local/testing, nested exclusive retention gateways and Laravel company write/outer FOR UPDATE queries throw LogicException before SQL can upgrade that connection's shared lock. Production reports the violation through the exception handler and lets the query proceed, preserving send-path behavior; SQL diagnostics contain placeholders without query bindings. Set ACCOUNT_CLEANUP_STRICT_LOCK_GUARD=true to enforce the same strict behavior in other environments. The callback contract still forbids company writes or lock upgrades. Child-row FOR UPDATE queries with plain company availability subqueries remain allowed. Nested shared callbacks restore their depth even after an exception, and normal exclusive marking/company changes are allowed once the shared scope exits. This check covers the application's Laravel connection/query paths; direct PDO and arbitrary non-Laravel SQL are outside this guard contract.

Email sendout dispatch commits its job claim before processing, then rechecks availability for initial job preparation and each individual recipient. A stable first job row within the sendout serializes duplicate/stat-priority decisions across its workers, rather than exclusively locking a company/sendout/receiver tracking parent. Dispatch releases the shared lock between recipients, preserves remaining receivers if marking occurs, and releases its committed reservation after a failed recipient so retry can resume from saved progress. Recipient statistics use the company/job connection with their fully qualified statistics table so stat, queue and recipient-progress writes commit or roll back together per recipient. Independently arriving tracking statistics can still insert while a dispatch guard is active. Rendering for one recipient remains inside that guard; no company lock spans the entire sendout job. No transaction automatically retries an external send or purge.

Ordinary cancellation still sets status 0, sends its existing notices and performs existing payment-method cancellation. Its legacy `CompanyDispatcher` job now marks deletion only if the company is still canceled and the current expiry plus seven days has arrived. `expire_date` is copied before adding days. Old auto-remove and campaign payloads are inert; they cannot purge, mark or reactivate an account. The class and historical protected payload fields remain solely for safe queue deserialization.

## Explicit operator commands

The separate prospective daily registration rule, runtime policy, immutable deployed-auth boundary, bounded pilot/enable process, journal uncertainty and protected restoration are documented in [daily-spam-hiding.md](daily-spam-hiding.md). It neither widens the fixed Oct8 cohort nor enables permanent cleanup. Historical NULL authentication fields never establish NEVER-login eligibility. Normal company lists hide abandoned markers; superadmins can review and restore retained marked accounts through the existing locked retention gateway. Daily account data remains retained for at least 12 calendar months from persisted `deleted_at`.

These examples are documentation, not authorization to change production accounts.

- `php artisan MarkSpamAccountsDeleted --limit=50 --after-id=0` reports the fixed registration-spam cohort, with pagination and the full conservative audit. Scope is immutable: IDs 43269-45090, package 1, active/non-deleted, name containing `tw1.ru` or `swtest.ru`, account strictly older than 30 days. Required evidence includes author comments, created notices, user-owned media, reseller links and manual-content editor references. Missing tables/columns fail closed.
- Only this fixed spam-marking workflow recognizes one unchanged automatic registration welcome notice. The notice must belong to the company and its owned, active main user, have type 2/status 1, exactly match the current registration welcome title/content, be created within 120 seconds of both registrations, have unchanged timestamps and no deletion or read links. Duplicate, additional, foreign, manual, edited or nonmatching notices remain blockers. The command derives the notice ID from database evidence and rechecks company, user, notice and read-link evidence with locking reads in the marking transaction. Ordinary audit report/count/explain methods retain their original notice exclusions. Every notice and all other data remain retained; all other legitimacy checks still apply.
- Marking apply requires 1-10 exact separately reviewed IDs: `php artisan MarkSpamAccountsDeleted --company-id=43269 --apply`. All requested IDs must pass initial scope/audit and each is revalidated under its company row lock immediately before marking. It never queues permanent cleanup. A later changed account stops the batch; earlier successfully marked accounts remain retained.
- `php artisan RestoreDeletedCompany --company-id=43269` reviews one retained account. Adding `--apply` restores that exact account through the shared lock, without recreating purged data or reversing canceled billing/payment actions.
- `php artisan CustomerCleanup --limit=10 --after-id=0` is a bounded dry-run by default. Reporting scans deleted rows in company-ID order and classifies eligibility with forward calendar arithmetic. Use the reported cursor for the next page.
- Permanent apply requires 1-10 exact IDs: `php artisan CustomerCleanup --company-id=43269 --apply`. Every requested account must be eligible; each receives fresh locked revalidation. The existing `allow_customercleanup` kill-switch must permit cleanup. There is no `--keep-company` option or one-month `allow_sendouts=0` fallback, and no scheduler automatically enables permanent cleanup.

## Retired campaign schema and operational limits

`AutoRemoveCompanies` and `KnownSpamCleanupCampaign`, their activation configuration, scope, runner, claims service and campaign schedule have been removed. Cached old configuration cannot activate absent code. Release preparation must account for long-lived workers still running old code; restart them through the approved deployment process before account changes. No command is provided to consume the retired campaign queue automatically.

The historical `2026_09_24_000001_create_known_spam_cleanup_claims` migration remains an inert compatibility record: both `up` and `down` issue no database writes. Pending environments install no table or trigger. Already-applied environments retain their existing schema and evidence; verify that state separately and use separately approved forward maintenance if removal is necessary. Never use an ad hoc rollback to remove historical schema.

`CompanyDataPurger` preserves the eventual permanent-cleanup footprint in a separate service. Its locked `CompanyPurgePreflight` runs before the first row mutation, file removal or statistics DDL. Unsupported company-product and receiver-delivery dependencies, retained MCP grants, foreign user overrides, foreign main-user/child references, shared manual content and cross-account comments/media/notices/list links stop cleanup. Missing required schema evidence also stops it. This conservative exclusion is separate from the required isolated rehearsal; it prevents known deterministic ownership/foreign-key failures from first erasing files. The shared permanent gateway enforces `allow_customercleanup` even for direct instance and bulk model calls. The company connection's transaction cannot roll back media/import file removal or statistics-table DDL on another connection. A timeout, connection loss, file error or statistics failure can leave partial external cleanup. The command stops on failure and does not automatically retry. Before any production permanent cleanup, require an isolated rehearsal and a verified targeted recovery procedure covering the precise records, statistics and files, including unrelated-account preservation and interruption behavior. No blanket atomicity or full restoration claim is made.

Preflight locks owned user, receiver and referenced parent rows on the company connection before checking dependencies; MySQL foreign-key inserts referencing those locked parents wait. This does not protect every child-table update or schema without enforced foreign keys. Permanent-purge release therefore also requires writer quiescence and an isolated concurrency/interruption rehearsal, alongside targeted filesystem/statistics recovery. The company row lock serializes the application retention and send paths; it is not a lock on arbitrary external SQL or every child-table writer. Do not bypass the shared interface with raw account deletion writes. Eloquent bulk `delete` and `forceDelete` route through the shared gateway; low-level query-builder SQL/update remains outside that application interface and must not be used for account lifecycle changes. SQLite unit tests prove policy/control flow and retained footprint. The opt-in `NUHET_LOCAL_MARIADB_TEST=1 php vendor/phpunit/phpunit/phpunit tests/Integration/CompanyRetentionMariaDbTest.php` uses only a randomly named disposable database on the local socket to test row locking and fresh eligibility. It does not run the full purger or prove rollback across files/connections.
