Repository navigation
Description
Priority: P1 — Architecture
Analysis baseline: main @ c0464d96, 9 November 2026. This includes the monitoring-capacity work in #392 / PR #404 and fault isolation in #403 / PR #405. It supersedes the original 3ec3455 inventory.
Decision
Keep the measured hybrid architecture. Bun owns application authorization, PostgreSQL transactions, domain workflows and incident policy. Rust owns native execution, private Caddy control, certificate/DNS authority and its existing autonomous workers. The root supervisor and root Bun backup executor retain their separate privileged maintenance authority. Caddy remains the sole public proxy data plane.
The remaining possible large Rust move is monitoring scheduling/execution autonomy, evaluated in #402 against the optimized hybrid. It is a conditional candidate, not an approved production migration. Discovery change notification is a narrower cross-language improvement in #394. Notification fairness, SQL efficiency, cancellation and observability have concrete improvements within their current owners.
The installation stays one jointly released appliance image/container with supported Docker and rootful Podman/Quadlet on AMD64/ARM64. This investigation changes no runtime owner, schema, process topology, dependency or backup format.
Decision vocabulary
- Keep in Bun: retain the application responsibility in its current runtime.
- Keep in Rust: retain existing native authority/execution; an RPC adapter does not transfer its caller's business authority.
- Partially move to Rust: move only the named trigger/execution responsibility through an explicit bounded contract.
- Candidate for full Rust migration: evaluate moving the entire named responsibility; current production ownership remains until the proof gates pass and implementation is separately authorized.
- No change required: preserve an already suitable arrangement, including its actual language/principal.
Rows split mixed features into responsibilities. “Autonomous” means a native scheduler does not need a Bun request for each pass; it does not by itself guarantee availability through every appliance fault.
Ownership decision matrix
Native responsibilities
| Responsibility / evidence | Classification | Scheduler, executor and state authority | Credentials / authorization | Recovery, maintenance and observability |
|---|---|---|---|---|
| Caddy configuration, activation and recovery | Keep in Rust | Bun publishes desired application state; Rust validates/renders/applies and owns verified active revision, private sockets, persisted snapshot and activation fences. Caddy forwards traffic. Rust recovery runs independently every 5s with bounded failure backoff. | Authenticated internal contract; controller/Caddy share UID 10001. Inherited ownership lock is a lifecycle guard, not a separate security principal. | Native rollback/recovery and exact child ownership stay local. Three failed live probes, three replacement admissions per rolling 300s, latched ownership-uncertainty circuit. Caddy-worker progress is separate from proxy readiness. Root owns whole-appliance failure/restart. |
| Certificate material, ACME, candidates and renewal | Keep in Rust | Rust owns certificate/material metadata, native operation/candidate journals, ACME and renewal. A 60s scheduler recovers due/candidate/manual-DNS work; issue/import/renew also have request-triggered operations. Bun owns application bindings and audit ingestion below. | Native keys and validated DNS connection references stay native; no browser/private-key transfer. Caddy automatic HTTPS remains disabled. | Bounded ACME admission 4; bounded candidate/cleanup work; interrupted native operations reconcile from durable journals. Root stops controller during privileged maintenance. Existing operation status/journals are useful; this is not uniform health coverage for all tasks. |
| DNS connections and autonomous DDNS | Keep in Rust | Rust owns provider execution, encrypted connection registry, saved DDNS revision/settings, due targets, in-flight marker, cooldowns and native events. Its 5s/wakeup scheduler is already autonomous; Bun supplies administration/RBAC/presentation. | Native registry grants, credential revisions, zone restrictions and read/modify/verify guards remain authoritative. Bun authorizes administrative calls. | Manual/scheduled work shares native exclusion; bounded 25s batch, 100 targets, persisted interruption/cooldown recovery. Restored external automation requires reactivation. Progress for the DDNS worker needs owner-specific observation through #396/#397. |
| Docker socket observation and inventory | Keep in Rust | One existing native observer subscribes before inventory, coalesces events and rotates/rescans after 60s. Connector configuration is durable; inventory/readiness/staleness is ephemeral. It observes candidates; it does not own application-host adoption. | Constrained validated GET-only client, bounded input/deadlines and no redirect/endpoint bypass. A read-only mount alone is not an API permission boundary. | Configuration change cancels observation; reconnect backoff caps at 60s; 500ms scan coalescing, at most 256 candidates and bounded bodies. Disabled/restored-paused configurations perform no Docker reads. Reconnect/resync remains native. |
| Requested host probes and diagnostics | Keep in Rust | Rust executes bounded configured-host DNS/TCP/TLS/HTTP observations. Bun currently schedules monitoring and commits results. Native snapshots/revision checks and per-host exclusion prevent stale or overlapping execution. | Configured active host/domain/revision only; scheduled upstream-only probes are credential-free HEAD checks, with verified TLS/trusted-CA controls and no followed redirects. Internal bearer is not user RBAC. | 64 scheduled plus 2 reserved interactive permits, with shared per-host exclusion; these are not the global ceiling for every native subsystem. Busy/cancelled/stale/unavailable are not host-down evidence. Default outer diagnostic budget 12s; final snapshot reserve 1s. |
| CrowdSec provider execution and Caddy integration | Keep in Rust | Rust validates/switches active provider transactionally, owns active native provider state and writes the managed-engine control contract. Bun owns desired application settings; root owns the managed engine process. | Managed key uses restricted files; external key arrives through the authorized Bun contract and is not persisted in the native desired snapshot. | Rollback/ownership and Caddy restart budget remain native. External cold-start credential replay requires Bun. Local API degradation/fail-open behavior is explicit and is not proof that enforcement or native scheduling is healthy. |
Application responsibilities
| Responsibility / evidence | Classification | Scheduler, executor and state authority | Credentials / authorization | Recovery, maintenance and observability |
|---|---|---|---|---|
| Monitoring policies, claims, history and incidents | Keep in Bun | PostgreSQL is application authority. Bun claims, hydrates/checks context, interprets native observations and commits fenced observations plus incident/notification inputs atomically. No second availability state machine belongs in Rust. | Fresh policy/host/grant/context checks, policy version, token, database-clock lease expiry, revision and host continuity proofs remain in protected application transactions. | 64 global active leases, batches 16, 45s lease, 2s transaction/lock/statement bounds; network I/O outside coordination transactions. Root web recovery does not itself turn this into autonomous monitoring. |
| Monitoring admission/schedule orchestration | Candidate for full Rust migration | Production remains the optimized Bun scheduler: continuous bounded refill, 250ms polling, fixed requested cadence and skipped missed periods. #402 may evaluate full native ownership of this scheduling responsibility while Bun retains policies/commits/incident policy. Native network execution is already Rust. | A prototype needs an explicit execution-authority protocol; cached settings or actor UUID alone are insufficient. Neither unrestricted application SQL access nor SMTP/webhook secrets are implied. | Existing stop aborts probes/admission and awaits late claim release. A native alternative needs durable bounded results, claim/replay/epoch fencing and restore participation before any continuity claim. Gates below compare it to the optimized 64/2 pipeline. |
| Notification collection, incident queue and transports | Keep in Bun | Bun collects sources and runs delivery independently within a pass. PostgreSQL configuration/runtime JSONB rows own durable collection/delivery leases, cursors, incidents, attempts and acknowledgements. Bun performs SMTP/webhook transport. Improve fairness in #393 first. | Fresh owner/category/channel revision/enabled/private-destination checks precede decrypt/send; preserve DNS pinning, TLS verification and payload allowlisting. Network work stays outside DB locks. | Four serial attempts/pass, then 15s sleep; 90s lease, 8 attempts, 256 queued deliveries, 4MiB state, 15s transport bound. Claim precedes send; ACK follows actual outcome. Crash-after-acceptance may duplicate delivery; stable webhook IDs support receiver deduplication, not exactly-once SMTP. No measured evidence currently justifies moving transport secrets/policy to Rust. |
| Docker adoption, ownership and host reconciliation | Keep in Bun | Bun reconciles complete native snapshots into PostgreSQL registry/owned hosts, audits the transaction and then requests proxy apply. Durable registry/tombstones/manual ownership stay application authority. | Revalidate delegated actor grants inside the write transaction. Only ready, fresh inventory matching current configuration revision and endpoint hash can mutate owned hosts. | Preserve bounded 16-change batches/fair progress, single-flight work, no destructive absence and no manual-host adoption. Missing/stopped containers do not silently delete/disable hosts. Current stop drains an in-flight pass; #395 supplies its cancellation/drain contract. |
| Docker inventory-change trigger across the boundary | Partially move to Rust | #394 should move inventory-change detection/wakeup from Bun's repeated 2s state polling to a native runtime/store identity plus monotonic inventory-generation hint. The native watcher already exists. Bun still owns DB-originated invalidations and authoritative reconciliation. | Bounded authenticated long-poll/revisioned invalidation; configuration revision alone is not inventory generation. Hints grant no adoption/host permission. | Coalesce to one running pass plus one dirty marker. After each bounded batch, self-rearm while the authoritative plan reports remaining eligible changes; yield fairly and back off rejected/failing work instead of hot-looping. Reconnect/store reset/lost wakeups require authoritative resync and a bounded fallback. Disabled discovery should avoid recurring registry reads except its declared safety fallback. No unbounded Docker event queue. |
| Proxy desired-state snapshot, mutation and drift reconciliation | Keep in Bun | PostgreSQL desired model/revision, actor authorization and audits stay Bun. Serialized/coalesced reconciliation invokes Rust and re-reads newest desired revision before reporting convergence. Rust owns active state above. | Application apply permissions and internal bearer remain separate. Do not copy SQL business rules into the controller. | Retry 1–60s, 60s drift observation, 20s apply timeout and 25s waiter/stop bounds. Dropping a caller does not cancel/undo a native apply; persisted native operation/revision must be reconciled. Drift observation still needs single-flight/cancellation work in #395. |
| CrowdSec desired settings and external credentials | Keep in Bun | SQL desired settings/fingerprint and encrypted external bouncer credential remain application authority. Bun replays desired configuration through native provider execution and verifies effective state. | Application permission/audit transaction remains Bun; external secret is decrypted only for the protected controller call. Native snapshot contains no replayable external key. | Shared reconciler retry/drift behavior; 60s waiter/stop. Preserve interrupted-apply reconciliation and restored automation/credential handling. Managed engine lifecycle is separate root authority. |
| Certificate binding jobs and host links | Keep in Bun | Bun/PostgreSQL owns durable stages, claims, host links and audits. Rust owns issuance/material/candidate execution. Bun binds only after current permissions/context and confirms the running proxy revision before terminal applied. | Recheck original actor, policy/host/domain/revision and discovery ownership at each protected stage; retain per-job encrypted request context and token/expiry fences. | Four concurrent jobs, 90s leases, 5s completion-relative tick. Stop drains but does not cancel already-dispatched native side effects. Expired DB authority does not prove an ACME/apply operation never happened. Native idempotency and job reconciliation remain required. |
| Certificate metadata, event receipts, audit and cursor | Keep in Bun | Rust produces bounded native events/material metadata; Bun transactionally commits unique receipt, metadata, audit and cursor in PostgreSQL. Preserve one owner for application audit semantics. | Protected metadata APIs and application transactions; do not send private certificate material merely to synchronize metadata. | 15s poll, up to 5 pages of 100 events/pass, bounded receipt retention. Store/reset/cursor rules prevent duplicate audit. Stop drains current fetch/commit; #395 must report its actual outcome truthfully. |
| Backup outcome audit/notification ingestion | Keep in Bun | Root agent produces durable outcomes, Rust forwards them, Bun commits application audit/notification input/cursor and ACKs producer disposal only after DB commit. | Internal token; original actor and allowlisted outcome metadata preserved; no off-host secret ownership in this consumer. | 100 events/batch, 15s poll, 5s DB/stop bounds; cursor/store reset and committed-prefix replay survive crash/restore. Current source fetch under cursor transaction needs measurement in #399, not an unmeasured claim of regression. |
| History/session/audit retention and NPM temporary cleanup | Keep in Bun | Monitoring/notification retention belongs to their data owners. Session/audit pruning is request/write-driven SQL housekeeping. NPM pruning is the immediate/hourly Foundation-managed local cleaner. | Application transactions/retention authority; importer cleanup matches only known files/directories and skips symlinks. | Keep work bounded and drain the cleaner; no new native scheduler justified. At 1,000 one-minute policies the 100k global observation cap is an average capacity of 100 samples/policy, not a promise of per-policy fairness or 24h/7d history. |
Process, infrastructure and intentional exclusions
| Responsibility / evidence | Classification | Scheduler, executor and state authority | Credentials / authorization | Recovery, maintenance and observability |
|---|---|---|---|---|
| Appliance process supervisor and managed CrowdSec engine | No change required | Root shell owns process identities, startup/stop order, maintenance and eligible web replacement. The managed CrowdSec supervisor owns its engine recovery. Native/application workers do not take root process authority. | UID 0 supervises web UID10002, controller/Caddy UID10001, CrowdSec UID10003 and PostgreSQL's own identity. Existing privileged paths remain constrained. | Eligible unexpected web loss preserves controller/Caddy identity; critical child/dependency failure or unsafe ownership/maintenance ends the appliance. Three web admissions/300s; TERM 18s + KILL/reap reserve 2s; bounded backoff and 60s new-web readiness. |
| Root Bun backup agent, export and destructive restore | No change required | Separate root Bun agent schedules durable jobs under an exclusive lock; root exporter/shell executes PostgreSQL capture/replacement, private artifact publication and key reload. Root-private jobs/artifacts/journals are authority. | Root is required for this executor's narrow maintenance role. Moving it into the unprivileged controller would broaden authority and couple it to a process intentionally stopped during capture. A separate Rust executor has no demonstrated benefit here. | One serialized 1s tick; durable intent before execution. State services remain available while consumers drain. Uncertain drain/export cleanup fails closed; restore success requires fresh readiness and matching operation/metadata proof. Agent survival is not a promise that any backup can execute through arbitrary web/controller failure. |
| Backup control API facade | Keep in Rust | Fixed typed HTTP-to-private-Unix-socket forwarding only. It is not a backup scheduler, database owner or root executor. | Configured token, bounded validated commands/IDs/JSON and fixed paths. Socket access does not grant arbitrary shell/root operations. | Bounded forwarding/unavailable result; producer authority stays with the root agent. Preserve this split rather than labeling backup execution as already Rust. |
| Web restore watcher, request gate and destructive quiescence | Keep in Bun | Root owns operation/progress; Bun fences new requests, drains admitted work/workers, closes its DB pool and writes an operation-bound acknowledgement. Root then owns replacement/restart. | Cached permitted pre-restore local sessions serve bounded maintenance snapshots. Root validates acknowledgement owner/link/size/operation. | 250ms watcher plus per-request checks. It intentionally remains available while ordinary workers stop. Safe early preparation failure can release a temporary gate; destructively quiesced old processes never resume writers. New web can be ready while workers wait for confirmed restore success. |
| Foundation worker lifecycle | Keep in Bun | Nine registrations: eight domain workers/reconcilers plus NPM cleanup. It coordinates loading/start/stop and permanent in-process maintenance fencing; domain state machines retain their owners. | Lifecycle coordination grants no new DB/root/native privilege. | Shutdown during import waits and stops once. Current start/stop contract lacks uniform IDs, health, retry/cancellation and honest timeout outcomes. Improve these through #395; a timeout race alone does not prove quiescence. |
| Valkey bridge and per-client realtime timers | No change required | Bun owns authenticated WebSocket subscriptions, sampling/backpressure and ephemeral invalidation. Root owns ephemeral Valkey process lifecycle; PostgreSQL/native stores own durable business state. | Browser origin/session/subscription permissions remain application concerns. No durable queue/authority is moved to Pub/Sub. | Valkey bridge is directly started and shutdown-managed, intentionally outside Foundation maintenance worker stop. Subscription timers are per-client scoped work with one flight/dirty marker, not autonomous global jobs. Reconnect/lost events require resampling. |
| Version checks and other request-scoped async work | No change required | Bun version lookup is request-triggered cached/single-flight work, not a periodic version worker. Native DNS setup/propagation fan-out, apply/import/CrowdSec joins and HTTP connection tasks are operation-scoped execution. | Preserve existing scoped auth, request bounds and safe output; do not create duplicate background roles for ordinary async calls. | Version cache: 1h complete /5min incomplete, 20s overall deadline. Operation tasks need existing cancellation/persistence semantics. Renewal's detached DNS permission-recovery wrapper is a lifecycle/observation gap, not evidence for moving the feature to another language. |
| Worker diagnostics and support aggregation | No change required | Each executor observes its own actual work; Bun aggregates authorized sanitized diagnostics. #396 extends this contract with bounded owner-specific status, not a new scheduling authority. | Allowlisted aggregate output and export permission; no domains, recipients, payloads, keys, raw errors or high-cardinality identifiers as metric labels. | Current support limit 64KiB. Caddy recovery progress is scoped to that worker, not a heartbeat for renewal/DDNS/discovery or the entire controller. Unknown/absent evidence must remain unavailable. |
Cross-cutting authority and lifecycle facts
- The controller has no PostgreSQL/Valkey driver or application DB role. Bun's SQL client is constructed without an explicit application pool ceiling; observed fixture connections are not a production pool configuration. Source: Cargo dependencies, Bun DB construction.
- Root installs an owner-private copy of the same installation application key for Rust; it is not a separate cryptographic application key. Controller token access and private paths reduce direct access, but a compromised Bun with the token can exercise the controller API. Caddy/controller share a principal. Source: key copy, assurance boundary.
- Ordinary appliance shutdown has a shared 25s budget, with approximately 23s for consumer drain. Native controller shutdown has a shared 20s signal-time budget. Some Bun reconciler waits are 25s/60s while web's force-exit guard is 18s. Standardize Background Worker Lifecycle and Recovery #395 must reconcile actual cancellation/drain and irreversible restore state; raising a timeout or clearing a timer is not proof that writers stopped.
- Only the Caddy recovery worker currently has the new completed-tick/circuit health contract. Native task join failure reporting does not supervise every detached task. Renewal's DNS permission recovery wrapper may spawn per tick; effective cleanup is serialized by its native lock and bounded cleanup work. Track it in Standardize Background Worker Lifecycle and Recovery #395/Introduce Comprehensive Background Worker Observability #396, without inventing an extra persistent worker category.
- Other native admission pools remain separate: DNS assistant 2, interactive diagnostics 2, scheduled monitoring 64, upstream-health requests 8; ACME has its own limit 4. A combined mixed-load/fairness budget is still Improve Background Scheduling, Backpressure and Resource Budgets #400 work. Source: runtime admissions.
- Preserve version-7 native snapshots, the v4 backup/restore contract, root journals, matching key/data pairing, explicit reactivation of restored external automation and compatible old readers. An added durable outbox/protocol needs its own format/upgrade/restore/rollback design.
Evidence and quantitative interpretation
Monitoring: published matched capacity evidence
#404 reports measurements at commit 305ebd2. These are prior experiment results, not a fresh benchmark of c0464d9. Native controller/Caddy had 2 CPUs/512MiB; PostgreSQL 2 CPUs/1GiB. Bun included an SSR adapter in the same process, with independent request timing. CPU/RSS below measure that Bun process, not combined appliance resource use.
All policies requested 60s. Mixed probes were 25% each at 20ms, 150ms, 1s and a real 3s timeout. The serial reference is one active check plus a completion-relative 1s wait on the same final storage/native runtime; it is a scheduling reference, not an older released appliance.
| Workload | Committed / observed window | Checks/s | Worker-start p99 | Commit p99 / max | SSR p99 / errors | Bun average cores / sampled peak RSS |
|---|---|---|---|---|---|---|
| Serial mixed reference | 51 /120s | 0.425 | 116.426s | 115.268s /115.268s | 6.65ms /0 | 0.055 /218.48MiB |
| Optimized hybrid, mixed 3s | 2,000 /120s | 16.649 | 20.125s | 22.677s /23.457s | 10.17ms /0 | 0.173 /271.01MiB |
| Optimized hybrid, all 3s timeouts | 2,000 /120s | 16.664 | 50.710s | 53.875s /54.112s | 10.80ms /0 | 0.111 /258.15MiB |
| Optimized hybrid, all 10s timeouts | 1,088 /180s | 6.033 | 154.870s | 165.051s /165.522s | 7.36ms /0 | 0.059 /237.00MiB |
The 3s cases had exactly 1,000 distinct committed policies per period, no duplicates/unknown outcomes and boundary backlog [0,0]. Observed active DB connections were 3 mixed /2 all-timeout; these are samples, not a configured pool ceiling. Native proxy p99 was 8.25ms mixed /5.00ms all-timeout, with zero observed traffic errors.
The 10s case did not meet 1,000/minute: backlog [680,616,616], with bounded cancellation/release at stop. At 1,000 checks/60s and 10s occupancy, the sizing lower bound is ceil(1000 × 10 /60) = 167 occupied slots, before overhead/reserves. That arithmetic is not a measured capacity result or permission to increase the existing 64 limit. A Rust scheduler using the same 64 network slots does not remove that bound.
Storage-phase p99, measured per bounded batch, was claim/context/commit/retention 52.19/48.88/129.19/11.53ms mixed and 117.60/112.57/210.05/12.57ms all-3s-timeout. These include coordination/wait/hydration work; they do not isolate JSON/hash CPU. #399 should profile those costs rather than infer a language migration benefit.
Evidence limits: the committed monitoring harness labels its management list reads and lack of SSR accurately. The extra SSR adapter behind #404's results was a local verification fixture. #397 must make an equivalent SSR/authenticated-management workload reproducible before comparing production migrations. The split #404 resource envelope is not the named 2-CPU/1GiB whole-appliance reference from #397. Existing production validation allows 30–86,400s intervals and 1–10s timeouts; the 1,000-at-60s result is not capacity for every allowed combination.
Fault isolation and actual continuity evidence
Current-source CI passed 66 appliance, 12 managed-backup, 59 proxy, 61 certificate/ACME and 21 upstream-TLS checks. Web TERM/KILL/STOP recovery measured 2.265s/2.821s/38.119s with zero errors among sampled HTTP/HTTPS requests. During the stopped original web identity, six Caddy recovery ticks completed; native controller/Caddy identities and active revision stayed unchanged.
This proves the tested eligible web-fault/process boundary and Caddy-worker progress. It does not prove ongoing host-monitor scheduling, notification delivery or every renewal/DDNS task through Bun absence. Root-critical failures, exhausted circuits and maintenance deliberately have different boundaries.
The green #405 checks ran at 4f08aac. Its Git tree and c0464d9 are identical: aa1abe179e74ddf9c78972454c5e2138065a3ac3. The analysis therefore uses tested current source without presenting an architecture investigation as a new performance run.
Predeclared proof gates and migration costs
These are engineering acceptance gates for the scoped future experiments. They are not advertised production SLOs, measured candidate results or authorization for a production migration. Keep workload/envelope/version fixed for a comparison; revise a gate with reasons before running it, not after a failing result.
Common A/B protocol
Use the optimized hybrid as A. First establish the workload in #397's explicitly named whole-appliance reference (2 CPUs, 1GiB, 512 PIDs, 100-connection guard), with exact source/image, real controller/upstreams, continuous native traffic and representative management/SSR load. If A cannot meet that envelope, record the unmet budget and use a separately named supported envelope before comparing B; do not relabel #404's split fixture as the same budget.
Run three paired bounded 120s steady-state samples after warmup, 1,000 policies at 60s with mixed and all-3s-timeout profiles. Keep p99 due-to-worker-start ≤55s, max due-to-committed-result ≤60s, one distinct result/policy/period, zero growing due backlog, SSR p99 ≤250ms and native traffic p99 ≤250ms with zero unexplained errors. Report CPU, RSS, DB connections/locks, execution throughput, admission lag, commit lag and failures separately. For a continuity prototype distinguish native durable raw results from later PostgreSQL-committed observations and report both clocks.
Treat the 10s all-timeout case as an explicit overload characterization unless a separately supported budget is established. Requested intervals never change silently. Fault samples are separate from steady-state/trend evidence; ordinary contributions retain short profiles, with release-duration soaks reserved for release preparation or an explicit owner request.
| Candidate / owner | Measured or source baseline and benefit to prove | Numeric success / no-go gate | Added cost and bounded proof |
|---|---|---|---|
| #402: native monitoring scheduler/execution autonomy only | Native probes already exist; current Bun cannot admit another monitoring pass while its process is stopped. Optimized A's healthy capacity above is the comparison. The proposed benefit is durable execution continuity, not “Rust does I/O faster.” | Under a real supported Bun STOP window observed for at least 25s, B must start and durably record at least 128 distinct policy checks after confirmed stop, beyond merely finishing up to 64 already admitted calls, while retaining native identity. Keep 1,000/60s steady-state gates. Replay one 1,000-result backlog within 30s of restored authority, without duplicate observations/incidents or stale commits. A sample without the declared actual fault window is insufficient evidence. | Design policy/version/authority acknowledgement, per-host exclusion, durable attempt IDs, bounded raw-result storage, receipt/ACK replay, store/restore epoch, storage pressure and retention. Initial proof caps: 4,096 records AND 16MiB encoded durable outbox, 120s reference retention window; filling either cap must backpressure/degrade visibly rather than drop silently. Scheduler CPU overhead ≤10% in matched equal-work healthy samples; the fault sample must remain within its predeclared absolute supported CPU envelope and preserve native traffic/reserves, reporting CPU and completed work separately. Added combined sampled RSS ≤32MiB relative to matched process-envelope A; at most 2 extra DB connections only if a separately justified least-privilege role is selected. No production migration until the authority and restore designs pass. |
| #402: resource-efficiency justification, if claimed | #404 only measured Bun CPU/RSS, so combined-system savings are currently unknown. Bun/SSR still exists after moving a scheduler. | Require ≥20% reduction in combined-system CPU or RSS across three paired samples, exceeding twice the measured run-to-run variation, with no loss of freshness, throughput, management/proxy behavior or security. Otherwise no-go for an efficiency-only migration. | Capture Bun + Rust + PostgreSQL + Caddy separately and in total; include serialization/IPC, native store/replay and cold/restart cost. Do not count work moved to another process as eliminated work. |
| #394: native inventory-generation/wakeup contract | Current Bun checks discovery every 2s: approximately 30 cycles/minute even when no inventory changed. This is a code-derived cadence, not a measured query benchmark. Native events already exist. | Establish enabled/disabled idle query baselines first, then ≥90% reduction in recurring inventory/reconcile reads. Proposed safety fallback ≤60s; a single relevant event p99 ≤2s to committed eligible host. In a healthy eligible fixture, 32 changes delivered by one coalesced hint converge within 10s under the declared 256-candidate connector limit, with no further hint. Keep one flight + one dirty marker, fair bounded batches and explicit self-rearm while eligible work remains. | Runtime/store epoch + inventory generation + reconnect/reset/ack/resync semantics; authenticated bounded waits; DB-originated edit/revocation invalidations and authoritative fallback. Test the single-hint multi-batch drain and bounded retry of failing/rejected work. Reject stale endpoint/generation/incomplete inventory writes and any unbounded event queue. Preserve the existing native watcher and Bun domain owner. |
| #393: notification fairness inside Bun | Source upper bound is 4 attempts per 15s plus pass duration; slow 15s transports worsen it. No matched incident-storm DB/latency benchmark is published here. This supports measuring scheduling/concurrency first, not moving transport secrets. | First proposal for a fixed mixed-channel fixture: global 8 sends, ≤2/channel and ≤4/owner; healthy delivery-start p99 ≤5s and drain 128 healthy deliveries ≤30s behind two failing channels. Exercise >256 potential deliveries with visible durable/deferred admission; never expand the queue silently. Lost-wakeup recovery ≤30s. No-go if fairness or authorization/retry fences regress. | #393 establishes actual baseline and candidate, with #399's locked JSONB cost. Keep collection and delivery independent; declare DNS/TLS/retry outcomes, stable webhook IDs and receiver deduplication. A Rust transport move is not selected; revisit only with new matched evidence and explicit secret/policy-boundary design. |
| #395/#396: lifecycle/owner-local observation | Current 18s web guard versus 25s/60s worker waits; progress coverage is incomplete. Shared names/statuses alone do not stop writes. | Proposed internal soft drain ≤15s where cancellation permits, leaving reserve within 18s; uncancellable/native side effects require truthful incomplete/timeout reporting and permanent destructive fencing, not a fabricated safe checkpoint. Observability target: ≤3% added total CPU, ≤8MiB RSS, bounded per-class backlog sampling at most once/30s, fixed cardinality and support export ≤64KiB. | Review every factory and intentional exclusion. No generic resume of the old destructively quiesced process. Join/cancel handles where needed, retain domain journals/leases and test hanging import/network/persistence, late callbacks, error sinks and resets. Measure overhead under the same saturated workload. |
Mandatory #402 authority/persistence gate: compare (A) current Bun SQL coordination, (B) controller-native durable raw results plus application commit/ACK, and (C) a narrowly scoped DB interface only if needed. An API served only by Bun cannot provide Bun-independent persistence. No branch of the comparison receives unrestricted application DB credentials, root authority or SMTP/webhook secrets.
A cached actor UUID, configuration revision or an unexpired native file alone is not fresh application authorization. Define current/effective policy and grant versions, leases/capabilities, revocation/edit/disable/delete acknowledgement, cancellation, controller replacement and result commit authority. Preserve the current pre-admission and final database/revision fences; do not accept expired claims, retroactively weaken committed revocations, or turn an already-admitted network request into a new unauthorized retry. Fail the migration if those semantics cannot be preserved. Any bounded authority expiry or pending-publication behavior needs an explicit product decision, not an implicit new guarantee in this issue.
Restored store identity/key/policy state must invalidate old work before native admission/replay; external automation remains paused until explicitly reactivated. Results accepted after recovery need an idempotent durable receipt/ACK contract, including crash-after-commit-before-ACK. Backlog pressure and evidence gaps must be visible. Execution continuity, PostgreSQL incident persistence and outbound notifications are three different promises; this candidate alone does not keep Bun-owned notifications sending during Bun absence. An optional worker outage must not make healthy Caddy readiness fail or broaden the root Caddy-progress health scope.
#398 remains a separate comparison. A dedicated Bun role would retain application logic but add process/RSS/connection cost and maintenance coordination. The current web-restart guard excludes every UID10002 writer before replacement, so simply launching a second application writer with that UID conflicts with the existing recovery proof. A new role needs explicit principal/file/API access, supervisor ownership and all-writer restore fencing. This issue selects neither a new mandatory process nor a multi-container service.
Implementation sequence and checkpoints
This is an acyclic sequence of evidence/contract checkpoints, not a requirement to finish all observability before any useful fix.
| Checkpoint | Prerequisites | Work / completion proof |
|---|---|---|
| D0 — owner/availability foundation | Delivered #392 and #403; this decision record | Retain actual 64/2 pipeline and eligible process boundary. Correct older issue baselines before experiments. |
| E1 — matched evidence slices | D0 | #396 owner status, #397 reproducible short background/SSR fixtures, #399 per-operation query/lock/CPU cost can proceed in parallel. Publish subsystem slices; no global framework dependency. |
| L1 — cancellation/maintenance contract | D0 plus each factory's current tests | #395 defines truthful start/stop/retry/cancel/timeout and intentional exclusions. Each domain can adopt the contract incrementally; root restore proof remains authoritative. |
| H1 — current-owner improvements | D0, relevant E1 slice and L1 contract where used | #393 fair delivery; #394 inventory-generation invalidation; scoped #399 query/retention fixes. Independent lanes do not wait for a speculative language migration or unrelated issue closure. |
| B1 — mixed resource policy | Relevant E1/H1 results and L1 | #400 composes global/per-class admission and reserves. Include diagnostic pools, ACME, DDNS, DB/cleanup and interactive management; test mixed starvation, not only isolated throughput. |
| A1 — optional ownership experiments | D0, matched optimized monitoring baseline, authority/product gates and relevant E1/DB findings | #402 evaluates native scheduling; #398 evaluates a Bun role independently. Either can conclude keep-hybrid. Unrelated notification/discovery closure is not a prerequisite. |
| M1 — any production migration | A1 demonstrates a declared benefit, security/restore/compatibility proof and explicit implementation scope | Separate authorized implementation issue/PR with upgrade/rollback, persisted formats, fault/lease/replay tests and measured resource envelope. No migration is hidden in #401. |
Product decisions explicitly still open
- Cadence and freshness: default interval 60s, validation 30–86,400s, timeout 1–10s. Decide the advertised supported combinations/load envelope and acceptable due/commit lag. Retain fixed requested cadence with skipped missed periods and visible overload; 1,000 policies is an admission cap, not every-configuration capacity.
- History at 1,000 policies: default 1,440 samples/policy and 7d age do not override the 100k global observation cap. At one observation/minute, 1,000 policies need 1.44M rows for one day; 100k is about 100 average samples/policy (~100min), not a fairness guarantee. perf(workers): measure remaining SQL, lock and history costs #399 must specify truthful retention/fairness and storage cost.
- Notification storm SLO: confirm healthy-channel latency, burst size/rate, per-owner fairness and treatment of excess admission. The table's 5s/30s targets are proposed fixture gates, not a current delivery guarantee. Receiver acceptance and exactly-once external delivery remain distinct.
- Component continuity: eligible web-only failure is supported as measured. Maintenance, root/host/volume loss, exhausted recovery, controller loss and PostgreSQL/Valkey/agent failure have different boundaries. Decide whether monitoring execution during management loss is a required feature, the permitted authorization freshness/authority lease, maximum retained outage and replay/evidence-gap behavior. Notification continuity requires its own owner design.
- Cold external integrations: external CrowdSec requires management credential replay, unlike the managed local engine. Preserve this limitation until a separately authorized safe persistence model changes it.
These questions gate their corresponding future changes; recording them is part of completing #401, not a claim that every product choice or later architecture experiment has been resolved.
Verification and source index
- Read-only audit of current native/app/root owners and relevant existing regressions, plus the published feat(monitoring): scale host checks with bounded batch processing #404 measurements and feat(runtime): isolate web faults and bound native recovery #405 current-tree CI evidence. No production data/credentials were accessed.
- Focused existing unit tests run in the immutable checkout: 24 passed, 107 assertions, across Foundation lifecycle, monitoring worker, notification worker and restore-maintenance fence. These exercise pending import/stop, bounded admission, late lease release, post-commit publication, notification cancellation and irreversible maintenance semantics. They are not a new capacity/A/B run.
- No production migration, new service, new dependency, repository documentation file or release-duration run is part of this deliverable.
Reproduce the focused unit invocation from the repository root:
bun --no-env-file test web/src/tests/server/Foundation/worker-lifecycle.test.ts web/src/tests/server/HostMonitoring/host-monitoring.worker.test.ts web/src/tests/server/Notifications/notification-worker.test.ts web/src/tests/server/Backups/restore-maintenance-fence.test.ts
Additional source/test anchors:
- Native execution and lifecycle: application startup/shutdown, admission defaults, Caddy recovery health, ownership regression, fault isolation regressions.
- Native certificates/DNS/discovery: ACME bounds, permission-recovery lock, DDNS recovery tests, discovery connector tests, diagnostic contention/interactive tests.
- Application transaction/cursor owners: monitoring transaction/retention, notification reauthorization/admission, certificate event receipts, backup commit-before-ACK.
- Maintenance/privilege boundary: root backup supervisor, exact retained-Caddy handoff, permanent restore fence, web root-progress reader.
- Intentionally distinct infrastructure: all Foundation registrations, watcher startup, per-client subscriptions, support size/allowlist, support permission/partial aggregation.
Acceptance checklist
- Every original inventory subsystem is classified, splitting mixed responsibilities, with actual scheduler/executor, desired/active/durable authority, credentials, recovery/restore and observability.
- Already-native work, Bun-delegated work, application execution and process availability are distinguished; existing good designs remain explicit.
- Conditional migration/improvement candidates name their baseline, benefit metric, resource/IPC/persistence/security cost and bounded proof.
- Numeric success/no-go gates are declared before future experiments; unknown, noisy or unsafe benefit does not justify migration.
- An acyclic evidence/contract/implementation sequence preserves current-owner improvements without a global framework prerequisite.
- Cadence/freshness, 1,000-policy history, storm SLO and component-continuity product questions remain explicitly recorded.
- Decision and evidence are recorded here; this investigation introduces no production migration or mandatory process.
Activity