Skip to content

perf(postgres): add attributed PostgreSQL write profile and diagnostics - #218

Merged
MisterVVP merged 2 commits into
mainfrom
dev-investigate-postgresql-write-saturation
Aug 17, 2026
Merged

MisterVVP merged 2 commits into
mainfrom
dev-investigate-postgresql-write-saturation

Conversation

@MisterVVP

@MisterVVP MisterVVP commented Aug 17, 2026 •

Copy link
Copy Markdown
Owner

Motivation

  • Reproduce and attribute the observed c16→c64 PostgreSQL write-saturation for task and push write paths without changing production SDK/SQL/schema behavior first.
  • Provide machine-readable database-side diagnostics (wait events, lock counts, WAL and buffer deltas, session activity) and representative EXPLAIN (ANALYZE, BUFFERS, WAL) captures to determine whether contention, WAL/fsync pressure, index/plan issues, or transaction scope are the dominant cause.

Description

  • Adds a new focused profile postgres-write to scripts/performance_runner.py that runs the four write scenarios (SendMessage_CreateTask, SendMessage_FollowUpExistingTask, PushConfig_Create, PushConfig_CreateMany) at concurrency levels 1,4,16,64 with pool size 64, using five repetitions and an isolated schema per scenario/coordinate/repetition to avoid data/lock cross-contamination.
  • Implements PostgresDiagnosticsCollector which samples pg_stat_activity, pg_locks, pg_stat_database, and pg_stat_wal while 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).
  • Adds representative 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.
  • Integrates the profile into CI (.github/workflows/ci.yml) to run the profile and upload perf-artifacts/postgres-write alongside existing tail profiles, and documents how to run and interpret the profile in docs/performance-testing.md (including the A2A_TEST_POSTGRES_DSN usage example).
  • Adds run_psql_json helpers and the subtract_postgres_counters helper and extends the runner to attach a postgres_database_diagnostics object to performance rows so results can be correlated with server-side signals.
  • Adds runner tests (tests/scripts/performance_runner_test.py) validating the new profile matrix and the counter-delta logic, and updates tests invocations to exercise the changes.
  • Applies a targeted clang-tidy-compatible initializer fix in src/core/protojson.cpp (designated initializers) to satisfy lint checks without changing runtime behavior.

@MisterVVP MisterVVP added the codex Automatic label added by codex agent. Should not be used label Aug 17, 2026 — with ChatGPT Codex Connector
@MisterVVP
MisterVVP marked this pull request as draft August 17, 2026 06:13
@MisterVVP MisterVVP self-assigned this Aug 17, 2026
@MisterVVP MisterVVP added AI agent AI agent contribution performance Performance improvement related tasks based on benchmark results. Performance tests changes. maintenance and removed codex Automatic label added by codex agent. Should not be used labels Aug 17, 2026
@MisterVVP
MisterVVP marked this pull request as ready for review August 17, 2026 09:36
@MisterVVP MisterVVP removed the performance Performance improvement related tasks based on benchmark results. Performance tests changes. label Aug 17, 2026
@MisterVVP
MisterVVP merged commit 1f5ea57 into main Aug 17, 2026
19 checks passed
@MisterVVP
MisterVVP deleted the dev-investigate-postgresql-write-saturation branch August 17, 2026 09:55
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

AI agent AI agent contribution maintenance

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant