mirror of
https://github.com/fosrl/pangolin.git
synced 2026-07-15 21:31:24 -05:00
Reference in New Issue
Block a user
Delete Branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
📋 Pull Request Information
Original PR: https://github.com/fosrl/pangolin/pull/3138
Author: @Josh-Voyles
Created: 5/23/2026
Status: ❌ Closed
Base:
dev← Head:mem-tune-2-oc📝 Commits (10+)
1cdd7dbremove mmap_size n cache_size - perf issues small instancesdaafccbfix: throttle expensive OLM ping operations to once per 5 minutes (#2120)7001ad8fix: add statusHistory table cleanup with 90-day retention (#2120)c561ba5fix: increase TraefikConfigManager default interval to 30s (#2120)f03d690fix: add TTL to Docker container cache entries (#2120)16bcc55fix: remove unnecessary autoFinalizeStatement wrapper (#2120)ab7c61cfix: restore immediate block enforcement on OLM ping path (#2120)1f8fddffix: select full client row for sendOlmSyncMessage (#2120)a248a21revert: per-ping block check on OLM ping path (#2120)07f7151feat: push-based OLM termination on block/delete (#2120)📊 Changes
9 files changed (+160 additions, -152 deletions)
View changed files
📝
server/db/sqlite/driver.ts(+2 -48)📝
server/lib/cleanupLogs.ts(+10 -3)📝
server/lib/readConfigFile.ts(+1 -1)📝
server/routers/client/blockClient.ts(+11 -7)📝
server/routers/client/deleteClient.ts(+15 -5)📝
server/routers/client/terminate.ts(+27 -1)📝
server/routers/newt/handleSocketMessages.ts(+5 -3)📝
server/routers/olm/deleteUserOlm.ts(+17 -7)📝
server/routers/olm/handleOlmPingMessage.ts(+72 -77)📄 Description
Community Contribution License Agreement
By creating this pull request, I grant the project maintainers an unlimited,
perpetual license to use, modify, and redistribute these contributions under any terms they
choose, including both the AGPLv3 and the Fossorial Commercial license terms. I
represent that I have the right to grant this license for all contributed content.
Summary
Fixes #2120 — rising memory floor and CPU spikes that cause Uptime Kuma timeouts and OOM container kills on small instances. Touches the OLM ping hot
path, audit/status log retention, Docker socket cache, Traefik config rebuild cadence, and SQLite driver setup. After this PR the same workload runs
cleanly on a 1 GB instance.
AI Disclosure
This PR was developed with AI assistance. Models used during exploration and implementation: Claude Opus 4.6 and Claude Opus 4.7. Three
different agentic environments were tried — Zed editor (Zed Agent), OpenCode, and Claude Code — with the best results coming from Claude
Code. All changes were reviewed, tested, and validated against a real production workload before merging (see Test Environment).
Test Environment
t3a.micro(2 vCPU burstable, 1 GB RAM)Changes
1. Throttle expensive OLM ping operations (
daafccb1) — biggest impactFile:
server/routers/olm/handleOlmPingMessage.tsBefore, every OLM ping ran 5–10 DB operations: full client SELECT, session validation, organization access policy check, config version lookup, and
fingerprint insertion. Under sustained Uptime Kuma probing this was the dominant source of CPU + SQLite contention.
Now the expensive checks run at most once every 5 minutes per OLM. Pings between checks only run the cheap in-memory
recordClientPing(), which isthen batch-flushed by the existing ping accumulator. This was the single biggest performance win in the PR.
Known behavioral side-effects. Admin actions (block / delete / unlink) are made immediate via change #2 below. The following state changes are
not push-mitigated and lag by up to ~5 minutes — by design:
invalidateSession()— OLM keeps tunneling for up to ~7 minutes after the session is invalid (5 min until slow-pathdetection + ~2 min offline-checker grace).
client.userIdmismatch (edge case: client reassigned to a different user) — same lag.incrementConfigVersion: true. Only the ping-side fallback (for missed pushes) is delayed.Other behavior changes worth noting:
lastFullCheckMap has no eviction-on-disconnect. ~50 bytes per unique OLM, negligible for typical deployments but technically unbounded over theprocess lifetime. (Eviction was implemented in a follow-up but was bundled with the reverted commit — see Reverted section.)
lastFullCheckMap.handleFingerprintInsertion()errors are now caught and logged rather than propagated. Stability improvement; behavior change.FULL_CHECK_INTERVAL_MS = 5 * 60 * 1000is hard-coded — not configurable.Mitigation paths for deployments that need stricter enforcement:
disconnectClient(olmId)from your session-invalidation / org-removal paths (deferred follow-up — seeterminateAndDisconnect()inserver/routers/client/terminate.tsfor the pattern).FULL_CHECK_INTERVAL_MSinhandleOlmPingMessage.ts, accepting some CPU/memory cost back.2. Push-based OLM termination on block/delete (
07f7151b)Files:
server/routers/client/terminate.ts,blockClient.ts,deleteClient.ts,server/routers/olm/deleteUserOlm.tsThe throttle in change #1 introduced a side-effect: admin actions like blocking or deleting a client took up to ~7 minutes to take effect (5 min
until the next slow-path check + 2 min offline-checker grace). Previously the offline checker handled this via
lastPingnot being updated, but withthe throttle that mechanism no longer fired on the fast path.
Instead of putting per-ping checks back (see Reverted section), we now push termination from the endpoints that mutate auth state. A new
terminateAndDisconnect(clientId, error, olmId)helper sends the existingolm/terminatemessage, waits 1 second, then force-closes the WebSocket —mirroring the pattern already used by
server/routers/olm/offlineChecker.ts. Wired intoblockClient,deleteClient, anddeleteUserOlm.Termination is moved outside the DB transaction so the 1-second sleep doesn't hold the SQLite write lock.
Admin actions now take effect immediately, with zero per-ping cost.
3. Add
statusHistorytable cleanup (7001ad8f)File:
server/lib/cleanupLogs.tsThe
statusHistorytable had no cleanup mechanism and grew without bound, which is one of the contributors to the rising-floor memory pattern. Addeda 90-day retention sweep to the existing 3-hour cleanup interval.
4. Increase TraefikConfigManager default interval 5s → 30s (
c561ba51)File:
server/lib/readConfigFile.tsEach Traefik config rebuild allocates 3–6 MB of temporary objects. At a 5-second interval on a small instance that's significant GC churn for a
config that changes rarely. Default raised to 30s. Existing deployments with
monitor_intervalset explicitly are unaffected.5. Add TTL to Docker container/socket cache entries (
f03d690f)File:
server/routers/newt/handleSocketMessages.tscache.set(..., 0)forsocketPath,isAvailable, anddockerContainersmeant entries never expired and accumulated permanently as newts churned.Changed TTL to 300s (5 minutes). The cache is repopulated on demand when the UI fetches container info.
6. Remove
autoFinalizeStatementwrapper (16bcc552)File:
server/db/sqlite/driver.tsThe wrapper was added to deterministically finalize prepared statements after each
.run() / .get() / .all(), on the assumption thatbetter-sqlite3was leaking statements. Investigation showed the assumption is wrong:better-sqlite3'sStatement::~Statement()destructor callssqlite3_finalize()when the JS wrapper is garbage-collected (see C++ source). The wrapper added per-query overhead, and itsfinalize-after-first-execution behavior would have silently broken any reusable prepared statement.
7. Remove
mmap_sizeandcache_sizepragmas (1cdd7dba)File:
server/db/sqlite/driver.tsBoth pragmas were causing performance issues on small instances and were removed.
Reverted changes
We tried one approach that had to be reverted. Documenting it because the original reasoning was sound and someone may be tempted to retry.
Reverted: per-ping fast-path block check (
ab7c61c4+1f8fddf8, reverted ina248a211)Why we tried it: the throttle in change #1 delayed admin block enforcement by up to 5 minutes. The original commit added a cheap PK
SELECTonclientsto every ping so blocked clients would be caught immediately by the offline checker — adding back ~1 DB op per ping in exchange for a5-minute → 2-minute enforcement window. Query-count math said this was still ~85% below the leaking pre-PR baseline, and the SELECT was projected to
just 4 columns.
Why we reverted: the query-count math missed the actual leak vector. With the
autoFinalizewrapper removed (change #6), each per-ping ad-hocquery allocates a native
sqlite3_stmtthat only releases on V8 GC. Drizzle doesn't cache statements automatically. On a 1 GB instance undersustained ping load, GC fell behind native allocation, off-heap RSS climbed, and the symptoms reappeared (Uptime Kuma timeouts, OOM kills) within
hours of deploying.
The proper fix turned out to be push-based termination (change #2), which has zero per-ping cost and gives faster enforcement than the per-ping check
would have.
Lesson: in this codebase, any per-ping ad-hoc DB query in the OLM ping path is suspect on small instances. If per-ping checks are ever genuinely
needed, they must use explicitly cached prepared statements (
drizzle.prepare()) or in-memory state with explicit invalidation — not ad-hoc queries.Operational notes
WAL mode and HTTPS Request Log Retention
WAL mode is opt-in via
ENABLE_SQLITE_WAL_MODE=true(seec8e7e0ee).Empirically:
forced restarts on small instances.
Recommendation for ≤ 1 GB deployments: if you want HTTPS request log retention turned on, set
ENABLE_SQLITE_WAL_MODE=true. With request loggingoff, the default (WAL off) is fine.
WAL remains opt-in rather than default because the disable in
c8e7e0eewas deliberate — see that commit for the rationale.Test plan
statusHistoryretention sweep runs without errorst3a.micro(verified 1466+ min)ENABLE_SQLITE_WAL_MODE=true🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.