You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
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.
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.
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: 4
Check name
Status
Explanation
Title check
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
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Description check
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
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this 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.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
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:
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
Measurement invocations, after preparing the uniquely disposable fixture:
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
Checklist
Breaking changes
None. A vanished or malformed locking-read result fails closed instead of becoming an unlocked default.