Repository navigation
perf(postgres): add attributed PostgreSQL write profile and diagnostics - #218
Merged
Merged
Conversation
MisterVVP
marked this pull request as draft
August 17, 2026 06:13
MisterVVP
marked this pull request as ready for review
August 17, 2026 09:36
MisterVVP
added a commit
that referenced
this pull request
Aug 25, 2026
…ency (#219) ## Motivation Issue #206 identified PostgreSQL write saturation between concurrency 16 and 64 while connection-pool acquisition remained negligible. The goal of this PR is to remove measured SDK/SQL/schema overhead from the affected task and push write paths without weakening correctness, transaction safety, least-privilege behavior, or TCK compatibility. ## What changed ### PostgreSQL write-path diagnostics - Extends the focused `postgres-write` profile with PostgreSQL-side diagnostics for: - wait events; - WAL/database counters; - `MultiXactMember` / `MultiXactOffset` SLRU activity; - per-operation PostgreSQL phase latency and call counts. - Distinguishes optimistic `task_history_snapshot` reads from legacy `task_history_lock_read` attribution. - Keeps the focused profile at pool size 64 with c1/c4/c16/c64 and five repetitions. - Fixes the push-create warmup fixture so warmup and measured IDs cannot collide. - Keeps query-plan fixtures at the configured fan-out after `EXPLAIN ANALYZE` insert probes. ### Push-config create/delete coordination - Replaces task-row `FOR KEY SHARE` coordination with schema-scoped transaction advisory locks. - Push create/update takes the shared advisory lock; task deletion takes the matching exclusive advisory lock in a `BEFORE DELETE` trigger. - Advisory keys include the schema-qualified task-table identity plus the complete task ID, avoiding cross-schema interference. - Rejects local task-aware push creation under `REPEATABLE READ` / `SERIALIZABLE`, where a stale transaction snapshot could otherwise survive an advisory-lock wait. - Preserves least-privilege operation without requiring task-table `UPDATE`. - Hardens externally managed schema validation, including case-sensitive validation of the delete-lock key seed. ### Push write amplification - Removes the redundant push-config task secondary index. - Removes the remaining push ordering index after validating that list ordering still comes from explicit `ORDER BY created_sequence`. - Keeps the `(task_id, config_id)` primary key as the write/conflict index. - Updates managed-schema and manual-migration documentation accordingly. ### Task send path - Separates explicit task-ID resolution from authoritative task validation. - Reuses the already fetched task snapshot instead of performing redundant task-store reads. - Preserves context, terminal-state, and requested-task identity validation. - Updates lifecycle benchmarks to measure the extracted validation step rather than only the ID resolver. ### Optimistic task-history writes - Replaces transaction / `SELECT ... FOR UPDATE` history appends with bounded optimistic revision-checked updates. - Retries revision conflicts with a fixed upper bound instead of allowing an unbounded loop. - Includes `created_sequence` in the history CAS predicate to prevent delete/recreate ABA overwrites. - Adds deterministic concurrent-append and task-recreation coverage. - Preserves both concurrent messages and task metadata without holding a row lock across the append flow. ### Benchmark/API and local-build cleanup - Keeps `PushConfig_CreateMany` on the same public executor/service path used by production. - Removes the benchmark-only PostgreSQL batch API and its unused SQL builder rather than hardening an API with no production caller. - Removes benchmark/test-only shortcuts that would make before/after results incomparable. - Fixes the Windows local FetchContent example path/toolchain handling. - Updates storage and performance documentation to describe the final advisory-lock and optimistic-history designs. ## Performance comparison ### Sources Main-equivalent baseline: - PR #218 final CI: `32015617204` - PR #218 head: `d1e06d66934992e73745297e93f459c7bf41eb22` - merged `main`: `1f5ea572b7f3528ee638c5a371b83a59f5e97660` - baseline tree matches the merged-main tree used for the comparison. Final combined PR (#219 + #221): - CI: `32860693863` - head: `bc8e51fb59e8a56e9b1eceabda061dbdbeb4615a` - TCK: `32860693755` - CI and TCK both passed. The focused table below uses five-run medians from `postgres-write`, pool size 64. ### Focused c64 results | Scenario | Main c64 | Final PR c64 | Throughput vs main | c64 p95: main → PR | c64 p99: main → PR | c16→c64: main → PR | | --- | ---: | ---: | ---: | ---: | ---: | ---: | | `PushConfig_Create` | 4,817 ops/s | **5,356 ops/s** | **+11.2%** | 31.01 → **30.09 ms (-3.0%)** | 81.21 → 81.26 ms (+0.1%) | -24.9% → **-21.9%** | | `PushConfig_CreateMany` | 734 ops/s | **831 ops/s** | **+13.3%** | 129.03 → **115.33 ms (-10.6%)** | 167.74 → **141.35 ms (-15.7%)** | -13.5% → **-11.3%** | | `SendMessage_CreateTask` | 2,883 ops/s | **3,892 ops/s** | **+35.0%** | 53.07 → **39.19 ms (-26.1%)** | 74.76 → **54.59 ms (-27.0%)** | -3.4% → -6.4% | | `SendMessage_FollowUpExistingTask` | 2,202 ops/s | **2,878 ops/s** | **+30.7%** | 58.34 → **47.26 ms (-19.0%)** | 77.05 → **63.59 ms (-17.5%)** | -4.5% → **-2.4%** | The important change after folding #221 into #219 is that the previous follow-up-task regression is gone. All four focused c64 paths now have higher throughput than the main-equivalent baseline, and three of four also improve both p95 and p99. `SendMessage_CreateTask` now has substantially higher absolute throughput and materially lower tails at c64 even though its c16→c64 percentage is slightly worse because c16 improved even more strongly. ### Normal in-process PostgreSQL matrix Across c1/c4/c16/c64 in the normal CI matrix, geometric-mean movement versus the main-equivalent baseline is: | Scenario | Throughput geometric mean | p95 geometric mean | | --- | ---: | ---: | | `PushConfig_Create` | **+13.9%** | **-6.7%** | | `PushConfig_CreateMany` | **+22.6%** | **-46.2%** | | `SendMessage_CreateTask` | **+30.3%** | **-22.2%** | | `SendMessage_FollowUpExistingTask` | **+13.7%** | **-5.1%** | | `SendMessage_FollowUpAtHistoryDepth/8` | **+12.8%** | **-6.3%** | The normal matrix therefore supports the focused result: the final combined branch no longer has a follow-up-task throughput regression, while create-task remains the largest measured gain. ### Structural database evidence The final profile also shows that the intended work was removed from the hot paths: | Signal | Main | Final PR | | --- | ---: | ---: | | `SendMessage_CreateTask` task reads/op | 1 | **0** | | `SendMessage_FollowUpExistingTask` task reads/op | 2 | **1** | | Push-create MultiXact SLRU activity | row-lock path could generate MultiXact work | **0 across final focused push rows** | | c64 connection-acquire p95 | negligible | **still negligible (sub-µs on the focused write paths)** | The remaining high-concurrency drop is most visible in push-create, but the final profile still does not point to connection-pool starvation. Residual pressure is primarily PostgreSQL-side write/WAL/buffer contention rather than avoidable SDK connection waiting. ## Benchmark comparability note This PR fixes a correctness bug in the push benchmark fixture: warmup and measured push-create IDs previously overlapped, so the main-equivalent baseline could update warmup rows instead of measuring disjoint creates. Because of that: - task-path main-vs-PR absolute comparisons remain directly comparable; - push-path **c16→c64 scaling within each run** remains the strongest cross-version signal; - absolute push throughput/latency deltas against the old main artifact should still be treated as directional rather than a perfectly identical workload comparison. GitHub-hosted runner variability also means small single-digit movements should not be overinterpreted. The focused five-repetition medians are the stronger signal for this PR. --------- Co-authored-by: Vladimir Pavlov <[email protected]>
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Motivation
EXPLAIN (ANALYZE, BUFFERS, WAL)captures to determine whether contention, WAL/fsync pressure, index/plan issues, or transaction scope are the dominant cause.Description
postgres-writetoscripts/performance_runner.pythat runs the four write scenarios (SendMessage_CreateTask,SendMessage_FollowUpExistingTask,PushConfig_Create,PushConfig_CreateMany) at concurrency levels1,4,16,64with pool size64, using five repetitions and an isolated schema per scenario/coordinate/repetition to avoid data/lock cross-contamination.PostgresDiagnosticsCollectorwhich samplespg_stat_activity,pg_locks,pg_stat_database, andpg_stat_walwhile a scenario runs and records: active sessions, active writers, idle-in-transaction counts, wait-event samples, lock-mode samples, and before/after counters (transactions, tuples, block I/O, WAL bytes, WAL sync/write timings).EXPLAIN (ANALYZE, BUFFERS, WAL)probes for task and push upsert conflict paths inside a rolled-back transaction so captured plans and buffer/WAL metrics can be inspected without persisting probe rows..github/workflows/ci.yml) to run the profile and uploadperf-artifacts/postgres-writealongside existing tail profiles, and documents how to run and interpret the profile indocs/performance-testing.md(including theA2A_TEST_POSTGRES_DSNusage example).run_psql_jsonhelpers and thesubtract_postgres_countershelper and extends the runner to attach apostgres_database_diagnosticsobject to performance rows so results can be correlated with server-side signals.tests/scripts/performance_runner_test.py) validating the new profile matrix and the counter-delta logic, and updatestestsinvocations to exercise the changes.src/core/protojson.cpp(designated initializers) to satisfy lint checks without changing runtime behavior.