Skip to content

perf(workers): reduce PostgreSQL coordination round trips - #429

Merged
RentnerKev merged 3 commits into
mainfrom
rentner/perf-worker-postgres-426
Nov 12, 2026
Merged

RentnerKev merged 3 commits into
mainfrom
rentner/perf-worker-postgres-426

Conversation

@RentnerKev

@RentnerKev RentnerKev commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Summary

Reduce measured PostgreSQL coordination round trips while keeping Bun/Drizzle as the sole application database authority.

Per-policy observation and incident retention now execute as two capped logical DELETEs in one SQL command. The current tables/predicates are independent, so the shared command snapshot preserves the intended decisions; this is not a general sequential-snapshot guarantee. Both 4,096-row limits, open incidents, policy scope and per-result savepoint rollback remain intact.

Existing notification setting rows now need one locking read instead of a no-op INSERT followed by a locking read. Missing rows still use conflict-safe initialization and a separate fresh SELECT FOR UPDATE. Configuration-before-runtime lock order and full schema validation remain unchanged.

Related issue

Refs #426, item 3, and #399. Full-snapshot hydration and whole-state JSONB remain measured follow-up costs; this PR does not replace the ORM, add a cache authority, normalize the queue or close that broader issue automatically.

Measured result

Matched actual production Bun/Drizzle operations used Bun 1.4.4 and disposable PostgreSQL 18.6 with 1,000 policies, 100,000 observations and a saturated notification fixture:

Operation Baseline SQL command round trips Candidate
Complete 16 monitoring results 193 177
Claim notification 13 11
Acknowledge notification 8 6

The retention operation still performs two logical DELETEs. Monitoring hydration remains approximately 87,390 bytes per preflight and 91,360 per completion batch; notification reads remain approximately 230 KB and JSONB update parameters approximately 212 KB. No CPU, physical-JSONB/WAL, RAM or sustained-capacity reduction is claimed. Wall-time results were noisy.

Disposition of the named costs: the full desired-state snapshot remains because it supplies the global desired revision; projecting only selected hosts would weaken the fence against unrelated configuration changes. Retention keeps both logical DELETEs and their independent limits while reducing command coordination. Whole-document notification JSONB writes remain: the tested nested patch increased PostgreSQL execution cost and was rejected. This completes a measured, selective optimization pass with invariants preserved; broader projection/CPU/lock/write-amplification investigation remains in #399.

Baseline was recorded before production edits against main 8ac0e3c. Source-sealed comparisons pin the helper and five measured module hashes, checking inputs before/after execution; the changed module hashes match the committed candidate inputs at 9f01b7c. Experimental retention query reshaping and nested JSONB patches were discarded because they did not demonstrate a justified net benefit.

Retained ignored evidence:

  • Helper SHA256: 057BC6E5FD320155FA9C5221560F028920682532E7DDDC56CDB77AABDCE812FC.
  • Sealed baseline report SHA256: A084614DC7B58AE48885F0C2BE366F62D82A3D7EC9F274AF70A1EC16C18341F2.
  • Sealed candidate report SHA256: 93D1DB2F4297E964396C2559DB436370DCF0C1763FE397824C5069A6717674D3.

The loopback wire observer counted actual command/returned-field/parameter bytes, alongside pg_stat_statements. Lock windows span successful acquisition response through commit response and include serving/transport time; they are not pure lock-wait/hold or isolated CPU measurements. No external notification transport was invoked.

Testing

  • 66 real PostgreSQL tests / 666 assertions passed: actual lock-wait synchronization, concurrent absent-row initialization with committed and rolled-back winners, fresh locked state, malformed-state rejection, observation-only/incident-only pruning, independent per-table caps and actual retention rollback at the final lease fence.
  • 56 affected unit tests passed.
  • bun --no-env-file run typecheck.
  • Focused standard/type-aware lint and diff whitespace checks passed.
  • Independent database/concurrency review found no actionable issue.
  • Repeated heavy fixture loads briefly reached the unchanged global-retention transaction timeout. After vacuuming only the disposable fixture, the focused suite passed serially; no timeout or assertion was weakened.

Measurement invocations, after preparing the uniquely disposable fixture:

bun --no-env-file core/target/sql-baseline.ts baseline-sealed <unchanged-main-8ac0e3ca-checkout>
bun --no-env-file core/target/sql-baseline.ts candidate-sealed

The helper/reports remain ignored local measurement evidence. The owned database container/volume and wire observer were removed after verification; existing user services were untouched.

Type of change

  • Refactoring
  • Other: measured SQL coordination efficiency

Checklist

  • Token, lease, revision, cursor, audit, outbox, rollback and retention guarantees preserved.
  • No schema/migration, Rust database layer, new service or unproven cache introduced.
  • No production data, secrets, documentation files or screenshots added.
  • Related issues linked.

Breaking changes

None. A vanished or malformed locking-read result fails closed instead of becoming an unlocked default.

@coderabbitai

coderabbitai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Host-monitoring pruning now deletes observations and incidents in one SQL command. Notification setting reads now select before initialization. Database tests cover retention limits, lease-expiry behavior, concurrent setting reads, initialization rollback, and malformed runtime data.

Changes: Host-monitoring history retention

Layer / File(s) Summary
Combined retention pruning and database coverage
web/src/server/HostMonitoring/host-monitoring.storage.ts, web/src/tests/server/HostMonitoring/host-monitoring.repository.db.test.ts
Observation deletion now uses a data-modifying CTE referenced by the incident deletion. Tests cover deletion limits, pruning when only one history table has expired rows, and preservation of existing rows when the lease-expiry fence rejects completion.

Notification setting reads

Layer / File(s) Summary
Read and initialize settings under lock
web/src/server/Notifications/notification-storage.ts, web/src/tests/server/Notifications/notification-repository.db.test.ts
readSetting selects before initializing. An unlocked miss returns a clone of the initial value without writing; a locked miss inserts, re-reads under lock, and throws configuration_unavailable if the row is absent. Tests cover lock waiting, rollback, concurrent initialization, and malformed runtime data.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Refactor

Possibly related issues

  • Issue 399 — The PR changes retention SQL and notification-setting locking, which are among the SQL paths described in the issue.
  • Issue 426 — The PR changes retention deletion and notification-setting locking, which overlap with the issue’s listed SQL hot-path work.

Possibly related PRs

Suggested labels: area: database

Merge Risk: Minimal · up to 38e3a

The change reduces database round trips for host-monitoring pruning and notification setting reads, and adds database tests for the retention limits and locking behavior. No actionable merge-blocking risk was identified.

Security architecture risk: Minimal · up to 38e3a

The inspected changes preserve policy-scoped retention, open incidents, transaction rollback, settings validation and notification lock ordering. No material security risk was found introduced or worsened by this PR.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The changed retention operation remains bounded to one admitted policy and at most 4,096 deletions from each history table per invocation. Notification reads affect shared configuration and runtime rows, so their coordination scope is service-wide rather than policy-local; the PR does not expand that existing scope.

Trust Boundaries and Controls

  • observed — Inspected notification mutation callers continue to lock configuration before runtime. Delivery authorization separately rechecks the live delivery lease, channel revision and ownership, resource access, and applicable owner permissions before transport. These existing controls are not replaced by the optimized settings read.

Resilience and Maintainability Implications

  • inferred — The settings transition preserves failure containment: conflicting initializers converge through the unique key and locking reread, transaction failure rolls back initialization, and malformed or unexpectedly absent locked state is rejected rather than silently replaced with defaults. Monitoring repetition remains subject to the existing version, token and expiry fences.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "perf(workers): reduce PostgreSQL coordination round trips" matches the main change. The PR combines two SQL statements for retention pruning and uses one locking read for existing notificat…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description follows the repository template. It has a summary, measured results, testing, checklist, and breaking-changes sections. It also links issues (Refs #426, #399) instead of using the requ…
Full details: Title check

Explanation

The title "perf(workers): reduce PostgreSQL coordination round trips" matches the main change. The PR combines two SQL statements for retention pruning and uses one locking read for existing notification settings rows, which reduces command round trips. The title is specific and conventional, and it follows the stated objective of the PR.

Full details: Description check

Explanation

The description follows the repository template. It has a summary, measured results, testing, checklist, and breaking-changes sections. It also links issues (Refs #426, #399) instead of using the required Fixes/Closes form. The 'Type of change' section marks Refactoring and Other, and the checklist is ticked. The description also states that the PR does not close the broader issue, which fits 'Refs' linking. The main gaps are the issue-link format, which the template asks to be Fixes/Closes for feature and fix PRs, and the Testing section, which lists measurement commands with placeholders but no explicit pass/fail commands beyond the summaries. Overall the description is mostly complete.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 4294bf8 and 38e3afc.

Files selected for processing: 4

  • web/src/server/HostMonitoring/host-monitoring.storage.ts
  • web/src/server/Notifications/notification-storage.ts
  • web/src/tests/server/HostMonitoring/host-monitoring.repository.db.test.ts
  • web/src/tests/server/Notifications/notification-repository.db.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.

@RentnerKev

Copy link
Copy Markdown
Member Author

@coderabbitai review

The repository automation merged current main into this branch (38e3afc). The two production SQL sources are unchanged from the already-reviewed head; the new merge adds the separately reviewed backup identity fix from #427. Please confirm the current PR head as well before the requested merge.

@coderabbitai

coderabbitai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor
Action not completed

Already reviewed the last commit. Use @coderabbitai full review to rerun a review of the entire changeset.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@RentnerKev

Copy link
Copy Markdown
Member Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor
Action performed

Full review finished.

@RentnerKev
RentnerKev merged commit 40797fd into main Nov 12, 2026
49 checks passed
@RentnerKev
RentnerKev deleted the rentner/perf-worker-postgres-426 branch November 12, 2026 19:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant