Repository navigation
driver/postgres: a statement that finishes quickly no longer arms the context watch - #1511
Merged
Merged
Conversation
…atched only once it waits (Refs #1501, #1447) A statement answered at once arms no watch; one that waits is watched; a cancel at any instant of a waiting statement ends the call within a bound and leaves the conn usable. The first test fails on this tree (every statement under a context that can end arms the watch); the other two pass on it and guard the guarantee while the watch is made lazy.
…s context only once it has waited past 2 ms (Refs #1501, #1447) A statement that gets its reply quickly no longer registers a context.AfterFunc or puts a deadline on the socket: the conn carries one rolling read deadline, refreshed when less than half of the bound is left, and a read that times out on it with the context alive arms the watch exactly as before. A context deadline inside the bound is put on the socket as it is; a cancel is noticed up to the bound after it lands, and a statement that finishes in that window returns its result. Every read deadline of a direct conn goes through three methods that keep the rolling-deadline flag true only while the socket carries the deadline. The tests that asserted how the watch is armed (at the start of every statement, the sequence of socket deadlines) now assert it for a statement that waits.
|
Caution Review failedThe pull request is closed.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
…the slow path, and a call with two slow rounds; two comments corrected (Refs #1501, #1447) The deadline test now uses a bound of 1.5 s with deadlines of 30 and 200 ms, for a timer context and a value context, and fails if the call ends later than the deadline. The two tests that cancel a waiting statement run the call in a goroutine with a 5 s limit, so a statement that is never woken fails where it stands. A new backend answers the extended protocol in rounds, and two new tests cancel, and end by a deadline, a call whose second round is slower than the bound. The comment on the Background case says what the check is (context.Background() itself), and the comment on the order of the deadline and the watch says why the order is kept. No change to the code.
FumingPower3925
marked this pull request as ready for review
December 1, 2026 20:25
This was referenced Dec 1, 2026
FumingPower3925
added a commit
that referenced
this pull request
Dec 2, 2026
…el test helper (Refs #1511)
FumingPower3925
added a commit
that referenced
this pull request
Dec 2, 2026
… and their fake backend routes a cancel like a real one (#1515) * tests: the postgres context-watch tests order their events by events, and their fake backend routes a cancel like a real one (Refs #1511, #1513) TestAStatementThatFinishesInsideTheBoundReturnsItsResult failed once on a CI runner: its first call dialled under a 5 ms timer, and the cancel landed during the dial. It now warms up the conn, cancels when the backend has the statement, and the backend answers only after the cancel. The fake backends give each conn a key of its own and route a CancelRequest by it: a cancel that reaches the backend before it has read the statement is no longer dropped, and a discarded conn can no longer take the next conn's cancel. Timers that ordered events are replaced by events (the backend's report, the arming of the watch, a held callback that signals it started); the tests that keep a timer, because the timer is what they are about, say so. Every helper that starts a statement goroutine joins it, so a failure cannot also produce a race report. Test files only. * tests: drop the embedded Conn from two selectors in the postgres cancel test helper (Refs #1511)
FumingPower3925
added a commit
that referenced
this pull request
Dec 2, 2026
…s when the kernel's send buffer is full, a Postgres call returns when its connection is clean, SocketBusyPoll as measured (#1516) Comments only. No code, test or exported-API change. - Config.WriteTimeout, the SSE package documentation, the WebSocket IdleTimeout documentation and the two engines' stall comments: the engine queues only the bytes the kernel's send buffer did not take, so the "no progress for WriteTimeout" clock starts when that buffer is full; the buffer grows up to net.ipv4.tcp_wmem's maximum and Config.SocketSendBuf fixes it. The wrong "(the write only queues the event in the engine)" is gone. On epoll only an acknowledgement restarts the clock; on io_uring a send completion that took bytes also does. - Config.SocketSendBuf and Config.SocketRecvBuf: the std engine ignores both. - Config.SocketBusyPoll: what measuring it on and off from one binary showed, and that busy polling spends CPU. - Pool, "Context": what a cancelled call waits for before it returns. - Context.Detach: the native engines' WriteTimeout bound on a detached connection. Refs #888, Refs #1511, Refs #1513
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.
Refs #1501, #1447
What changes and why
On a native Postgres connection in direct mode, every statement whose context can end used to register a
context.AfterFuncbefore it read the reply and stop it afterwards. That is what makes a call end when its context ends (#1447), and it costs about 0.8 us of CPU and four allocations (384 B) per statement on the driver-pg-read cell, the largest single piece of the gap to v1.5.11 (#1501).Now a statement that gets its reply quickly arms nothing. The connection carries one rolling read deadline (now plus 2 ms), refreshed only when less than half of it is left. A read that times out on it with the context still alive has waited past the bound: from there the statement is watched exactly as before (the same
AfterFunc, the same settle-before-drain order). A context deadline inside the bound is put on the socket as it is, so a deadline is not delayed.Every read deadline of a direct connection is now set through three methods that keep the rolling-deadline flag true only while the socket carries that deadline, and a test fails if any other call sets one.
What the caller sees
A cancel is noticed up to 2 ms after it lands, plus the platform's timer latency; a statement that finishes in that window returns its result; a deadline is not delayed.
The same text is in the Context section of the
Pooldocumentation. A statement that has waited longer than 2 ms ends as soon as its context does, as before.Release note: The native Postgres pool and database/sql connections in direct mode no longer arm a context watch for a statement that finishes quickly, which gives back most of the per-statement cost of ending a call when its context ends. A cancel is noticed up to 2 ms after it lands, plus the platform's timer latency; a statement that finishes in that window returns its result. A deadline is not delayed.
Cost, measured
Linux arm64 VM, Postgres 16 in a separate container (fsync off), one connection, one statement per iteration (
SELECT 1 FROM pg_sleep($1)) under a freshcontext.WithTimeout(5 s), three builds interleaved in rotating order, 12 rounds each, benchstat. "main" is main before this change. The CPU of the client process is within the run-to-run noise at every row (at the slow rows the spread is 33 to 70 % of a mostly idle process; on the quick statement it is 14.06 us here against 14.15 us on main).Wall time differs by less than the run-to-run spread at every row. The same run with a separate-process fake backend (3, 10 and 50 ms) gives the same picture.
The quick statement drops four allocations and 384 B. A statement that waits longer than 2 ms allocates ONE more object than main: the
net.OpErrorthat the standard library builds when the rolling read deadline fires (80 to 190 B per such statement). It cannot be avoided while the first wake of a waiting read is a read deadline, and it was accepted for the slow path.Cancel latency, and what is not ours
400 cancels at random instants of a statement that never answers, ten runs each, GOMAXPROCS 2, same VM, the cancel exchange included:
net.Connread with a 2 ms read deadline, no celeris code at all, three runs of 4000 reads: 9 reads returned more than 3 ms after the deadline, 2 more than 5 ms, the largest 31 ms (12000 reads). The program and its output are kept with the measurements.The tail comes from the timer wake of the platform (the VM here), not from the driver: a cancel inside the bound is noticed by a read deadline firing, and a read deadline fires late by the same amount for any program. Main has no such tail because its watch is woken by the cancel itself, not by a timer.
Tests
Eight tests asserted how the watch is armed rather than what a call returns, and change their expectation:
The 17 tests that pin the guarantee itself (cancel at each point of a statement, the 20,000-iteration stale-cancel loop, a deadline mid-statement, the foreign context deadline, the drain dropping rows, a deadline racing the end, a callback in flight when the drain begins, a completed request winning over an ended context, a cancel of a statement that answers on its own, an unconfirmed cancel replacing the conn, a timer context already past its deadline, a timer-context deadline racing the reply, the read deadline cleared at the end, and the COPY cancel tests) are unchanged.
Later commits add tests for what a first review asked: a deadline inside a bound of 1.5 s (deadlines of 30 and 200 ms) ends the call at the deadline, for a timer context and for a value context over one, and a deadline beyond a short bound does the same; the tests that cancel a waiting statement run the call with a 5 s limit, so a statement that is never woken fails where it stands; and a call with two rounds that are each slower than the bound (a write the connection prepares and then executes), cancelled or ended by a deadline during the second round, ends within the bound plus the timer's latency, and at the deadline, respectively.
New tests, in their own first commit where they could fail before the change: a quick statement arms no watch (fails before); a statement that waits is watched; a cancel at any instant of a waiting statement ends the call within a bound and leaves the conn usable. In the second commit: the rolling deadline does not survive a cancel drain, a COPY, or a statement under no context (the next statement is still cancellable); a cancel inside the bound is noticed when the bound ends; a statement that finishes inside it returns its result; a deadline is not delayed; a quick statement under one context sets the rolling deadline once; a statement shorter than half the bound is never watched; an idle conn serves any context after the rolling deadline expired; the bound is 2 ms (as documented); and a scan that no other read deadline is set.
Mutation check of the new flag (19 mutants, one per place the flag is read, written or set; each run against the cancel and timeout tests): 13 killed, 6 equivalent.
The new deadline test kills two further mutants (the exact socket deadline kept only for deadlines already past, and removed), and the hang mutant (no watch armed once the statement is past the bound) now fails the waiting-statement tests by the 5 s limit, not by go test's timeout.
What ran
go build ./...,go vetof the driver packages, gofmt: clean.go -C .github/tools run ./apidump: clean (api/ matches 53 packages)../driver/postgres/...: two findings, both in files this change does not touch (an unchecked channel receive in two older tests); none in the changed files.driver/postgreswith-race -count=1on macOS and on Linux (Docker, golang 1.27.4);internal/driver/postgreswith-race(its only package with tests is the protocol package).-race -count=20on macOS and Linux; the 20,000-iteration stale-cancel loop with-raceat count 20 on macOS and count 5 on Linux. The five tests that CI runs against a server under thepostgrestag indriver/postgres(streamed infinity, connector on a started engine) also pass.test/conformance/postgres,-race) against Postgres 16 with scram-sha-256 in Docker: default mode and the default-engine, default-engine-ready and epoll-ready modes. All passed (Postgres 16.16, one run each, no failure).The last commit changes tests and two comments only: the syntax tree of every non-test file of the package, comments dropped, is identical to the commit before it. Its tests were run with
-race -count=20and the package with-raceon Linux (Docker).Run separately on this head (Linux arm64 VM, Postgres 16, race and plain binaries, the native pool in direct mode and database/sql):
Pooltext above says "as soon as its context does"; it is corrected in a separate comment-only change.Not run here: the loop-path cells (they run in the release-candidate run on the cut commit), Windows, other Postgres versions.