skaidb 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f947092b55d66cc8d7c55153cbea09ebcdd0298f48fcb6c97ea0f3a5edd5ac01
4
- data.tar.gz: 9b472d16803f161f2aa6d4554c19aede65f9a227b79d29c7f015204c04a7bcc7
3
+ metadata.gz: c1684623cac79f6c62a066686a0a6f6af3af9141a7434eb4b3a297a7c0d4d9f1
4
+ data.tar.gz: 62a78c8e58e4ce110e2ae3ce52ccc2dd246bb9481aeee68d80292b46e17c2d2f
5
5
  SHA512:
6
- metadata.gz: 68d82f58f409113c18f1536023042343ffbfa86c8ec6029a0f799cd8f88fd038f418ced9c1be77beca7826c7d5756e523de221c6bf798e7069db1e14be7aaf12
7
- data.tar.gz: f95915e0918b17e31d2b9e63cfbcbe92ee717f07b49075bbd1da055cb49f60f592c346eb579b6c65a8dc855ddf669c41d467086dec90ccb59abc0861c784dacc
6
+ metadata.gz: c85ce23da9ad6e8fb7a372190ace6ef40226319fa601ecbbc2477d891a272a1303b919494d2b10f98aae441c0583802b2ce729c381b000da021bbdef12933f5d
7
+ data.tar.gz: 82d387c4e1ce106331ac57dc8cf20225018f8fa491fc73ab8954062eb3624d3b191882b32ca801cdc7edbffd2922990bebbd83050e2ee8cceef24a6712491046
data/CHANGELOG.md CHANGED
@@ -4,6 +4,80 @@ All notable changes to the skaidb Ruby driver. The format follows
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow
5
5
  [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## [1.5.0] - 2026-11-15
8
+
9
+ ### Added
10
+ - **`Skaidb::TransactionConflict`**, a `QueryError` raised for a server
11
+ error whose message starts with `transaction conflict:` — what a
12
+ standalone server (≥ 0.346) answers a `COMMIT` with when another writer
13
+ changed a row the transaction writes after its `BEGIN`. Nothing was
14
+ applied, the transaction is over and the connection stays usable; the
15
+ message is the server's, unchanged. Every call that runs a statement
16
+ raises it (`exec`, `exec_params`, `exec_prepared`, `exec_batch`,
17
+ `stream`), and `rescue Skaidb::QueryError` catches it as before. It is a
18
+ statement error: it does not count against a pool member's health, close
19
+ the connection or cause a re-dial.
20
+ - **`conn.transaction(attempts: 3, begin: "BEGIN") { |conn| … }`** sends
21
+ `begin`, runs the block, sends `COMMIT` and returns the block's value. A
22
+ `COMMIT` refused with `TransactionConflict` runs the whole transaction
23
+ again from `begin` — up to `attempts` runs in all, with no pause between
24
+ them — so the block must be safe to run more than once; the conflict of
25
+ the last attempt is raised. A refused `begin` is raised without running
26
+ the block or sending anything else. A block that does not run to its end
27
+ (an exception, `break`, `throw`) is rolled back and never retried, and
28
+ what the `ROLLBACK` answers never replaces the block's exception. Any
29
+ other `COMMIT` error is raised with no retry and no `ROLLBACK`. `begin:`
30
+ is the opening statement, sent as given (`BEGIN ATOMIC` or
31
+ `BEGIN ATOMIC PARTITION (col = lit)` on a cluster). `attempts` below 1,
32
+ or no block, raises `ArgumentError` before anything is sent.
33
+ - Inside `transaction` a connection that loses its transport does not
34
+ re-dial: the `ConnectionError` is not retried, no `ROLLBACK` is sent to a
35
+ new session, and a statement the block still runs after rescuing the
36
+ failure raises `ConnectionError` instead of being committed on its own
37
+ there. The first statement after `transaction` returns re-dials as always.
38
+ - **`pool.transaction(attempts: 3, begin: "BEGIN", affinity: nil) { |conn| … }`**:
39
+ the same helper on one checked-out connection, held for every attempt and
40
+ returned afterwards.
41
+
42
+ ### Fixed
43
+ - A statement cut short between its request and its reply by something
44
+ other than a transport error — `Timeout.timeout`, an `Interrupt`,
45
+ `Thread#kill` — left the reply on the socket with `usable?` still `true`,
46
+ and the next statement on that connection read it as its own: a
47
+ `SELECT 1` returned the rows of the statement that had timed out. The
48
+ connection is now marked broken at that point, so `usable?` is `false`, a
49
+ pool closes it on check-in and the next statement re-dials. `exec`,
50
+ `exec_params`, `exec_batch` and the first frame of a `stream` are covered.
51
+ `transaction` relies on it: a block cut short that way is not followed by
52
+ a `ROLLBACK` that would wait for the outstanding reply.
53
+ - A broken connection is re-dialled by whichever statement comes next. A
54
+ parameterised statement the connection had already prepared
55
+ (`exec_params`, `exec_batch`) took its id from the cache before that
56
+ check and sent it down the old socket, so a connection that ran only
57
+ such statements raised `ConnectionError` on every call after a transport
58
+ failure and never recovered. The cache is now read after the re-dial,
59
+ which empties it. `exec_prepared` with an id from before the failure
60
+ raises `ConnectionError` (`connection is broken; prepare the statement
61
+ again`).
62
+
63
+ ## [1.4.1] - 2026-10-31
64
+
65
+ ### Fixed
66
+ - One slow round trip at the start can no longer get a healthy member
67
+ ejected for latency. A member's first round trip set its average
68
+ outright, so a statement that stalled in the client — a CPU-bound
69
+ application holding the thread while it starts — put seconds into it;
70
+ ten round trips later the member was compared with the others, and the
71
+ average had barely decayed: ejected (`latency 4153.7 ms vs median
72
+ 0.2 ms`) while it answered in milliseconds. The fastest of a member's
73
+ first three round trips now seeds its average (a round trip is only ever
74
+ lengthened), and later ones move it as before; until then the member
75
+ counts as not measured, and `pool.members` reports its `latency_ms` as
76
+ `nil`.
77
+ - A latency ejection's `logger` warning names the slowest of the member's
78
+ last 10 round trips alongside its average and the median, which tells a
79
+ slow member from one slow statement.
80
+
7
81
  ## [1.4.0] - 2026-10-29
8
82
 
9
83
  ### Fixed
@@ -206,6 +280,9 @@ batches, a 2 500-row stream, error handling, and the `drivers` table showing
206
280
  because it is a bundled gem since Ruby 3.4.
207
281
  - The example moved to `examples/basic.rb`.
208
282
 
283
+ [1.5.0]: https://github.com/porcupin26/skaidb-ruby/compare/v1.4.1...v1.5.0
284
+ [1.4.1]: https://github.com/porcupin26/skaidb-ruby/compare/v1.4.0...v1.4.1
285
+ [1.4.0]: https://github.com/porcupin26/skaidb-ruby/compare/v1.3.0...v1.4.0
209
286
  [1.3.0]: https://github.com/porcupin26/skaidb-ruby/compare/v1.2.0...v1.3.0
210
287
  [1.2.0]: https://github.com/porcupin26/skaidb-ruby/compare/v1.1.0...v1.2.0
211
288
  [1.1.0]: https://github.com/porcupin26/skaidb-ruby/compare/v1.0.3...v1.1.0
data/README.md CHANGED
@@ -12,9 +12,9 @@ and the result behaves like `PG::Result`. **Pure standard library** (`socket`,
12
12
  `openssl`, `securerandom`, `bigdecimal`) — no third-party code, one file,
13
13
  Ruby 2.7 through 3.4. It speaks skaidb's binary protocol directly:
14
14
  SCRAM-SHA-256 authentication, server-side prepared statements with typed
15
- parameters, one-round-trip batches, streamed result sets, multi-seed failover,
16
- transparent reconnect, TLS and a connection pool that balances across the
17
- cluster's members.
15
+ parameters, one-round-trip batches, streamed result sets, a retrying
16
+ transaction helper, multi-seed failover, transparent reconnect, TLS and a
17
+ connection pool that balances across the cluster's members.
18
18
 
19
19
  - Repository: <https://github.com/porcupin26/skaidb-ruby>
20
20
  - RubyGems: <https://rubygems.org/gems/skaidb>
@@ -55,13 +55,13 @@ Xcode command-line tools on macOS). `gem install skaidb` and vendoring reuse
55
55
  the `bigdecimal` already installed.
56
56
 
57
57
  Or vendor the single file: copy
58
- [`lib/skaidb.rb`](https://github.com/porcupin26/skaidb-ruby/blob/v1.4.0/lib/skaidb.rb)
58
+ [`lib/skaidb.rb`](https://github.com/porcupin26/skaidb-ruby/blob/v1.5.0/lib/skaidb.rb)
59
59
  into your project and `require_relative` it. It has no dependencies beyond
60
60
  Ruby's standard library.
61
61
 
62
62
  Every release is also attached as a `.gem` to its
63
63
  [GitHub release](https://github.com/porcupin26/skaidb-ruby/releases) for
64
- installs without registry access: `gem install ./skaidb-1.4.0.gem`.
64
+ installs without registry access: `gem install ./skaidb-1.5.0.gem`.
65
65
 
66
66
  ## Quick start
67
67
 
@@ -104,7 +104,8 @@ end
104
104
  - [Streams (`CREATE STREAM`)](#streams-create-stream) — `subscribe`
105
105
  - [Type mapping](#type-mapping)
106
106
  - [Errors](#errors)
107
- - [Transactions](#transactions)
107
+ - [Transactions](#transactions) — `transaction`, `TransactionConflict`,
108
+ hand-written `BEGIN`/`COMMIT`
108
109
  - [Thread safety](#thread-safety)
109
110
  - [Client identification and version](#client-identification-and-version)
110
111
  - [Compatibility](#compatibility)
@@ -155,7 +156,9 @@ through.
155
156
  `timeout` bounds the TCP dial only. Reads have no deadline: a peer that is
156
157
  alive but silent blocks the caller, as in ruby-pg. `close` deliberately does
157
158
  not take the connection's lock, so another thread can break a stuck read by
158
- closing the connection.
159
+ closing the connection. A statement cut short while its reply is outstanding
160
+ — by `Timeout.timeout`, an `Interrupt`, `Thread#kill` — leaves the connection
161
+ marked broken, so the next statement re-dials instead of reading that reply.
159
162
 
160
163
  ### TLS
161
164
 
@@ -202,8 +205,8 @@ the server regardless of this setting.
202
205
  ### Health
203
206
 
204
207
  - `conn.usable?` — no round-trip. `true` unless the connection is closed, was
205
- left out of sync by a transport error or an undrainable abandoned stream, or
206
- is currently mid-stream.
208
+ left out of sync by a transport error, a round trip cut short or an
209
+ undrainable abandoned stream, or is currently mid-stream.
207
210
  - `conn.closed` / `conn.finished?` — `true` after `close`.
208
211
 
209
212
  ## Statements and parameters
@@ -359,8 +362,11 @@ pool.members # => [{ endpoint: "db1:7000", canonical: "10.0.0.1:7000", state: :r
359
362
 
360
363
  A member with consecutive transport failures, or a round-trip average far
361
364
  above the others', is ejected and re-admitted by a background probe (the last
362
- usable member never is); `idle_order: :fifo` keeps every idle connection in
363
- use. Details: [docs/pooling.md](https://github.com/porcupin26/skaidb-ruby/blob/main/docs/pooling.md).
365
+ usable member never is). The fastest of a member's first three round trips
366
+ seeds its average, so a statement that stalls in your own process cannot get
367
+ a healthy member ejected; a latency ejection's `logger:` warning names the
368
+ average, the median and the slowest of the member's last 10 round trips.
369
+ `idle_order: :fifo` keeps every idle connection in use. Details: [docs/pooling.md](https://github.com/porcupin26/skaidb-ruby/blob/main/docs/pooling.md).
364
370
 
365
371
  ## Streams (`CREATE STREAM`)
366
372
 
@@ -426,24 +432,113 @@ StandardError
426
432
  └── Skaidb::Error # also: invalid consistency, pool closed
427
433
  ├── Skaidb::ConnectionError # dial/auth/transport failures, framing, closed connection
428
434
  └── Skaidb::QueryError # the server rejected the statement; bad parameters
435
+ └── Skaidb::TransactionConflict # a COMMIT refused: another writer changed a row it writes
429
436
  ```
430
437
 
431
438
  - A server `Error` frame is a **statement** error (`QueryError`); the
432
439
  connection stays usable.
440
+ - A server error whose message starts with `transaction conflict:` is a
441
+ `TransactionConflict`, from every call that runs a statement. It is a
442
+ `QueryError`, so `rescue Skaidb::QueryError` catches it too; see
443
+ [Transactions](#transactions).
433
444
  - A transport failure (`ConnectionError`) marks the connection broken; the
434
- next statement re-dials, or a pool replaces it.
445
+ next statement re-dials, or a pool replaces it. So does anything else that
446
+ cuts a statement short between its request and its reply (an `Interrupt`,
447
+ a `Timeout`); that exception propagates as it is.
435
448
  - `ArgumentError` for `Pool.new(maxsize: 0)` or an unknown
436
449
  `load_balancing`/`idle_order`, for `Skaidb::Uuid.new` of a string that
437
- is not a UUID, and for `stream` parameters that are not an Array.
450
+ is not a UUID, for `stream` parameters that are not an Array, and for
451
+ `transaction` with `attempts` below 1 or without a block.
438
452
 
439
453
  ## Transactions
440
454
 
441
- skaidb autocommits every statement. There is no `BEGIN` on this driver's API;
442
- where your server supports statement-level transaction control, issue
443
- `BEGIN`/`COMMIT`/`ROLLBACK` as ordinary statements. **On a cluster,
444
- transaction control is not available** — a `BEGIN` there is refused by the
445
- server as a statement error. See the server documentation for what your
446
- deployment supports.
455
+ skaidb autocommits every statement outside a transaction. A transaction is
456
+ ordinary statements on **one connection**: an opening statement, the
457
+ statements, then `COMMIT` or `ROLLBACK`. `conn.transaction` does that around
458
+ a block and returns the block's value:
459
+
460
+ ```ruby
461
+ conn.transaction do |c|
462
+ c.exec_params("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [10, 1])
463
+ c.exec_params("UPDATE accounts SET balance = balance + $1 WHERE id = $2", [10, 2])
464
+ end
465
+
466
+ conn.transaction(attempts: 5, begin: "BEGIN ATOMIC") { |c| … }
467
+ pool.transaction { |c| … } # one checked-out connection for all of it
468
+ ```
469
+
470
+ `begin:` is the opening statement, sent as given: `"BEGIN"` (the default) on
471
+ a standalone server; a cluster takes `BEGIN ATOMIC` or
472
+ `BEGIN ATOMIC PARTITION (col = lit)`. The rest is the same on both.
473
+
474
+ **Conflicts.** A standalone server (≥ 0.346) refuses a `COMMIT` when another
475
+ writer changed a row the transaction writes after its `BEGIN`. Nothing was
476
+ applied, the transaction is over, and the connection is back in autocommit
477
+ and stays usable. The driver raises `Skaidb::TransactionConflict` for it — a
478
+ `QueryError` carrying the server's message, recognised by its
479
+ `transaction conflict:` prefix, from `exec` and every other call as well as
480
+ from the helper. Running the whole transaction again from its opening
481
+ statement is safe, and that is what `transaction` does: up to `attempts` runs
482
+ in all (default 3), with no pause between them — the other writer has
483
+ already finished, and the next run reads the rows as they are now. So **the
484
+ block must be safe to run more than once**, and should do nothing outside the
485
+ database that a repeat would do twice. The conflict of the last attempt is
486
+ raised.
487
+
488
+ What else `transaction` does:
489
+
490
+ - The opening statement is refused: its error is raised, the block never
491
+ runs and nothing else is sent.
492
+ - The block does not run to its end (an exception, `break`, `throw`):
493
+ `ROLLBACK` is sent, and the block's exception propagates unchanged
494
+ whatever the `ROLLBACK` itself answers. Nothing is retried, a
495
+ `TransactionConflict` raised inside the block included.
496
+ - Any other `COMMIT` error is raised as it is, with no retry and no
497
+ `ROLLBACK`: a `COMMIT` that fails has ended the transaction.
498
+ - A transport failure is the usual `ConnectionError` and is not retried. The
499
+ transaction lived on the socket that died, so until `transaction` returns
500
+ the connection does not re-dial: no `ROLLBACK` is sent, and a statement the
501
+ block still runs after rescuing the failure raises `ConnectionError`
502
+ instead of running on a new session. The same goes for a block cut short
503
+ in the middle of a round trip (an `Interrupt`, a `Timeout`): the reply is
504
+ still on its way, so nothing more is written to that socket.
505
+ - `pool.transaction(attempts: 3, begin: "BEGIN", affinity: nil)` checks one
506
+ connection out, runs every attempt on it, and returns it afterwards.
507
+
508
+ Written by hand, the same transaction is:
509
+
510
+ ```ruby
511
+ conn.exec("BEGIN") # if this raises, stop here
512
+ begin
513
+ conn.exec_params("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [10, 1])
514
+ conn.exec_params("UPDATE accounts SET balance = balance + $1 WHERE id = $2", [10, 2])
515
+ rescue StandardError
516
+ begin
517
+ conn.exec("ROLLBACK") if conn.usable?
518
+ rescue Skaidb::Error
519
+ nil # the clean-up never replaces the error it follows
520
+ end
521
+ raise
522
+ end
523
+ conn.exec("COMMIT") # Skaidb::TransactionConflict: nothing was applied; run it again from BEGIN
524
+ ```
525
+
526
+ Two rules hold however the statements are sent:
527
+
528
+ - **One connection for the whole transaction.** Statements sent on another
529
+ connection are not part of it, so with a pool check one connection out
530
+ (`pool.with`) and keep it until the `COMMIT`; a statement another thread
531
+ sends on that connection meanwhile is part of it. A `ConnectionError` ends
532
+ the transaction with its socket; the connection's next statement re-dials
533
+ and runs on a new session, in autocommit. That is why the example sends
534
+ `ROLLBACK` only while the connection is `usable?`.
535
+ - **Stop if `BEGIN` fails.** No transaction is open, so every statement sent
536
+ after it would be committed on its own.
537
+
538
+ A statement that fails inside a transaction leaves it open: decide between
539
+ `ROLLBACK` and carrying on. A `ROLLBACK` with no transaction open succeeds on
540
+ a server ≥ 0.347 and is a statement error (`no transaction in progress`) on
541
+ an older one.
447
542
 
448
543
  ## Thread safety
449
544
 
@@ -461,7 +556,7 @@ frame after every handshake. It shows up as `client_name = 'ruby'` /
461
556
 
462
557
  ```sql
463
558
  SELECT client_name, client_version FROM drivers;
464
- -- ruby | 1.4.0
559
+ -- ruby | 1.5.0
465
560
  ```
466
561
 
467
562
  The server records the row asynchronously, so a `SELECT` immediately after
data/docs/api.md CHANGED
@@ -52,6 +52,9 @@ Raises `Skaidb::Error` before dialing for an unknown `auth_mechanism`, a
52
52
  (which names the failing row index; earlier rows stay applied).
53
53
  - `exec_prepared(id, params, consistency) → Result` — run a statement by the
54
54
  id `prepare_server` returned, with an Array of typed values in `?` order.
55
+ The id is valid on the socket that prepared it: on a broken connection
56
+ this raises `ConnectionError` instead of re-dialing, and `prepare_server`
57
+ hands out a new id.
55
58
  - `prepare_server(sql) → [id, nparams] | nil` — prepare a statement with `?`
56
59
  placeholders on the server; `nil` when the server refuses. Cached per
57
60
  connection (240 entries); the cache is cleared on re-dial.
@@ -77,13 +80,55 @@ Raises `Skaidb::Error` before dialing for an unknown `auth_mechanism`, a
77
80
  keyset cursor, sleeping `poll` seconds when caught up. `after:` is the last
78
81
  `"id"` (an opaque String) already handled.
79
82
 
83
+ ### Transactions
84
+
85
+ `transaction(attempts: 3, begin: "BEGIN") { |conn| … } → the block's value`
86
+ runs the block inside a transaction on this connection: it sends `begin`,
87
+ yields the connection, then sends `COMMIT`.
88
+
89
+ - `begin:` is the opening statement, sent as given: `"BEGIN"` on a standalone
90
+ server, `"BEGIN ATOMIC"` or `"BEGIN ATOMIC PARTITION (col = lit)"` on a
91
+ cluster.
92
+ - A `COMMIT` refused with `TransactionConflict` (a standalone server ≥ 0.346:
93
+ another writer changed a row the transaction writes after its `BEGIN`;
94
+ nothing was applied) runs the whole transaction again from `begin`, up to
95
+ `attempts` runs in all with no pause between them. The block may therefore
96
+ run more than once: it must be safe to repeat and should do nothing outside
97
+ the database that a repeat would do twice. The conflict of the last
98
+ attempt is raised.
99
+ - `begin` refused: its error is raised, the block never runs and nothing
100
+ else is sent.
101
+ - The block does not run to its end (an exception of any class, `break`,
102
+ `throw`, a `return` out of it): `ROLLBACK` is sent and the exception
103
+ propagates unchanged, whatever the `ROLLBACK` itself answers — an error
104
+ from it is ignored. Nothing is retried, a `TransactionConflict` raised
105
+ inside the block included.
106
+ - Any other `COMMIT` error is raised as it is, with no retry and no
107
+ `ROLLBACK` (a `COMMIT` that fails has ended the transaction).
108
+ - A transport failure is the usual `ConnectionError` and is not retried.
109
+ Until `transaction` returns the connection does not re-dial: no `ROLLBACK`
110
+ is sent, and a statement the block runs after rescuing the failure raises
111
+ `ConnectionError` (`connection lost inside a transaction; …`). A
112
+ `ConnectionError` from the `COMMIT` leaves its outcome unknown.
113
+ - A block cut short in the middle of a round trip (an `Interrupt`, a
114
+ `Timeout`, `Thread#kill`) leaves a reply on its way, so the connection is
115
+ not `usable?` and nothing more is written to it: no `ROLLBACK`. The
116
+ transaction ends with that socket, which the next statement after
117
+ `transaction` replaces.
118
+ - Raises `ArgumentError`, before anything is sent, when `attempts` is not an
119
+ Integer ≥ 1 or no block is given.
120
+
121
+ The whole transaction runs on this one connection, so no other thread may
122
+ use it meanwhile.
123
+
80
124
  ### State
81
125
 
82
126
  - `consistency` / `consistency=` — the default level (`0`/`1`/`2`; the setter
83
127
  accepts anything `Consistency.resolve` does).
84
- - `usable?` — `false` once closed, once a transport error broke the socket,
85
- or while a stream is in flight (including one abandoned through external
86
- iteration). No round-trip.
128
+ - `usable?` — `false` once closed, once a transport error broke the socket
129
+ or a round trip was cut short with its reply outstanding, or while a
130
+ stream is in flight (including one abandoned through external iteration).
131
+ No round-trip.
87
132
  - `endpoint` — the member the connection reached, as the `"host:port"` it
88
133
  dialed (it changes when a re-dial lands on another member).
89
134
  - `closed`, `finished?` — `true` after `close`.
@@ -93,12 +138,17 @@ Raises `Skaidb::Error` before dialing for an unknown `auth_mechanism`, a
93
138
  ### Reconnect
94
139
 
95
140
  A transport failure raises `Skaidb::ConnectionError` and marks the
96
- connection broken. The next `exec`/`exec_params`/`exec_batch`/`stream`
141
+ connection broken. A statement cut short between its request and its reply
142
+ by anything else (an `Interrupt`, `Timeout.timeout`, `Thread#kill`) marks it
143
+ broken too, since that reply is still on its way; the exception propagates
144
+ as it is. The next `exec`/`exec_params`/`exec_batch`/`stream`
97
145
  re-dials across the original seeds (a pooled connection: in the pool's
98
146
  order, usable members first and the one it lost last), re-authenticates,
99
147
  re-sends `Hello`, re-runs `USE`, and starts with an empty prepared-statement
100
148
  cache. If the re-dial fails, that statement raises `ConnectionError` and the
101
- one after it tries again.
149
+ one after it tries again. Inside `transaction` there is no re-dial: the
150
+ transaction ended with its socket, so every further statement raises
151
+ `ConnectionError` until the helper returns.
102
152
 
103
153
  ## `Skaidb::Result`
104
154
 
@@ -131,6 +181,10 @@ A thread-safe pool balanced across the cluster's members — see
131
181
 
132
182
  - `with(affinity: nil) { |conn| … }` — check out, yield, check in; returns
133
183
  the block's value.
184
+ - `transaction(attempts: 3, begin: "BEGIN", affinity: nil) { |conn| … }` —
185
+ `Connection#transaction` on one checked-out connection, held for every
186
+ attempt and checked in afterwards; returns the block's value. The
187
+ arguments are checked before a connection is checked out.
134
188
  - `checkout(affinity: nil) → Connection` — an idle connection to the member
135
189
  the policy picks, or a new one. Never blocks. `affinity` (any Hash key;
136
190
  `nil` = pool-wide) scopes `read_your_writes`.
@@ -143,9 +197,9 @@ A thread-safe pool balanced across the cluster's members — see
143
197
 
144
198
  `load_balancing` (`:random`, `:round_robin`, `:least_latency`) and
145
199
  `idle_order` (`:lifo`, `:fifo`) take a Symbol or a String. Raises
146
- `ArgumentError` for `maxsize < 1`, `eject_errors < 1` or an unknown
147
- `load_balancing`/`idle_order`, and `Skaidb::Error` on checkout from a closed
148
- pool.
200
+ `ArgumentError` for `maxsize < 1`, `eject_errors < 1`, an unknown
201
+ `load_balancing`/`idle_order` or a `transaction` with `attempts` below 1 or
202
+ no block, and `Skaidb::Error` on checkout from a closed pool.
149
203
 
150
204
  ## `Skaidb::Uuid`
151
205
 
@@ -173,6 +227,14 @@ otherwise.
173
227
  message is the server's), or a parameter could not be bound
174
228
  (placeholder/parameter mismatch, out-of-range Integer, non-finite Float or
175
229
  BigDecimal, unsupported type). The connection stays usable.
230
+ - `Skaidb::TransactionConflict < QueryError` — the server refused a `COMMIT`
231
+ because another writer changed a row the transaction writes after its
232
+ `BEGIN` (a standalone server ≥ 0.346). Raised by every call that runs a
233
+ statement, for a server error whose message starts with
234
+ `Skaidb::TransactionConflict::PREFIX` (`"transaction conflict:"`); the
235
+ message is the server's. Nothing was applied, the transaction is over and
236
+ the connection stays usable, in autocommit; running the whole transaction
237
+ again from `BEGIN` is safe, which is what `transaction` does.
176
238
 
177
239
  ## Codec helpers
178
240
 
@@ -93,6 +93,23 @@ Rows arrive chunk by chunk; the driver holds one chunk at a time. See
93
93
  [streaming.md](streaming.md), in particular what happens when you leave the
94
94
  block early.
95
95
 
96
+ ## Transactions
97
+
98
+ ```ruby
99
+ conn.transaction do |c| # BEGIN, the block, COMMIT; returns the block's value
100
+ c.exec_params("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [10, 1])
101
+ c.exec_params("UPDATE accounts SET balance = balance + $1 WHERE id = $2", [10, 2])
102
+ end
103
+ ```
104
+
105
+ A block that raises is rolled back. A `COMMIT` the server refuses because
106
+ another writer changed a row the transaction writes raises
107
+ `Skaidb::TransactionConflict` with nothing applied, and `transaction` then
108
+ runs the block again (three runs in all by default), so the block must be
109
+ safe to run more than once. On a cluster pass the opening statement:
110
+ `conn.transaction(begin: "BEGIN ATOMIC") { |c| … }`. Details:
111
+ [api.md](api.md#transactions).
112
+
96
113
  ## Errors
97
114
 
98
115
  ```ruby
@@ -105,7 +122,8 @@ rescue Skaidb::ConnectionError => e # transport/handshake trouble; next stateme
105
122
  end
106
123
  ```
107
124
 
108
- Both inherit from `Skaidb::Error`.
125
+ Both inherit from `Skaidb::Error`. `Skaidb::TransactionConflict` is a
126
+ `QueryError`.
109
127
 
110
128
  ## Close
111
129
 
data/docs/pooling.md CHANGED
@@ -44,6 +44,7 @@ Skaidb::Pool.new(
44
44
  )
45
45
 
46
46
  pool.with(affinity: nil) { |conn| … } # the block's value
47
+ pool.transaction(attempts: 3, begin: "BEGIN", affinity: nil) { |conn| … } # the block's value
47
48
  pool.checkout(affinity: nil) -> Skaidb::Connection
48
49
  pool.checkin(conn)
49
50
  pool.members -> Array of Hashes (see "Watching it")
@@ -81,7 +82,7 @@ pool = Skaidb::Pool.new(
81
82
  | `idle_order` | `:lifo` | `:lifo` hands out the most recently returned connection first, so a quiet pool keeps few sockets warm. `:fifo` hands out the longest-idle one first, so every idle connection keeps being used and a server-side idle timeout never finds one. |
82
83
  | `discover` | `false` | Reads the members with `SHOW ENDPOINTS` (server ≥ 0.327; no privilege needed) when a member is first reached and every `refresh_interval` (60 s) after — every 5 s while a member is `resyncing` or `unreachable`. New members are added, members that left are dropped (seeds are kept, marked `unlisted`), and members the server reports `resyncing` or `unreachable` get no new connections until they are `ready` again, when they start with a fresh latency average. An older or standalone server leaves the seeds as they are, and the pool stops asking. |
83
84
  | `eject_errors` | `3` | Consecutive transport failures (a failed dial, an I/O error mid-request, a capacity refusal) that eject a member. Statement errors and refused logins do not count. |
84
- | `eject_latency_factor`, `eject_latency_floor` | `3.0`, `0.05` | A member whose round-trip average is above factor × the other usable members' median **and** more than floor seconds above it is ejected (once it and another member have 10 samples each). A factor of `0` disables it. |
85
+ | `eject_latency_factor`, `eject_latency_floor` | `3.0`, `0.05` | A member whose round-trip average is above factor × the other usable members' median **and** more than floor seconds above it is ejected (once it and another member have 10 samples each). The fastest of a member's first three round trips seeds its average, so a statement that stalls in your own process — a CPU-bound start-up — cannot get a healthy member ejected; the `logger` warning names the average, the median and the slowest of the member's last 10 round trips. A factor of `0` disables it. |
85
86
  | `eject_backoff`, `eject_backoff_max` | `5.0`, `60.0` | How long an ejection lasts, doubling for each repeat up to the max; a member that stays healthy for `eject_backoff_max` after a re-admission starts over at the base. When the time is up a background thread dials the member and runs one statement: success re-admits it (with a fresh latency average), failure ejects it again. The last usable member is never ejected — a slow or flaky member beats none. |
86
87
  | `read_your_writes` | `0.0` | Seconds after a write during which checkouts with the same `affinity` go to the member that took the write. |
87
88
  | `logger` | `nil` | A `Logger` (or anything with `warn`) told of each ejection and re-admission. |
@@ -94,10 +95,15 @@ through to the other usable members, then to the unusable ones, so a
94
95
  checkout never has nowhere to go while any member is configured.
95
96
 
96
97
  **Latency.** Per member the pool keeps an exponentially weighted average of
97
- round trips (request sent to the first response frame): each sample moves it
98
- 5 % of the way, and no sample counts for more than 10 × the larger of the
99
- current average and `eject_latency_floor`. One slow statement barely moves
100
- it; a member that stays slow is noticed within a few dozen statements.
98
+ round trips (request sent to the first response frame). The fastest of the
99
+ member's first three round trips seeds it: a round trip is only ever
100
+ lengthened — by the member, the network or your own process (a thread that
101
+ stalls while the application starts, say) — so one or two slow first
102
+ statements cannot set it. From then on each sample moves it 5 % of the way,
103
+ and no sample counts for more than 10 × the larger of the current average
104
+ and `eject_latency_floor`. One slow statement barely moves it; a member that
105
+ stays slow is noticed within a few dozen statements. Until its average is
106
+ seeded a member counts as not measured.
101
107
 
102
108
  **Read-your-writes.** The member that coordinated a write reads it back at
103
109
  any consistency, `ONE` included; another member may not have applied it yet.
@@ -139,7 +145,8 @@ endpoint:
139
145
  `endpoint` is what the pool dials, `canonical` the name the member reports
140
146
  for itself (once discovered), `state` one of `:ready`, `:ejected`,
141
147
  `:resyncing`, `:unreachable`, `:unlisted`, and `latency_ms` is `nil` until
142
- the member has been measured. The rules are the same in every skaidb driver
148
+ the member has been measured (its first three round trips). The rules are
149
+ the same in every skaidb driver
143
150
  ([PROTOCOL.md §6.1](https://skaidb.org/docs/PROTOCOL.html#61-balancing-a-pool-across-members)).
144
151
 
145
152
  ## Behaviour
@@ -155,6 +162,14 @@ the member has been measured. The rules are the same in every skaidb driver
155
162
  and will fail its first statement with `Skaidb::ConnectionError`; that
156
163
  failure marks it broken, so `checkin` discards it and the next checkout
157
164
  gets a fresh one. Retry the statement in that case if it is safe to.
165
+ - A transaction belongs to one connection. `pool.transaction { |conn| … }`
166
+ checks one out, runs `Connection#transaction` on it (`begin`, the block,
167
+ `COMMIT`, the whole of it again when the `COMMIT` is refused with
168
+ `Skaidb::TransactionConflict`) and checks it in afterwards; separate
169
+ `pool.with` calls may each get a different connection, and statements
170
+ sent that way are not one transaction. A `TransactionConflict` is a
171
+ statement error: it does not count against the member and the connection
172
+ goes back to the idle set.
158
173
  - `close` marks the pool closed, closes the idle connections and stops the
159
174
  background thread; connections checked out at the time are closed when
160
175
  they are returned. `checkout` on a closed pool raises `Skaidb::Error`.
data/lib/skaidb.rb CHANGED
@@ -35,7 +35,7 @@ require "bigdecimal"
35
35
  module Skaidb
36
36
  # The package version — the single source of truth. The gemspec reads it,
37
37
  # and it is what the driver reports to the server in the Hello frame.
38
- VERSION = "1.4.0"
38
+ VERSION = "1.5.0"
39
39
 
40
40
  # Base class for every error raised by this driver.
41
41
  class Error < StandardError; end
@@ -48,6 +48,35 @@ module Skaidb
48
48
  # stays usable for the next query.
49
49
  class QueryError < Error; end
50
50
 
51
+ # The server refused a COMMIT because another writer changed a row the
52
+ # transaction writes after its BEGIN. Nothing was applied and the
53
+ # transaction is over: the connection is back in autocommit and stays
54
+ # usable, and running the whole transaction again from BEGIN is safe —
55
+ # which is what Connection#transaction does. A QueryError like any other
56
+ # statement error, so +rescue Skaidb::QueryError+ catches it too; the
57
+ # message is the server's.
58
+ class TransactionConflict < QueryError
59
+ # What the server's message starts with (PROTOCOL.md §6 rule 6). Only the
60
+ # prefix is matched: the rest of the text may change.
61
+ PREFIX = "transaction conflict:"
62
+ end
63
+
64
+ # Internal: the error for a server Error frame's message — a
65
+ # TransactionConflict when it starts with the conflict prefix, a QueryError
66
+ # otherwise, the message unchanged either way.
67
+ def self.statement_error(message)
68
+ (message.start_with?(TransactionConflict::PREFIX) ? TransactionConflict : QueryError).new(message)
69
+ end
70
+
71
+ # Internal: the argument checks of Connection#transaction and
72
+ # Pool#transaction, made before anything is sent.
73
+ def self.check_transaction_arguments(attempts, has_block)
74
+ raise ArgumentError, "transaction needs a block" unless has_block
75
+ return if attempts.is_a?(Integer) && attempts >= 1
76
+
77
+ raise ArgumentError, "attempts must be an Integer >= 1, got #{attempts.inspect}"
78
+ end
79
+
51
80
  # Consistency levels — how many replicas must acknowledge/answer.
52
81
  module Consistency
53
82
  ONE = 0
@@ -715,6 +744,9 @@ module Skaidb
715
744
  @broken = false
716
745
  # A stream is in flight, so the socket sits mid-reply (see stream).
717
746
  @streaming = false
747
+ # The transaction helper is between its BEGIN and its COMMIT/ROLLBACK,
748
+ # so a lost socket must not be re-dialled (see ensure_live!).
749
+ @in_transaction = false
718
750
  @prepared = {}
719
751
  @last_prepare_error = nil
720
752
  # Retained so a reconnect repeats the original connect exactly.
@@ -926,6 +958,82 @@ module Skaidb
926
958
  n
927
959
  end
928
960
 
961
+ # Run the block inside a transaction on this connection and return the
962
+ # block's value: +begin+, the block (handed the connection), COMMIT.
963
+ #
964
+ # conn.transaction do |c|
965
+ # c.exec_params("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [10, 1])
966
+ # c.exec_params("UPDATE accounts SET balance = balance + $1 WHERE id = $2", [10, 2])
967
+ # end
968
+ #
969
+ # A COMMIT the server refuses with TransactionConflict (another writer
970
+ # changed a row the transaction writes; nothing was applied) starts the
971
+ # whole thing again from +begin+ — up to +attempts+ runs in all, with no
972
+ # pause between them: the other writer has already finished, and the next
973
+ # run reads the rows as they are now. So the block may run MORE THAN
974
+ # ONCE: it must be safe to repeat, and should do nothing outside the
975
+ # database that a repeat would do twice. The conflict of the last attempt
976
+ # is raised.
977
+ #
978
+ # +begin+ is the opening statement, sent as given: "BEGIN" on a
979
+ # standalone server, "BEGIN ATOMIC" or "BEGIN ATOMIC PARTITION (col =
980
+ # lit)" on a cluster.
981
+ #
982
+ # - +begin+ refused: its error is raised, the block never runs and
983
+ # nothing else is sent (the block's statements would autocommit one by
984
+ # one).
985
+ # - The block does not run to its end — an exception of any class,
986
+ # +break+, +throw+ or a +return+ out of it: ROLLBACK is sent, and what
987
+ # the block was leaving with carries on unchanged whatever the ROLLBACK
988
+ # itself answers. Nothing is retried, a TransactionConflict raised in
989
+ # the block included.
990
+ # - Any other COMMIT error is raised as it is. A failed COMMIT has ended
991
+ # the transaction, so no ROLLBACK follows and nothing is retried.
992
+ # - A transport failure is the usual ConnectionError and is not retried.
993
+ # The transaction lived on the socket that died, so until the helper
994
+ # returns the connection does not re-dial: no ROLLBACK is sent, and a
995
+ # statement the block still runs after rescuing the failure raises
996
+ # ConnectionError instead of autocommitting on a new session. The same
997
+ # goes for a block cut short in the middle of a round trip (an
998
+ # Interrupt, a Timeout): the reply is still on its way, so nothing more
999
+ # is written to that socket.
1000
+ #
1001
+ # The whole transaction runs on this one connection, so no other thread
1002
+ # may use it meanwhile. +attempts+ below 1, or no block, is an
1003
+ # ArgumentError raised before anything is sent.
1004
+ def transaction(attempts: 3, begin: "BEGIN")
1005
+ opening = binding.local_variable_get(:begin) # +begin+ is a keyword, so the local has no other name
1006
+ Skaidb.check_transaction_arguments(attempts, block_given?)
1007
+
1008
+ enclosing = @in_transaction
1009
+ attempt = 0
1010
+ begin
1011
+ attempt += 1
1012
+ committing = false
1013
+ exec(opening)
1014
+ @in_transaction = true
1015
+ finished = false
1016
+ begin
1017
+ value = yield self
1018
+ finished = true
1019
+ ensure
1020
+ rollback_quietly unless finished
1021
+ end
1022
+ committing = true
1023
+ exec("COMMIT")
1024
+ value
1025
+ rescue TransactionConflict
1026
+ # Only a refused COMMIT is run again; a conflict the block raised
1027
+ # was rolled back above, and one from +begin+ opened nothing.
1028
+ raise unless committing && attempt < attempts
1029
+
1030
+ @in_transaction = enclosing
1031
+ retry
1032
+ ensure
1033
+ @in_transaction = enclosing
1034
+ end
1035
+ end
1036
+
929
1037
  # Stream a result set: yields one row Hash at a time while holding a
930
1038
  # single chunk, instead of buffering the whole result. For exports and
931
1039
  # large scans.
@@ -1000,8 +1108,7 @@ module Skaidb
1000
1108
  @mutex.synchronize do
1001
1109
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
1002
1110
  begin
1003
- write_frame(req)
1004
- r = Reader.new(read_frame)
1111
+ r = Reader.new(round_trip(req))
1005
1112
  rescue ConnectionError
1006
1113
  observe_failure
1007
1114
  raise
@@ -1016,7 +1123,7 @@ module Skaidb
1016
1123
  what = params.empty? ? "streaming" : "parameterised streaming (skaidb >= 0.330)"
1017
1124
  raise QueryError, "server does not support #{what}: #{msg}"
1018
1125
  end
1019
- raise QueryError, msg
1126
+ raise Skaidb.statement_error(msg)
1020
1127
  when 1
1021
1128
  return Result.new(fields: [], rows: [], cmd_tuples: r.u64, kind: :mutation) # not row-producing
1022
1129
  when 2
@@ -1056,7 +1163,7 @@ module Skaidb
1056
1163
  live = false
1057
1164
  when 3
1058
1165
  live = false
1059
- raise QueryError, fr.text
1166
+ raise Skaidb.statement_error(fr.text)
1060
1167
  else
1061
1168
  # Mid-stream the server sends only RowsChunk, RowsEnd or Error.
1062
1169
  # Anything else means we no longer know where the reply ends, so
@@ -1090,10 +1197,12 @@ module Skaidb
1090
1197
  # server declines the statement kind (DDL, session statements) so the
1091
1198
  # caller falls back to text binding. Cached per connection.
1092
1199
  def prepare_server(sql)
1093
- hit = @prepared[sql]
1094
- return hit if hit
1095
1200
  raise ConnectionError, "connection is closed" if @closed
1201
+ # Before the cache is read: a re-dial empties it, and a cached id must
1202
+ # not send a statement down a socket that is broken.
1096
1203
  ensure_live!
1204
+ hit = @prepared[sql]
1205
+ return hit if hit
1097
1206
 
1098
1207
  sql_bytes = sql.dup.force_encoding("UTF-8").b
1099
1208
  req = [2].pack("C") + [sql_bytes.bytesize].pack("V") + sql_bytes
@@ -1116,9 +1225,12 @@ module Skaidb
1116
1225
  end
1117
1226
  end
1118
1227
 
1119
- # Execute a prepared statement with TYPED parameters.
1228
+ # Execute a prepared statement with TYPED parameters. The id belongs to
1229
+ # the socket that prepared it, so a broken connection is not re-dialled
1230
+ # here: prepare_server does that, and hands out a new id.
1120
1231
  def exec_prepared(id, params, consistency)
1121
1232
  raise ConnectionError, "connection is closed" if @closed
1233
+ raise ConnectionError, "connection is broken; prepare the statement again" if @broken
1122
1234
 
1123
1235
  req = +([3, consistency].pack("CC") + [id].pack("V") + [params.length].pack("v"))
1124
1236
  params.each do |p|
@@ -1210,6 +1322,10 @@ module Skaidb
1210
1322
  def ensure_live!
1211
1323
  raise ConnectionError, "connection is closed" if @closed
1212
1324
  return unless @broken
1325
+ # A transaction lives on the socket that carried its BEGIN. Re-dialling
1326
+ # inside the helper would run the rest of the block, and the COMMIT, on
1327
+ # a new session with no transaction open: each statement autocommitted.
1328
+ raise ConnectionError, "connection lost inside a transaction; not re-dialling until it ends" if @in_transaction
1213
1329
 
1214
1330
  @prepared.clear
1215
1331
  begin
@@ -1338,6 +1454,19 @@ module Skaidb
1338
1454
 
1339
1455
  # -- query --
1340
1456
 
1457
+ # The transaction helper's clean-up after a block that did not run to its
1458
+ # end. It runs while something else is unwinding, so it never raises: a
1459
+ # ROLLBACK the server refuses (one before 0.347 answers "no transaction in
1460
+ # progress" when nothing is open) or that dies in transport must not
1461
+ # replace what the block left with. Not sent on a connection that is not
1462
+ # usable — its socket died, or was left in the middle of a reply: the
1463
+ # transaction goes with the socket.
1464
+ def rollback_quietly
1465
+ exec("ROLLBACK") if usable?
1466
+ rescue StandardError
1467
+ nil
1468
+ end
1469
+
1341
1470
  def run(sql, consistency)
1342
1471
  raise ConnectionError, "connection is closed" if @closed
1343
1472
  ensure_live!
@@ -1380,10 +1509,7 @@ module Skaidb
1380
1509
  def request(req)
1381
1510
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
1382
1511
  frame = begin
1383
- @mutex.synchronize do
1384
- write_frame(req)
1385
- read_frame
1386
- end
1512
+ @mutex.synchronize { round_trip(req) }
1387
1513
  rescue ConnectionError
1388
1514
  observe_failure
1389
1515
  raise
@@ -1392,6 +1518,23 @@ module Skaidb
1392
1518
  Reader.new(frame)
1393
1519
  end
1394
1520
 
1521
+ # Write a request and read the first frame of its reply (the caller holds
1522
+ # @mutex). Leaving in between — on a transport error, but also on an
1523
+ # Interrupt, a Timeout or Thread#kill, which no rescue here sees — means
1524
+ # the reply is still on its way: the socket no longer sits at a request
1525
+ # boundary, and the next statement would read this one's reply as its
1526
+ # own. So the connection is marked broken: usable? turns false, a pool
1527
+ # drops it, and the next statement re-dials.
1528
+ def round_trip(req)
1529
+ answered = false
1530
+ write_frame(req)
1531
+ frame = read_frame
1532
+ answered = true
1533
+ frame
1534
+ ensure
1535
+ @broken = true unless answered
1536
+ end
1537
+
1395
1538
  def observe_failure
1396
1539
  @observer.note_failure(@endpoint) if @observer && @endpoint
1397
1540
  end
@@ -1414,7 +1557,7 @@ module Skaidb
1414
1557
  when 2 # Ddl
1415
1558
  Result.new(fields: [], rows: [], cmd_tuples: 0, kind: :ddl)
1416
1559
  when 3 # Error — a statement error, connection stays usable
1417
- raise QueryError, r.text
1560
+ raise Skaidb.statement_error(r.text)
1418
1561
  else
1419
1562
  raise ConnectionError, "unknown response tag #{tag}"
1420
1563
  end
@@ -1568,13 +1711,18 @@ module Skaidb
1568
1711
  class Pool
1569
1712
  POLICIES = %i[random round_robin least_latency].freeze
1570
1713
  IDLE_ORDERS = %i[lifo fifo].freeze
1571
- # Latency EWMA: each round trip moves a member's average 5% toward it,
1572
- # and no sample counts for more than 10x the larger of the current
1573
- # average and the ejection floor — one slow query does not eject a
1574
- # healthy member, a member that stays slow is ejected within a few dozen
1575
- # statements.
1714
+ # Latency EWMA: the fastest of a member's first round trips seeds it (a
1715
+ # round trip is only ever lengthened — by the member, the network or this
1716
+ # process stalling — so a slow first statement cannot set it); then each
1717
+ # round trip moves it 5% toward it, and no sample counts for more than
1718
+ # 10x the larger of the current average and the ejection floor — one slow
1719
+ # query does not eject a healthy member, a member that stays slow is
1720
+ # ejected within a few dozen statements.
1721
+ EWMA_SEED_SAMPLES = 3
1576
1722
  EWMA_WEIGHT = 0.05
1577
1723
  EWMA_CLAMP = 10.0
1724
+ # Round trips a latency ejection's warning reports the slowest of.
1725
+ RECENT_SAMPLES = 10
1578
1726
  # Round trips a member (and at least one other) needs before its average
1579
1727
  # can eject it.
1580
1728
  EWMA_MIN_SAMPLES = 10
@@ -1591,12 +1739,13 @@ module Skaidb
1591
1739
  MAINTAIN_TICK = 0.25
1592
1740
  # Read-your-writes keys kept before the expired ones are swept.
1593
1741
  AFFINITY_SWEEP = 4096
1594
- private_constant :EWMA_WEIGHT, :EWMA_CLAMP, :EWMA_MIN_SAMPLES, :STALE_SAMPLE,
1595
- :REFRESH_NOT_READY, :MAINTAIN_TICK, :AFFINITY_SWEEP
1742
+ private_constant :EWMA_SEED_SAMPLES, :EWMA_WEIGHT, :EWMA_CLAMP, :RECENT_SAMPLES,
1743
+ :EWMA_MIN_SAMPLES, :STALE_SAMPLE, :REFRESH_NOT_READY, :MAINTAIN_TICK,
1744
+ :AFFINITY_SWEEP
1596
1745
 
1597
1746
  # One member as the pool sees it.
1598
1747
  class Member
1599
- attr_reader :endpoint, :host, :port, :seed
1748
+ attr_reader :endpoint, :host, :port, :seed, :firsts, :recent
1600
1749
  attr_accessor :canonical, :listed, :ewma, :samples, :last_sample, :errors,
1601
1750
  :ejected_until, :ejections, :readmitted_at, :in_use, :probing
1602
1751
 
@@ -1608,6 +1757,8 @@ module Skaidb
1608
1757
  @canonical = nil # its own SHOW ENDPOINTS name
1609
1758
  @listed = :ready # :ready, :resyncing, :unreachable, :unlisted
1610
1759
  @ewma = nil # seconds
1760
+ @firsts = [] # round trips before the average is seeded
1761
+ @recent = [] # the last RECENT_SAMPLES round trips
1611
1762
  @samples = 0
1612
1763
  @last_sample = 0.0
1613
1764
  @errors = 0 # consecutive transport failures
@@ -1617,6 +1768,14 @@ module Skaidb
1617
1768
  @in_use = 0
1618
1769
  @probing = false
1619
1770
  end
1771
+
1772
+ # Measure the member afresh (a re-admission, back to ready).
1773
+ def reset_latency
1774
+ @ewma = nil
1775
+ @firsts.clear
1776
+ @recent.clear
1777
+ @samples = 0
1778
+ end
1620
1779
  end
1621
1780
  private_constant :Member
1622
1781
 
@@ -1730,6 +1889,20 @@ module Skaidb
1730
1889
  end
1731
1890
  end
1732
1891
 
1892
+ # Run the block inside a transaction on ONE checked-out connection and
1893
+ # return the block's value: Connection#transaction, with the same
1894
+ # +attempts+ and +begin+, on a connection held for the whole transaction
1895
+ # — every attempt included — and returned afterwards. +affinity+ scopes
1896
+ # read-your-writes, as in +with+.
1897
+ #
1898
+ # pool.transaction { |conn| conn.exec_params("UPDATE … WHERE id = $1", [id]) }
1899
+ def transaction(attempts: 3, begin: "BEGIN", affinity: nil, &block)
1900
+ opening = binding.local_variable_get(:begin) # +begin+ is a keyword, so the local has no other name
1901
+ Skaidb.check_transaction_arguments(attempts, block_given?)
1902
+
1903
+ with(affinity: affinity) { |conn| conn.transaction(attempts: attempts, begin: opening, &block) }
1904
+ end
1905
+
1733
1906
  # The members as the pool sees them, for monitoring: one Hash each with
1734
1907
  # +:endpoint+ (what the pool dials), +:canonical+ (the member's own name,
1735
1908
  # once discovered), +:state+ (+:ready+, +:ejected+, +:resyncing+,
@@ -1787,15 +1960,21 @@ module Skaidb
1787
1960
  next if m.nil?
1788
1961
 
1789
1962
  m.errors = 0
1963
+ m.recent.push(elapsed)
1964
+ m.recent.shift if m.recent.length > RECENT_SAMPLES
1790
1965
  if m.ewma.nil?
1791
- m.ewma = elapsed
1966
+ m.firsts.push(elapsed)
1967
+ if m.firsts.length >= EWMA_SEED_SAMPLES
1968
+ m.ewma = m.firsts.min
1969
+ m.firsts.clear
1970
+ end
1792
1971
  else
1793
1972
  cap = EWMA_CLAMP * [m.ewma, @eject_floor].max
1794
1973
  m.ewma += EWMA_WEIGHT * ([elapsed, cap].min - m.ewma)
1795
1974
  end
1796
1975
  m.samples += 1
1797
1976
  m.last_sample = now
1798
- next unless m.samples >= EWMA_MIN_SAMPLES && @eject_factor.positive? && m.ejected_until.nil?
1977
+ next unless m.ewma && m.samples >= EWMA_MIN_SAMPLES && @eject_factor.positive? && m.ejected_until.nil?
1799
1978
 
1800
1979
  others = @members.each_value.select do |o|
1801
1980
  !o.equal?(m) && usable?(o) && o.ewma && o.samples >= EWMA_MIN_SAMPLES
@@ -1804,7 +1983,9 @@ module Skaidb
1804
1983
 
1805
1984
  median = others[(others.length - 1) / 2]
1806
1985
  if m.ewma > @eject_factor * median && m.ewma - median > @eject_floor
1807
- eject(m, format("latency %.1f ms vs median %.1f ms", m.ewma * 1000, median * 1000))
1986
+ eject(m, format("latency %.1f ms vs median %.1f ms; " \
1987
+ "slowest of the last %d round trips %.1f ms",
1988
+ m.ewma * 1000, median * 1000, m.recent.length, m.recent.max * 1000))
1808
1989
  end
1809
1990
  end
1810
1991
  end
@@ -2009,8 +2190,7 @@ module Skaidb
2009
2190
  if ok && !@closed
2010
2191
  m.ejected_until = nil
2011
2192
  m.errors = 0
2012
- m.ewma = nil
2013
- m.samples = 0
2193
+ m.reset_latency
2014
2194
  m.readmitted_at = now
2015
2195
  log("re-admitted #{m.endpoint}")
2016
2196
  if @idle.length < @maxsize
@@ -2112,8 +2292,7 @@ module Skaidb
2112
2292
  state = %w[ready resyncing unreachable].include?(state) ? state.to_sym : :ready
2113
2293
  if state == :ready && m.listed != :ready
2114
2294
  # Back in rotation: measured afresh, like a re-admission.
2115
- m.ewma = nil
2116
- m.samples = 0
2295
+ m.reset_latency
2117
2296
  m.errors = 0
2118
2297
  end
2119
2298
  m.listed = state
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: skaidb
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.4.0
4
+ version: 1.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - skaidb contributors
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-10-30 00:00:00.000000000 Z
11
+ date: 2026-11-15 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: bigdecimal