redis_queued_locks 1.23.0 → 1.24.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.
Files changed (58) hide show
  1. checksums.yaml +4 -4
  2. data/.claude/project-overview.md +70 -33
  3. data/.claude/rules/acquirer.md +6 -3
  4. data/.claude/rules/arguments.md +2 -2
  5. data/.claude/rules/git.md +1 -1
  6. data/.claude/rules/logic.md +5 -4
  7. data/.claude/rules/readme.md +40 -0
  8. data/.claude/rules/swarm.md +2 -2
  9. data/.claude/rules/tests.md +3 -2
  10. data/.claude/rules/type-checking.md +3 -2
  11. data/.claude/rules/visitors.md +3 -2
  12. data/.claude/skills/rql-code-review/SKILL.md +6 -3
  13. data/.claude/skills/rql-project-full-review/SKILL.md +171 -0
  14. data/.claude/skills/rql-project-full-review/templates/report.en.md +41 -0
  15. data/.claude/skills/rql-project-full-review/templates/report.ru.md +41 -0
  16. data/CHANGELOG.md +30 -9
  17. data/CLAUDE.md +7 -5
  18. data/README.md +390 -17
  19. data/lib/redis_queued_locks/acquirer/acquire_lock/dequeue_from_lock_queue.rb +60 -1
  20. data/lib/redis_queued_locks/acquirer/acquire_lock/try_to_lock/log_visitor.rb +38 -1
  21. data/lib/redis_queued_locks/acquirer/acquire_lock/try_to_lock.rb +31 -4
  22. data/lib/redis_queued_locks/acquirer/acquire_lock/with_acq_timeout.rb +6 -3
  23. data/lib/redis_queued_locks/acquirer/acquire_lock/yield_expire.rb +257 -32
  24. data/lib/redis_queued_locks/acquirer/acquire_lock.rb +103 -4
  25. data/lib/redis_queued_locks/acquirer/lock_series/try_to_lock_series.rb +27 -1
  26. data/lib/redis_queued_locks/acquirer/lock_series.rb +160 -15
  27. data/lib/redis_queued_locks/client.rb +96 -16
  28. data/lib/redis_queued_locks/config/dsl.rb +2 -0
  29. data/lib/redis_queued_locks/config.rb +35 -11
  30. data/lib/redis_queued_locks/errors.rb +19 -2
  31. data/lib/redis_queued_locks/lock_keeper/instr_visitor.rb +173 -0
  32. data/lib/redis_queued_locks/lock_keeper/lease.rb +434 -0
  33. data/lib/redis_queued_locks/lock_keeper/lock_lease.rb +106 -0
  34. data/lib/redis_queued_locks/lock_keeper/log_visitor.rb +187 -0
  35. data/lib/redis_queued_locks/lock_keeper.rb +1007 -0
  36. data/lib/redis_queued_locks/resource.rb +1 -1
  37. data/lib/redis_queued_locks/swarm/swarm_element/threaded.rb +2 -2
  38. data/lib/redis_queued_locks/utilities.rb +1 -15
  39. data/lib/redis_queued_locks/version.rb +2 -2
  40. data/lib/redis_queued_locks.rb +1 -0
  41. data/sig/redis_queued_locks/acquirer/acquire_lock/dequeue_from_lock_queue.rbs +14 -0
  42. data/sig/redis_queued_locks/acquirer/acquire_lock/try_to_lock/log_visitor.rbs +12 -0
  43. data/sig/redis_queued_locks/acquirer/acquire_lock/try_to_lock.rbs +2 -0
  44. data/sig/redis_queued_locks/acquirer/acquire_lock/yield_expire.rbs +30 -2
  45. data/sig/redis_queued_locks/acquirer/acquire_lock.rbs +6 -1
  46. data/sig/redis_queued_locks/acquirer/lock_series.rbs +12 -1
  47. data/sig/redis_queued_locks/client.rbs +14 -0
  48. data/sig/redis_queued_locks/config.rbs +15 -1
  49. data/sig/redis_queued_locks/errors.rbs +12 -0
  50. data/sig/redis_queued_locks/instrument/void_notifier.rbs +2 -2
  51. data/sig/redis_queued_locks/lock_keeper/instr_visitor.rbs +67 -0
  52. data/sig/redis_queued_locks/lock_keeper/lease.rbs +78 -0
  53. data/sig/redis_queued_locks/lock_keeper/lock_lease.rbs +19 -0
  54. data/sig/redis_queued_locks/lock_keeper/log_visitor.rbs +62 -0
  55. data/sig/redis_queued_locks/lock_keeper.rbs +108 -0
  56. data/sig/redis_queued_locks/utilities.rbs +0 -2
  57. data/sig/vendor/redis_client.rbs +1 -0
  58. metadata +15 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 0c06bae2bc7f0b6164847caa6b7adb5c77a7aab5a85dc5f3ef8c45ac19b8ed80
4
- data.tar.gz: 6a73267ecd535b74c98f489066ee5cc6f2a8c2ea261eab6d5b5f6b84e4748585
3
+ metadata.gz: cfd698c844aa60fcc94c7b90f8a48b0f9d09548f89f3d32e8d22b9ba5c6cd909
4
+ data.tar.gz: e0e050bb6e04827e53e97a9c477767627009a27f69462feb54858b1ae735da37
5
5
  SHA512:
6
- metadata.gz: b3f34d6976337bcdfe4732b3c58034ed455922450f98758a0f4c90e36a885721d847e648c5dfa64357aac9b1b401138787649bda0491693777581669f932a187
7
- data.tar.gz: 7d4e8769653ddfaf0f483a413c08ba10ea15d4f4d324e57dee1009e27222f7c2473789b0221380fc68a0047a5383083761963ed541179f7ab633876f68b3e891
6
+ metadata.gz: e85b789ce9dfe50a174ae9ec3cc357ad0ceb2c56079bd753942910d70e98e6436907865dfc9ea8df641eb90d3ab68e6fe468c5cd068b04c52bfdda8c58d91df4
7
+ data.tar.gz: fc737baa22abe3d9afc76ff8a905f8af6fafe046af8763daad84af3d0a2283cf35b3b5060496b06870e73549ed512e2a80b2c91a47775f54b2d029f7e8cee964
@@ -2,13 +2,13 @@
2
2
 
3
3
  Ruby gem providing **distributed locks on Redis with a prioritized lock-acquisition queue**.
4
4
  Each lock has its own request queue; requests are processed FIFO (`:queued`, ordered by the lock request
5
- priority first: `priority` -100..100) or first-come (`:random`). Requests have TTLs (with requeue), so queues never get stuck. Includes reentrancy
6
- (conflict) strategies, timed locks, retries/fail-fast, logging, instrumentation with sampling,
7
- and a background "swarm" that detects dead hosts and flushes their locks.
5
+ priority first: `priority` -100..100) or first-come (`:random`). Requests have TTLs (with requeue), so queues never get stuck. Includes read/write
6
+ locks, atomic lock series, reentrancy (conflict) strategies, timed locks, retries/fail-fast, an opt-in lock index, logging,
7
+ instrumentation with sampling, and a background "swarm" that detects dead hosts and flushes their locks.
8
8
 
9
9
  - Repo: https://github.com/0exp/redis_queued_locks (MIT); main branch `master`
10
10
  - Runtime dependency: `redis-client ~> 0.20` (locked 0.31.0), nothing else
11
- - Ruby `>= 4.0` (`.ruby-version` = 4.0.7)
11
+ - Ruby `>= 4.0` (`.ruby-version` = 4.0.9)
12
12
 
13
13
  ---
14
14
 
@@ -21,6 +21,7 @@ RedisQueuedLocks (lib/redis_queued_locks.rb) entry point; requires all parts;
21
21
  Client (client.rb) public API facade
22
22
  ├── Config (config.rb + config/dsl.rb) declarative settings + validators
23
23
  ├── Swarm (swarm.rb + swarm/*) supervised background workers
24
+ ├── LockKeeper (lock_keeper.rb + lock_keeper/*) keeps the locks of running blocks alive (`auto_extend`)
24
25
  └── Acquirer::* modules one stateless module per operation
25
26
  │
26
27
  ▼
@@ -32,7 +33,8 @@ Resource (resource.rb) keys, acquirer/host ids, queue s
32
33
  `Client.new(redis_client) { |config| ... }`:
33
34
  1. builds `Config` from the block,
34
35
  2. computes `uniq_identity` via `config['uniq_identifier']`,
35
- 3. creates `Swarm` and starts it when `config['swarm.auto_swarm']` is true.
36
+ 3. creates `LockKeeper` (no thread until the first `auto_extend: true` block),
37
+ 4. creates `Swarm` and starts it when `config['swarm.auto_swarm']` is true.
36
38
 
37
39
  Every other public method is a thin wrapper: it fills option defaults from `config[...]` and calls
38
40
  an `Acquirer::*` module function with `redis_client`.
@@ -151,18 +153,20 @@ AcquireLock Step 0.1 / LockSeries Step 0.1 name -> Integer, range -
151
153
  |---|---|
152
154
  | `lock` / `lock!` | `acquirer/acquire_lock.rb` + `acquirer/acquire_lock/*` |
153
155
  | `lock_series` / `lock_series!` | `acquirer/lock_series.rb` + `acquirer/lock_series/*` (atomic, see "Lock series"; one `rw_mode`, `priority` and `ttl` for the whole series) |
154
- | `unlock` | `acquirer/release_lock.rb` |
156
+ | `auto_extend:` of the four lock methods | `lock_keeper.rb` + `lock_keeper/*` (see "Lock auto extension") |
157
+ | `unlock` / `release_lock` | `acquirer/release_lock.rb` |
155
158
  | `unlock_read` / `release_read_lock` | `acquirer/release_read_lock.rb` (own read lock or `acquirer_id:` read lock only) |
156
159
  | `extend_lock_ttl` | `acquirer/extend_lock_ttl.rb` (`rw_mode: :read` extends own read lock, `+ all_read_locks: true` all live read locks) |
157
160
  | `locked?` / `queued?` | `acquirer/is_locked.rb` / `acquirer/is_queued.rb` |
158
161
  | `lock_info` / `queue_info` | `acquirer/lock_info.rb` / `acquirer/queue_info.rb` |
159
162
  | `locks`, `locks_info`, `queues`, `queues_info`, `keys` | `acquirer/locks.rb`, `queues.rb`, `keys.rb` (keyspace SCAN or lock index: `lock_index_enabled`) |
160
- | `clear_locks` | `acquirer/release_all_locks.rb` |
161
- | `clear_locks_of`, `clear_current_locks` | `acquirer/release_locks_of.rb` |
163
+ | `clear_locks` / `release_locks` | `acquirer/release_all_locks.rb` |
164
+ | `clear_locks_of` / `release_locks_of`, `clear_current_locks` / `release_current_locks` | `acquirer/release_locks_of.rb` |
162
165
  | `clear_dead_requests` | `acquirer/clear_dead_requests.rb` (`by_priority: true` reads the first request of each priority band instead of all requests) |
163
166
  | `reindex_locks` | `acquirer/reindex_locks.rb` (adds keys without lock index entries to the lock index: one SCAN pass; works in both modes) |
164
- | `current_acquirer_id`, `current_host_id`, `possible_host_ids` | `resource.rb` |
165
- | `swarmize!`, `deswarmize!`, `swarm_status`, `swarm_info`, `probe_hosts`, `flush_zombies`, `zombie_locks`, `zombie_acquirers`, `zombie_hosts`, `zombies_info` | `swarm.rb` + `swarm/*` |
167
+ | `current_acquirer_id` (`current_acq_id`, `acq_id`), `current_host_id` (`current_hst_id`, `hst_id`), `possible_host_ids` | `resource.rb` |
168
+ | `swarmize!`, `deswarmize!`, `swarm_status` / `swarm_state`, `swarm_info`, `probe_hosts`, `flush_zombies`, `zombie_locks`, `zombie_acquirers`, `zombie_hosts`, `zombies_info` / `zombies` | `swarm.rb` + `swarm/*` |
169
+ | `configure` | `config.rb` (`Config#configure`) |
166
170
 
167
171
  ### Lock acquisition flow (`acquirer/acquire_lock.rb` + `acquire_lock/`)
168
172
 
@@ -170,13 +174,35 @@ AcquireLock Step 0.1 / LockSeries Step 0.1 name -> Integer, range -
170
174
 
171
175
  | Mixin | Role |
172
176
  |---|---|
173
- | `TryToLock` (`try_to_lock.rb`) | One attempt: `multi(watch:)` (write: lock key + readers registry, read: lock key only), one pipelined read of the lock state (`HGET acq_id`, `TIME`, own reader score, longest reader: write requests only), the lock request queueing in one pipelined round trip (`queue_lock_request`: prune the priority band of the request in both queues (first: the old dead position of a requeued request is dropped before `ZADD NX` adds its new position), `ZADD NX` into the queue of the requested mode (timestamp score shifted by the priority band, see "Lock request priorities"), both queue heads with scores, then (the enabled lock index only) the lock index commands: request queue `PEXPIRE NX`+`GT` (queue ttl), `ZADD GT` of the lock name into the lock index (queue ttl), `ZREMRANGEBYSCORE` of expired lock names), drop the dead requests of other priority bands that block the request (the write queue head and the earlier opposite-mode request) with their bands in one more round trip that re-reads the heads (`drop_dead_requests_ahead`, Step 2.2, also in the pre-check: up to `MAX_DEAD_REQUEST_REMOVALS` = 5 such round trips per attempt, none while no dead request blocks), take the lock if allowed (see Read/Write locks; with the enabled lock index the obtaining `MULTI` ends with the lock index `ZADD GT` (lock ttl), the `:extendable_work_through` extension `MULTI` with `ZADD XX INCR`). Eager queueing (`:wait_for_lock`/`:dead_locking` without `fail_fast`) sends the queueing commands in the lock state round trip: `lock {}` = 4 round trips (`WATCH`, state + queueing, `MULTI/EXEC`, release), a failed attempt = 3. Pre-check (`precheck_lock`, retries and `fail_fast` attempts): the lock state (+ the queueing for retries) without `WATCH` in one round trip; an attempt that can not obtain the lock fails there (same results and log events in the same order: `lock_obstacle`/`log_lock_obstacle`, the dropped dead requests after the queueing events: `log_dropped_requests`), otherwise the attempt continues with `WATCH`/`MULTI` (a failed retry = 1 round trip, a successful one = 4; `fail_fast` on an obtained lock = 1); same-process conflicts are never decided by the pre-check. Handles reentrant conflicts (incl. read/write ones); write TTL extension via inline Lua (`PTTL` + `PEXPIRE`). |
174
- | `WithAcqTimeout` | Global acquisition timeout (`timeout`). |
177
+ | `TryToLock` (`try_to_lock.rb`) | One attempt: `multi(watch:)` (write: lock key + readers registry, read: lock key only), one pipelined read of the lock state (`HGET acq_id`, `TIME`, own reader score, longest reader: write requests only), the lock request queueing in one pipelined round trip (`queue_lock_request`: prune the priority band of the request in both queues (first: the old dead position of a requeued request is dropped before `ZADD NX` adds its new position), `ZADD NX` into the queue of the requested mode (timestamp score shifted by the priority band, see "Lock request priorities"), both queue heads with scores, then (the enabled lock index only) the lock index commands: request queue `PEXPIRE NX`+`GT` (queue ttl), `ZADD GT` of the lock name into the lock index (queue ttl), `ZREMRANGEBYSCORE` of expired lock names), drop the dead requests of other priority bands that block the request (the write queue head and the earlier opposite-mode request) with their bands in one more round trip that re-reads the heads (`drop_dead_requests_ahead`, Step 2.2, also in the pre-check: up to `MAX_DEAD_REQUEST_REMOVALS` = 5 such round trips per attempt, none while no dead request blocks), take the lock if allowed (see Read/Write locks; with the enabled lock index the obtaining `MULTI` ends with the lock index `ZADD GT` (lock ttl), the `:extendable_work_through` extension `MULTI` with `ZADD XX INCR`). Eager queueing (`:wait_for_lock`/`:dead_locking` without `fail_fast`) sends the queueing commands in the lock state round trip: `lock {}` = 4 round trips (`WATCH`, state + queueing, `MULTI/EXEC`, release), a failed attempt = 3. Pre-check (`precheck_lock`, retries and `fail_fast` attempts): the lock state (+ the queueing for retries) without `WATCH` in one round trip; an attempt that can not obtain the lock fails there (same results and log events in the same order: `lock_obstacle`/`log_lock_obstacle`, the dropped dead requests after the queueing events: `log_dropped_requests`), otherwise the attempt continues with `WATCH`/`MULTI` (a failed retry = 1 round trip, a successful one = 4 + the release; `fail_fast` on an obtained lock = 1); same-process conflicts are never decided by the pre-check. Handles reentrant conflicts (incl. read/write ones); write TTL extension via inline Lua (`PTTL` + `PEXPIRE`). |
178
+ | `WithAcqTimeout` | Global acquisition timeout (`timeout`). Its callback (`acq_dequeue` of `acquire_lock`) completes the acquirement when the lock is already obtained (`true`: no timeout error), otherwise releases the lock of an obtaining transaction that Redis can apply without the reply (`acq_process[:lock_obtaining_sent]`, set by `try_to_lock` right before `EXEC`, dropped at the start of each attempt and after a failed one: the same as `drop_failed_lock_series` of the series) and dequeues the request. |
175
179
  | `DelayExecution` | Retry delay + jitter between attempts. |
176
- | `DequeueFromLockQueue` | Removes the acquirer from the queue of the requested mode on timeout/failure. |
177
- | `YieldExpire` | Runs the user block (optionally `timed`), then releases/expires the lock of the held mode (write: `EXPIRE 0`; read: `ZREM` own reader + `DEL` own read lock data; extendable reentrant: decrease). Known limitation (kept by the user's decision, documented in README): the write release and the write ttl decrease have no owner check, so a block longer than the ttl can delete/shorten the lock of another acquirer. |
180
+ | `DequeueFromLockQueue` | Removes the acquirer from the queue of the requested mode on timeout/failure; `release_unconfirmed_lock`: the owner-checked release of the lock of an interrupted obtaining (write: `RELEASE_OWN_LOCK`, read: own `ZREM` + `DEL`; `expire_lock` log). |
181
+ | `YieldExpire` | Runs the user block (optionally `timed`: budget = `ttl` - time from the start of the successful attempt - `REDIS_TIMESHIFT_ERROR`, always within the lock lifetime; no budget left => the block is not invoked, `LockTtlTimeBudgetIsSpentError`; the budget exceeded => `TimedBlockExceedsLockTtlError`; `Timeout.timeout(0)` means no timeout; a long `ensure` of the block, `rescue Exception` and non-interruptible code can still outlive the lock; `auto_extend`: the block gets a lease of `LockKeeper` and the budget is `max_hold_time_during_auto_extend`, see "Lock auto extension"), then releases/expires the lock of the held mode (write: `EXPIRE 0`; read: `ZREM` own reader + `DEL` own read lock data; extendable reentrant: decrease). Known limitation (kept by the user's decision, documented in README): without `auto_extend` the write release and the write ttl decrease have no owner check, so a block longer than the ttl can delete/shorten the lock of another acquirer (with a lease: `RELEASE_OWN_LOCK`, `DECREASE_OWN_LOCK_PTTL`). |
178
182
  | `LogVisitor` / `InstrVisitor` | One method per lifecycle event for logs and instrumentation. |
179
183
 
184
+ ### Lock auto extension (`lock_keeper.rb`)
185
+
186
+ `auto_extend: true` (`lock`, `lock!`, `lock_series`, `lock_series!`): the lock ttl is a lease that is extended while the block of code is running. Without a block the option has no effect. The acquirement is the same: the extension concerns an already held lock; `TryToLock`/`TryToLockSeries` only recognize a reentrant attempt that is aborted by a tick (see "Reentrancy" below).
187
+
188
+ - `RedisQueuedLocks::LockKeeper`: one per `Client` (`client.lock_keeper`, forwarded as the internal keyword `lock_keeper:`, like `lock_priorities:`), one thread `rql.lock_keeper`. No module-level state: a client lives in its Ractor. The only stateful object of the lock path: `Acquirer::*` stay stateless and get it as an argument.
189
+ - `LockKeeper::Lease`: one per block of code, not per lock: the block is interrupted once and the hold limit is one for the whole block (a series with several lost locks would get several `Thread#raise`s otherwise, the second one reaches the application as an internal exception); the locks are parallel arrays (the series arrays as is; one-element arrays for `lock`).
190
+ - Connection: `redis_client.config.new_client` (own connection, no new settings; plain client, pool, sentinel). The client's `RedisClient` can be one connection: using it from another thread is the issue #10 protocol desync. Not a swarm element: the swarm is opt-in and its `redis_config.*` default to localhost.
191
+ - Settings: `config['lock_keeper.*']` (`idle_timeout`, `min_idle_wake_up_interval`, `extension_retry_ratio`, `extension_batching_ratio`, `schedule_slot`, `fiber_interruption_timeout`, `fiber_interruption_wait_step`), the keeper gets the client (`LockKeeper.new(client)`, like `Swarm`) and reads them into its attributes in `load_settings`: at the creation and at each start of the thread (`run_keeper_thread`, under `sync`, followed by `rebuild_schedule`: the slots of the registered leases are recomputed with the new `schedule_slot`; `schedule`/`unschedule` must use one slot length, so the settings never change while the thread runs). A changed setting takes effect at the next start of the thread. `EXTEND_LOCK_LUA_LOST_LOCK_REPLY` stays a constant: it is the reply of the extension scripts.
192
+ - Lifecycle: `start` (`AcquireLock`/`LockSeries` Step 1.1, before the lock is obtained: connecting takes several round trips, a slow start under load eats the first lease) → `keep` (in `yield_expire`/`lock_series`, inside the `ensure` scope of the release: an interrupted caller leaves a lease on a released lock, the next tick drops it) → `forget` (before the release: the keeper can not report a released lock as a lost one). The thread starts on demand, stops after `config['lock_keeper.idle_timeout']` (`#idle_timeout`) without new leases (counted from the last `keep`: a short block can end before the thread gets the GVL, so the leases it sees say nothing), and is revived by the next `start`/`keep` (`Thread#alive?`, a new process: `fork` keeps no threads; the leases of the parent are dropped by the pid check: a child never extends the locks of the parent). Without leases the thread keeps waking up each last extension interval, `min_idle_wake_up_interval` at least: `keep` wakes it only for an earlier extension (`@wake_at`), so a stream of short blocks of one ttl costs no context switch per block.
193
+ - Tick: leases due now (and in `extension_interval / extension_batching_ratio` of the nearest one) → one pipeline with one `EVAL` per lock; replies by position (one per lock that is not lost). Time is taken before the commands, all deadlines are counted from the start of the successful attempt (`try_start_time`) or of the tick.
194
+ - Timer wheel (under `sync`): slots of `schedule_slot` (10 ms) by `next_extension_at` (`@buckets` slot => leases, sorted `@slot_keys`), so the work under the lock does not grow with the number of running blocks (a wake-up with 1k/10k/100k leases: 0.001 ms; the former scan of the registry took 0.04/0.4/13.6 ms and blocked `keep`/`forget`). `keep`/`forget` schedule/unschedule in O(1) (an empty slot stays till its time and is reused by a stream of short blocks: no slot per block; `planned_extension_at` drops empty front slots); `take_due_leases` takes the due slots out, the tick puts the kept leases back in one section (`reschedule`), the membership checks of a tick are one section too; a limit moved by `hold_for` after the tick has found it reached (`stop_hold` → `:moved`) is extended with the others. A new thread rebuilds the schedule from the registry (`rebuild_schedule`: a killed thread can leave the leases of its tick out). The global `sync` stays on purpose: a single owner thread with a queue of leases was tried and rejected (one consumer with its share of the GVL can not drain a stream of blocks; with real locks both designs kept 240/240 extensions under 16-32 churn threads).
195
+ - Schedule: the first extension at `max(ttl / 3, ttl - extension_ttl * 2 / 3)` (at once for a reentrant `:work_through` lock and for a series with one: the attempt does not extend it, its remaining ttl is unknown, `keep` gets `0` as the ttl), then each `extension_ttl / 3` (a constant interval: never derive the next tick from the `PTTL` of the reply: a nested `:extendable_work_through` raises the ttl for a moment and takes it back after the nested block, the postponed tick comes after the expiration). `extension_ttl` = `auto_extend_ttl || ttl`.
196
+ - Extension semantics: "live `extension_ttl` from now", not "add": `EXTEND_WRITE_LOCK` (`HGET acq_id` owner check, `PEXPIRE GT`, returns `PTTL`), `EXTEND_READ_LOCK` (no write lock, live own reader (`TIME`), `ZADD XX GT`, `PEXPIRE NX`+`GT` of the registry and the reader data). Replies: `-3` = lost (`EXTEND_LOCK_LUA_LOST_LOCK_REPLY`, not a `PTTL` sentinel). A lost lock is never revived. Owner = `acq_id` only (like `release_lock_series`): `ts` of a reentrant result is not the `ts` of the lock; a late tick of a finished block can only extend the next lock of the same acquirer. Lua is not the acquirement path: mutual exclusion stays with `WATCH`/`MULTI`.
197
+ - `max_hold_time_during_auto_extend`: the protection against blocks that never finish (hung forever, or abandoned midway: a fiber that is never resumed never runs its `ensure`, its lease stays registered and its lock is extended while the process lives; an exception in the block releases the lock at once); `hold_deadline` = attempt start + limit; `extension_ttl_at` caps an extension by the time left, so the lock expires at the limit, nothing depends on the client (no renewal = expiry). At the deadline the lease is dropped and `lock_hold_limit_reached` is reported (`stop_hold` checks the limit again under `sync`: a limit moved after the partition of the tick is kept, the lease stays due). Validated against `ttl` only with `auto_extend`. The docs mark the option and `config['default_max_hold_time_during_auto_extend']` as **!IMPORTANT** (README: the config, `#lock` and "Lock Auto Extending"; the `Client#lock` YARD; CHANGELOG): the application sets the limit deliberately (`nil` or a period of its logic), the default (1 hour) is only a fallback.
198
+ - Lease of the block (`lock_keeper/lock_lease.rb`, `RedisQueuedLocks::LockKeeper::LockLease`, public): the argument of a block of code with parameters (`block.arity != 0`, no object otherwise; rbs/test wraps the blocks of the checked methods, so in the runtime type checks a lambda without parameters gets it too); a facade over the `Lease`, the keeper and the client connection. `hold_for(ms)` → `LockKeeper#hold_for`: under `sync`: lost → `:lock_lost`, stopped → `:hold_limit_reached`, not registered (forgotten, a lease of the parent after `fork`) → `:released`, else the thread is revived and `Lease#hold_until(now + ms)` (never back, no limit stays no limit); then one pipeline of the extension scripts at once through the client connection (the keeper connection belongs to its thread; at once: the last extensions end the lock at the old limit, a tick can come too late), lost replies → `report_lost_lock`, the others → `lock_hold_limit_extended`. `lost?` (local), `hold_time_left`. The deadline is moved by the thread of the block under `sync`; the schedule stays the keeper's.
199
+ - Two threads can lose a lock (the tick, `hold_for`): the replies of a pipeline are read by the lock indexes captured before it (`extended_lock_indexes`), `report_lost_lock` reports a lock once and skips an already lost one, a tick does not report the extension of a lock lost meanwhile.
200
+ - Lost lock: `auto_extended_lock_lost`, the lock is not extended anymore, other locks of the lease continue. `timed: true`: the block is interrupted with `TimedLockIntermediateTimeoutError` from the keeper thread (under `sync`, once: the lease is dropped; so no list of the WATCH rescues changes), `yield_with_timeout` converts it (`TimedBlockLostLockError` for a lost lease, `TimedBlockExceedsMaxHoldTimeError` for the hold limit). A lock lost by `hold_for` of the `timed` block itself: the error is raised in that thread after the report. The interruption period is limited by `interrupt_timed_block` and `forget`, both inside the `rescue` scope of `yield_with_timeout` (a lease is not interruptible from `keep`: a lock can be lost before the block starts, an interruption there is out of the `rescue` scope and the internal error reaches the application; `interrupt_timed_block` raises it synchronously instead (a lost lock or a stopped hold), the block is not invoked). Interruption targets (set by `interrupt_timed_block`, used by `Lease#interrupt` under `sync`): a blocking fiber → `interrupted_thread` (`Thread#raise`); a non-blocking fiber → `fiber_scheduler` when it responds to `fiber_interrupt` (a Ruby 4.0 hook that may be called by another thread; `Thread#raise` would reach another task, `Fiber#raise` raises `FiberError` across threads); no hook or no scheduler → not interruptible (`Lease#interruptible?` false). `timed_fiber` is set in every mode: `hold_for` of the block itself raises after the report in any fiber, and a non-interruptible block is interrupted by `hold_for` for a lock lost earlier too. A fiber interruption comes at the next suspension point of the fiber and can not be cancelled: `Lease#interrupt` keeps it pending (`@pending_interruption`), `forget(lease, raised_error)` ends the interruption period under `sync` (`timed_fiber` = nil: `hold_for` of a kept lease after the block never raises), takes it and, when the block ended before it came, waits for it inside the `rescue` scope (`wait_for_interruption`: `sleep(fiber_interruption_wait_step)` up to `fiber_interruption_timeout`, 1 s, then gives up: a scheduler that never raises it); `yield_with_timeout` passes the interruption that has come (inner `rescue`) and calls `forget` once more in its outer `rescue` (it can come while `forget` waits for `sync`: the next `forget` calls do not wait). A failing hook clears the pending state (the loss is reported only). An error of another source during the wait stops it (the interruption can come after the block then, like two asynchronous errors in a thread).
201
+ - `timed` + `auto_extend`: an interruptible block (a blocking fiber, or a non-blocking one with an interrupting scheduler: `async` >= 2.25): no `Timeout`, `stop_hold` interrupts the block at the hold limit (movable by `hold_for`; a dead keeper thread interrupts nothing till it is revived by the next `keep`/`hold_for`; a fiber scheduler interrupts a CPU-bound block when it yields); a non-blocking fiber without an interrupting scheduler: `Timeout` with the budget `max_hold_time_during_auto_extend` - attempt time (`nil`: no `Timeout`), `hold_for` does not move it. Specs: `async` (dev gem) in `Sync` blocks; a scheduler without the hook: its `fiber_interrupt` is undefined on the singleton class. No budget left: the block is not invoked (`LockTtlTimeBudgetIsSpentError`).
202
+ - Failed tick (`StandardError` from the pipeline): `lock_auto_extension_failed` per lock, the next try in `extension_interval / extension_retry_ratio`, the thread stays alive.
203
+ - Reentrancy: a nested block with `auto_extend` gets its own lease (no ref counters: two leases of one lock are harmless, `GT` and the owner check make them idempotent). `held_rw_mode` decides the script (a read request under the own write lock extends the write lock). A lease of a series covers its reentrant locks too. A `:work_through` lock (single or in a series) is extended at once: the outer logic can have spent its ttl (see Schedule). A tick changes the watched lock key, so it can abort `EXEC` of a reentrant attempt of the same acquirer (a series: of any attempt with a reentrant lock; `:work_through` of a single lock does not read its result): it is not a failed acquirement, the lock is held. The attempt returns `:reentrant_lock_is_changed_during_extension` (`try_lock.exit__reentrant_lock_is_changed` log) and `acquire_lock`/`lock_series` repeat it at once, Step 2.1.b: no delay, no spent try, no `fail_fast` failure, up to `TryToLock::MAX_REENTRANT_EXTENSION_RETRIES` times; a really lost lock is found by the repeated attempt.
204
+ - Limits (measured, README "Lock Auto Extending"): a Ruby thread waits for the GVL and the GC: delay ≈ 110 ms per CPU-bound thread + the longest GVL-holding call; the lock is kept while delay < 2/3 of the extension ttl (`RUBY_THREAD_TIMESLICE` scales it). Redis applies the renewal at the write, a late reply matters only for the next tick. `Thread#priority` and a raw socket (`recv_nonblock`) gave nothing. A sidecar Ractor is immune to the CPU contention but stalls at the GC barrier during long C calls, fails on non-shareable redis-client middlewares (APM) and has no `Thread` access; a helper process is immune but heavy; a presence on a subscribed connection (`PUBSUB NUMSUB`) is a separate idea (no renewals, failover and hot path costs).
205
+
180
206
  ### Lock series (`acquirer/lock_series.rb`)
181
207
 
182
208
  The second part of the lock acquisition core (not an operation module): `LockSeries` extends `TryToLockSeries` (it includes
@@ -233,10 +259,11 @@ The second part of the lock acquisition core (not an operation module): `LockSer
233
259
  ### Main `lock` options (defaults from config)
234
260
 
235
261
  `ttl`, `queue_ttl`, `lock_index_grace_period` (used with the enabled lock index only; the mode itself, `config['lock_index_enabled']`,
236
- is client-wide: `Client` passes it to the acquirers, it is not a `lock` option), `timeout`, `timed`, `retry_count`, `retry_delay`, `retry_jitter`,
262
+ is client-wide: `Client` passes it to the acquirers, it is not a `lock` option), `timeout`, `timed`, `auto_extend`, `auto_extend_ttl`, `max_hold_time_during_auto_extend`
263
+ (see "Lock auto extension"), `retry_count`, `retry_delay`, `retry_jitter`,
237
264
  `raise_errors`, `fail_fast`, `conflict_strategy`, `access_strategy`, `priority` (`-100`..`100` or a priority name of `config['lock_priorities']`, default
238
265
  `config['default_lock_priority']` = `0`, see "Lock request priorities"), `rw_mode`
239
- (`:write` (default, exclusive) | `:read` (shared)), `identity`, `meta`, `logger`, `log_lock_try`,
266
+ (`:write` (default, exclusive) | `:read` (shared)), `identity`, `meta`, `detailed_acq_timeout_error`, `logger`, `log_lock_try`,
240
267
  `instrumenter`, `instrument`, log/instr sampling options, `log_sample_this`, `instr_sample_this`.
241
268
 
242
269
  - `access_strategy`: `:queued` (FIFO, default) or `:random`.
@@ -269,7 +296,8 @@ is client-wide: `Client` passes it to the acquirers, it is not a `lock` option),
269
296
  `:conflict_dead_lock` for `:dead_locking`, waits for own read expiration for `:wait_for_lock`.
270
297
  - `fail_fast`: write fails on write holder or live readers; read fails on write holder (or own live read).
271
298
  - Try results (internal symbols): `:write_request_is_ahead`, `:read_request_is_ahead`,
272
- `:read_lock_is_still_acquired`, `:conflict_lock_upgrade`, `:read_lock_is_expired_during_extension`;
299
+ `:read_lock_is_still_acquired`, `:conflict_lock_upgrade`, `:read_lock_is_expired_during_extension`,
300
+ `:reentrant_lock_is_changed_during_extension` (see "Lock auto extension");
273
301
  try success result carries internal `rw_mode` (held mode), not exposed in the public `lock` result.
274
302
  - Validation (`AcquireLock`): `rw_mode` must be `:read`/`:write`; `ttl` must be a positive
275
303
  Integer in both modes (`RedisQueuedLocks::ArgumentError`; write: `PEXPIRE` with a non-positive ttl would
@@ -313,7 +341,7 @@ is client-wide: `Client` passes it to the acquirers, it is not a `lock` option),
313
341
  - Design decisions (release semantics, not limitations to "fix"): read->write upgrade is an error unless
314
342
  `:wait_for_lock`; nested reads of one acquirer go through `conflict_strategy` (no hold counting);
315
343
  `:random` gives no fairness between modes; cross-host FIFO is best effort; no Lua in the RW path.
316
- - RBS: `Client` types `rw_mode` as `:read | :write`. Older gem versions ignore readers: all processes must be upgraded
344
+ - RBS: `Client` types `rw_mode` as `RQL::readWriteMode` (`:read | :write`). Older gem versions ignore readers: all processes must be upgraded
317
345
  before read locks are used.
318
346
 
319
347
  ### Lock request priorities (`priority`)
@@ -440,6 +468,7 @@ is client-wide: `Client` passes it to the acquirers, it is not a `lock` option),
440
468
  indexes the lock` drops the entry right before the obtaining `MULTI`;
441
469
  - every extension of a lock key: `ZADD XX INCR <ms> <name>` in the same transaction (reentrant `:extendable_work_through`, `extend_lock_ttl`
442
470
  write (`MULTI { EVAL; ZADD }`), own read, all read locks); `XX`: names without an entry (older versions) are not indexed with a wrong score;
471
+ the lock keeper sets an absolute lifetime, so its scripts use `ZADD XX GT <now + extension ttl + grace> <name>` after the owner check (`KEYS[2]`/`KEYS[4]`, sent with the enabled lock index only);
443
472
  - the score is never decreased (`GT`; ttl decreases and releases do not touch the index);
444
473
  - lock request queues have TTL (`PEXPIRE NX` + `GT` = queue ttl on each queueing): the lifetime of every indexed key is bounded;
445
474
  - pruning: `ZREMRANGEBYSCORE <index> -inf <now - 1>` in every queueing pipeline (amortized, no background jobs) and in `flush_zombies`,
@@ -459,7 +488,7 @@ is client-wide: `Client` passes it to the acquirers, it is not a `lock` option),
459
488
  `redis_queued_locks.` + `lock_obtained`, `reentrant_lock_obtained`,
460
489
  `extendable_reentrant_lock_obtained`, `lock_hold_and_release`, `reentrant_lock_hold_completes`,
461
490
  `lock_obtaining_failed`, `lock_series_intermediate_lock_obtained`, `lock_series_lock_obtained`, `lock_series_lock_obtaining_failed`, `lock_series_obtained`,
462
- `lock_series_hold_and_release`, `lock_series_obtaining_failed`, `explicit_lock_release`,
491
+ `lock_series_hold_and_release`, `lock_series_obtaining_failed`, `lock_auto_extended`, `lock_auto_extension_failed`, `auto_extended_lock_lost`, `lock_hold_limit_reached`, `lock_hold_limit_extended`, `explicit_lock_release`,
463
492
  `explicit_all_locks_release`, `release_locks_of`, `explicit_read_lock_release`, `extend_lock_ttl`, `clear_dead_requests`,
464
493
  `reindex_locks`. Observability rule (`logic.md#16`): logic that changes keys is logged and instrumented, the lock
465
494
  acquirement per meaningful outcome (visitors; `lock_obtaining_failed` with the failure `result` also before a raised
@@ -478,12 +507,13 @@ its priority (`first_priority_in_queue` after `first_acq_id_in_queue`, `ahead_pr
478
507
  lock log lines (incl. lock series logs) carry `rw_mode => '...'`. RW try-lock log events: `exit__write_request_ahead`,
479
508
  `exit__read_request_ahead`, `exit__read_lock_still_obtained`, `single_process_lock_conflict__lock_upgrade`. Priorities try-lock
480
509
  log event: `dead_request_removed` (`dead_acq_id`, `dead_priority`: a dead blocking request of another band was dropped).
510
+ Lock auto extension events and logs are raised by the keeper thread through `LockKeeper::LogVisitor`/`InstrVisitor`, one per lock (`rw_mode` = held mode), with the sampling of the lock acquirement (`at` is computed by the visitor after the sampling guard).
481
511
 
482
512
  ### Errors (`errors.rb`)
483
513
 
484
514
  Global base errors per branch (`logic.md#15`): `RedisQueuedLocks::Error < StandardError` (the main
485
515
  hierarchy: `LockAlreadyObtainedError`, `LockAcquirementTimeoutError`, `LockAcquirementRetryLimitError`,
486
- `TimedLockTimeoutError`, `ConflictLockObtainError`, `SwarmError`, `ConfigError` (`ConfigNotFoundError`,
516
+ `TimedLockTimeoutError` (`LockTtlTimeBudgetIsSpentError`, `TimedBlockExceedsLockTtlError`, `TimedBlockExceedsMaxHoldTimeError`, `TimedBlockLostLockError`), `ConflictLockObtainError`, `SwarmError` (never raised now: public, kept for compatibility: `rescue` of the applications), `ConfigError` (`ConfigNotFoundError`,
487
517
  `ConfigValidationError`)), `RedisQueuedLocks::ArgumentError < ::ArgumentError` (`SwarmArgumentError`),
488
518
  `RedisQueuedLocks::Exception < ::Exception` (`@api private`, super exceptional cases only: the internal
489
519
  `*IntermediateTimeoutError`s of `Timeout.timeout` for `timeout` and `timed`; like `Timeout::ExitException`,
@@ -502,13 +532,14 @@ the connection (drops the WATCH state, reconnected on the next use) and re-raise
502
532
  |---|---|
503
533
  | `Client` | Facade; constructor injection (caller-supplied `RedisClient`); `x` returns a result hash, `x!` raises |
504
534
  | `Acquirer::*` | One module per command; stateless `class << self` functions; uniform `{ ok:, result: }` returns (public API contract; swarm element internals use bare scalars/primitives) |
505
- | `AcquireLock` | Composition via `extend` mixins; optimistic concurrency (WATCH/MULTI; asymmetric WATCH for read/write locks) + Lua only for write TTL extension/decrease; strategy options (`access_strategy`, `conflict_strategy`, `rw_mode`) |
535
+ | `AcquireLock` | Composition via `extend` mixins; optimistic concurrency (WATCH/MULTI; asymmetric WATCH for read/write locks) + Lua only for write TTL extension/decrease and the owner-checked operations of a lease (the release and the decrease, `LockKeeper` extensions: not the acquirement); strategy options (`access_strategy`, `conflict_strategy`, `rw_mode`) |
506
536
  | Log/Instr visitors | Visitor-style event hooks keep observability out of the algorithm; percent sampling via `sampling_happened?(percent)` |
507
537
  | `Logging` / `Instrument` | Null Object defaults (`VoidLogger`, `VoidNotifier`); Adapter (`instrument/active_support.rb`); duck typing (`::Logger` API, `#notify(event, payload)`) |
508
538
  | `Config` | Declarative DSL: `setting(key, default)` and `validate(key) { }` registries; access as `config['a.b']`; runtime `Client#configure` |
509
539
  | `Swarm` | Template base classes `SwarmElement::Threaded` (Thread) and `SwarmElement::Isolated` (Ractor; commands/replies via a per-element pair of `Ractor::Port`s, termination via `Ractor#monitor`). `ProbeHosts < Threaded`; `FlushZombies < Isolated` with its own connection from `RedisClientBuilder` (plain, pooled or sentinel). `Supervisor` watchdog thread restarts dead elements. |
510
540
  | `Resource` | Single source of truth for key names and identity strings |
511
- | Misc | `Data < Hash` result object; `Utilities::Lock` mutex wrapper; global `Debugger` toggle |
541
+ | `LockKeeper` | One background thread per client (lazy, revived on demand, fork-aware), `Lease` per block of code, own connection, Lua with an owner check; no supervisor: `start`/`keep` revive it |
542
+ | Misc | `Data < Hash` result object; `Utilities::Lock` `Monitor` wrapper (reentrant); global `Debugger` toggle |
512
543
 
513
544
  ---
514
545
 
@@ -517,10 +548,12 @@ the connection (drops the WATCH state, reconnected on the next use) and re-raise
517
548
  | Group | Keys (default) |
518
549
  |---|---|
519
550
  | Retry/timeouts | `retry_count` (3), `retry_delay` (200 ms), `retry_jitter` (25 ms), `try_to_lock_timeout` (10 s), `is_timed_by_default` (false) |
551
+ | Lock auto extension | `is_auto_extended_by_default` (false), `default_auto_extend_ttl` (nil: the lock ttl, ms), `default_max_hold_time_during_auto_extend` (3_600_000 ms, nil: no limit) |
520
552
  | TTLs | `default_lock_ttl` (5000 ms), `default_queue_ttl` (15 s), `dead_request_ttl` (1 day, ms) |
521
553
  | Strategies | `default_conflict_strategy` (`:wait_for_lock`), `default_access_strategy` (`:queued`), `default_lock_priority` (0, from -100 to 100 or a priority name), `lock_priorities` (priority names => Integer priorities) |
522
554
  | Batching | `lock_release_batch_size` (100), `clear_locks_of__lock_scan_size` / `__queue_scan_size` (300), `key_extraction_batch_size` (500) |
523
555
  | Lock index | `lock_index_enabled` (false; client-wide mode, config only), `lock_index_grace_period` (60_000 ms; also a `lock`/`lock!`/`lock_series`/`lock_series!`/`reindex_locks` option) |
556
+ | Lock keeper | `lock_keeper.idle_timeout` (60_000 ms), `lock_keeper.min_idle_wake_up_interval` (100 ms), `lock_keeper.extension_retry_ratio` (3), `lock_keeper.extension_batching_ratio` (10), `lock_keeper.schedule_slot` (10 ms), `lock_keeper.fiber_interruption_timeout` (1_000 ms), `lock_keeper.fiber_interruption_wait_step` (0.001 s): read when the keeper thread starts (see "Lock auto extension") |
524
557
  | Identity | `uniq_identifier` (lambda → `Resource.calc_uniq_identity`) |
525
558
  | Logging | `logger` (VoidLogger), `log_lock_try`, `log_sampling_enabled`, `log_sampling_percent` (15), `log_sampler` |
526
559
  | Instrumentation | `instrumenter` (VoidNotifier), `instr_sampling_enabled`, `instr_sampling_percent` (15), `instr_sampler` |
@@ -539,15 +572,17 @@ lib/redis_queued_locks/
539
572
  acquirer/*.rb one operation per file
540
573
  acquirer/acquire_lock/* lock algorithm mixins + visitors
541
574
  acquirer/lock_series/* lock series attempt and release mixins + visitors
575
+ lock_keeper.rb, lock_keeper/* lock auto extension: keeper thread, leases, visitors
542
576
  swarm.rb, swarm/* supervisor, swarm elements, zombie logic, redis client builder
543
577
  logging/, instrument/ void defaults, samplers, ActiveSupport adapter
544
578
  resource.rb keys and identities
545
579
  data.rb, errors.rb, utilities.rb, utilities/lock.rb, debugger/, version.rb
546
- sig/ RBS mirror of lib/ + sig/vendor stubs (redis_client, active_support, semantic_logger)
547
- spec/ redis_queued_locks_spec.rb (~5.6k lines, integration: shared examples run with both lock lookup modes), redis_queued_locks/config_spec.rb (Redis-free: `Config#[]` RBS table == `setting` registry), spec_helper.rb, setup_simplecov.rb, support/parallel_runner.rb (the `rake rspec:parallel` runner, not a spec)
580
+ sig/ RBS mirror of lib/ + sig/vendor stubs (redis_client, active_support, semantic_logger), manifest.yml (dependencies of the signatures)
581
+ spec/ redis_queued_locks_spec.rb (~10.5k lines, integration: shared examples run with both lock lookup modes), redis_queued_locks/config_spec.rb (Redis-free: `Config#[]` RBS table == `setting` registry), spec_helper.rb, setup_simplecov.rb, support/parallel_runner.rb (the `rake rspec:parallel` runner, not a spec)
548
582
  .github/workflows/ tests, lint, typecheck-static, typecheck-runtime
583
+ .claude/ this overview, rules/*.md (path-scoped rules), skills/rql-code-review (review of the changes), skills/rql-project-full-review (full audit of the repository, on request)
549
584
  bin/console, bin/setup dev scripts
550
- Rakefile, Steepfile, rbs_collection.yaml
585
+ Rakefile, Steepfile, rbs_collection.yaml, .rubocop.yml, .rubocop.rbs.yml
551
586
  ```
552
587
 
553
588
  ---
@@ -555,8 +590,8 @@ Rakefile, Steepfile, rbs_collection.yaml
555
590
  ## 5. Technology stack
556
591
 
557
592
  ### Runtime
558
- - Ruby >= 4.0; stdlib `timeout`, `securerandom`, `logger`; Thread, Fiber, Ractor, Mutex
559
- - Redis server: WATCH/MULTI, EVAL (Lua), ZSET, HASH, PTTL/PEXPIRE (NX/GT: Redis >= 7), SCAN/ZSCAN
593
+ - Ruby >= 4.0; stdlib `timeout`, `securerandom`, `logger`, `monitor`; Thread, Fiber, Ractor, Monitor
594
+ - Redis server `>= 7`, `~> 8.x`, protocol RESP3 (README "Requirements"): WATCH/MULTI, EVAL (Lua), ZSET, HASH, PTTL/PEXPIRE (NX/GT: Redis >= 7), SCAN/ZSCAN
560
595
  - `redis-client ~> 0.20`
561
596
  - Optional, duck-typed: any `::Logger`-compatible logger; any `#notify(event, payload)` instrumenter (ActiveSupport adapter included; SemanticLogger has only an RBS stub)
562
597
 
@@ -572,16 +607,18 @@ Rakefile, Steepfile, rbs_collection.yaml
572
607
  - rake, bundler, pry, pry-doc, reline, activesupport 8.1
573
608
 
574
609
  ### Rake tasks
575
- `rspec` (default), `rspec:parallel` (`spec/support/parallel_runner.rb`, the `Rakefile` only declares the task: the specs in `WORKERS` processes, ~1 min instead of ~6: each worker gets its own pair of Redis databases via `RQL_SPEC_DB_OFFSET` = worker index * 2, prepended to `RedisClient::Config::Common#initialize` in `spec_helper.rb` (the library, swarm and Ractor clients included; after the URL is resolved: the database of a `url:` gets the offset too); examples listed by `rspec --dry-run` and distributed by the durations of the previous runs (`tmp/rspec_parallel/durations.json`, the longest first to the least loaded worker); per-worker logs/JSON in `tmp/rspec_parallel/` (the worker files of the previous run are deleted before the workers start: a worker that dies before RSpec writes its JSON output is reported as broken, never with stale results); coverage: each worker stores only its SimpleCov result in `coverage/parallel/worker-<n>` (`rspec:worker:<n>` command names, no report), the task collates one report into `coverage/` after all workers (`SimpleCov.collate`) and drops the collated resultset (later `rspec` runs don't merge it); the environment is passed to the workers: the RBS runtime checks and `RSPEC_RETRY_RETRY_COUNT` work as with `rspec`), `rubocop` (runs `rubocop:ruby` and `rubocop:rbs`, fails if either fails), `steep:check`, plus bundler gem tasks (`build`, `release`, ...).
610
+ `rspec` (default), `rspec:parallel` (`spec/support/parallel_runner.rb`, the `Rakefile` only declares the task, optional `rspec:parallel[<paths>]`: the specs in `WORKERS` processes, ~1 min instead of ~6: each worker gets its own pair of Redis databases via `RQL_SPEC_DB_OFFSET` = worker index * 2, prepended to `RedisClient::Config::Common#initialize` in `spec_helper.rb` (the library, swarm and Ractor clients included; after the URL is resolved: the database of a `url:` gets the offset too); examples listed by `rspec --dry-run` and distributed by the durations of the previous runs (`tmp/rspec_parallel/durations.json`, `durations-rbs.json` under the RBS runtime checks; the longest first to the least loaded worker, examples without a recorded duration count as the median one); per-worker logs/JSON in `tmp/rspec_parallel/` (the worker files of the previous run are deleted before the workers start: a worker that dies before RSpec writes its JSON output is reported as broken, never with stale results); coverage: each worker stores only its SimpleCov result in `coverage/parallel/worker-<n>` (`rspec:worker:<n>` command names, no report), the task collates one report into `coverage/` after all workers (`SimpleCov.collate`) and drops the collated resultset (later `rspec` runs don't merge it); the environment is passed to the workers: the RBS runtime checks and `RSPEC_RETRY_RETRY_COUNT` work as with `rspec`), `rubocop` (runs `rubocop:ruby` and `rubocop:rbs`, fails if either fails), `steep:check`, plus bundler gem tasks (`build`, `release`, ...).
611
+
612
+ ### CI (GitHub Actions, ubuntu-latest, Ruby 4.0, on every push except gem docs-only pushes)
576
613
 
577
- ### CI (GitHub Actions, ubuntu-latest, Ruby 4.0, on every push)
614
+ All workflows skip a push that changes only the gem documentation files (`paths-ignore`: `README.md`, `CHANGELOG.md`, `CODE_OF_CONDUCT.md`, `LICENSE.txt`); a push with any other file runs all of them. `master` has no required status checks, so a skipped run never blocks a merge (required checks would need a workaround: a skipped workflow stays pending).
578
615
 
579
616
  | Workflow | Command |
580
617
  |---|---|
581
- | tests | `bundle exec rake rspec:parallel` (with a Redis service; 4 workers on the 4-core runner; `tmp/rspec_parallel/durations.json` restored/saved with `actions/cache` (a new key per run, `restore-keys` prefix) to balance the workers; the worker logs are uploaded as an artifact on failure) |
618
+ | tests | `bundle exec rake rspec:parallel` (with a Redis service; 4 workers on the 4-core runner; `tmp/rspec_parallel/durations.json` restored/saved with `actions/cache` (a new key per run, `restore-keys` prefix) to balance the workers; the worker logs are uploaded as an artifact on failure; `timeout-minutes: 15`: a hung example fails the job instead of holding the runner for the default 6 hours) |
582
619
  | lint | `bundle exec rake rubocop` (precompiled native gems: no `BUNDLE_FORCE_RUBY_PLATFORM`, a rubydex 0.4.1 source build on the runner flags constants as `@deprecated` and breaks `Lint/DeprecatedReference`) |
583
620
  | typecheck-static | `bundle exec rbs collection install && bundle exec rake steep:check -j 10` |
584
- | typecheck-runtime | `RBS_TEST_RAISE=true RUBYOPT='-rbundler/setup -rrbs/test/setup' RBS_TEST_OPT='-I sig' RBS_TEST_TARGET='RedisQueuedLocks::*' RBS_TEST_SKIP='::RedisQueuedLocks::Swarm::FlushZombies,::RedisQueuedLocks::Swarm::SwarmElement::Isolated,::RedisQueuedLocks::Swarm::RedisClientBuilder' bundle exec rspec` (blocking; serial on purpose: the RBS hooks keep a worker on a CPU core, and parallel workers on the runner (4 vCPU = 2 physical cores) starved the timing-sensitive examples: Redis connect timeouts with 4 workers, swarm flush waits with 2; locally `rake rspec:parallel` works for the RBS checks; Ractor-executed methods are skipped: `RBS_TEST_SKIP` + `%a{rbs:test:skip}` in `resource.rbs`/`utilities.rbs`) |
621
+ | typecheck-runtime | `bundle exec rbs collection install && RBS_TEST_RAISE=true RUBYOPT='-rbundler/setup -rrbs/test/setup' RBS_TEST_OPT='-I sig' RBS_TEST_LOGLEVEL=error RBS_TEST_TARGET='RedisQueuedLocks::*' RBS_TEST_SKIP='::RedisQueuedLocks::Swarm::FlushZombies,::RedisQueuedLocks::Swarm::SwarmElement::Isolated,::RedisQueuedLocks::Swarm::RedisClientBuilder' bundle exec rake rspec:parallel` (blocking; parallel as tests: 4 workers, `tmp/rspec_parallel/durations-rbs.json` cached with its own `rspec-rbs-durations-` keys, the worker logs uploaded on failure; `RUBY_TCP_NO_FAST_FALLBACK=1` in the job env: no resolver threads per Redis connection (on a shared CPU they stretched the connection storm of the specs past its connect timeout and raced the closed resolution pipe, `Thread.abort_on_exception` turns either into a dead worker); serial until the runtime checks got cheaper (`Config#config_state` skip, 10 rounds of the sampling examples): the RBS hooks kept the workers on the CPU, and parallel workers on the runner (4 vCPU = 2 physical cores) starved the timing-sensitive examples: Redis connect timeouts with 4 workers, swarm flush waits with 2; Ractor-executed methods are skipped: `RBS_TEST_SKIP` + `%a{rbs:test:skip}` in `resource.rbs`/`utilities.rbs`; `Config#config_state` is skipped for speed (`config.rbs`, `type-checking.md#15`); gems come from the `bundler-cache` of `ruby/setup-ruby` as in the other jobs; `timeout-minutes: 20`) |
585
622
 
586
623
  ---
587
624
 
@@ -593,6 +630,6 @@ Rakefile, Steepfile, rbs_collection.yaml
593
630
  - New operation: new `Acquirer::*` module, thin `Client` method (+ `!` variant if it should raise), RBS, spec.
594
631
  - New config option: `setting` (+ `validate`) in `config.rb` + the typed `Config#[]` overload line in `sig/redis_queued_locks/config.rbs`, read via `config['key']`, document defaults.
595
632
  - Development gems go in `Gemfile` (`Gemspec/DevelopmentDependencies: Gemfile`), not the gemspec.
596
- - This overview and `.claude/rules/*.md` are updated in the same change as the code (keys, options, results, events, algorithm steps, limitations); README and CHANGELOG `[Unreleased]` for user-visible behavior (log keys and instrumentation payloads: README `## Logging` / `### Instrumentation Events`); CHANGELOG entries are compact, subject-level changes only (`.claude/rules/changelog.md`).
597
- - Temporary debt: rspec-retry, disabled coverage minimum.
633
+ - This overview and `.claude/rules/*.md` are updated in the same change as the code (keys, options, results, events, algorithm steps, limitations); README and CHANGELOG `[Unreleased]` for user-visible behavior (log keys and instrumentation payloads: README `## Logging` / `### Instrumentation Events`; the full README sync list: `.claude/rules/readme.md`); CHANGELOG entries are compact, subject-level changes only (`.claude/rules/changelog.md`).
634
+ - Temporary debt: rspec-retry, disabled coverage minimum, the swarm README docs (pending rework, `readme.md#9`: the reserved anchors, the `swarm.*` keys out of `### Configuration`, no swarm method sections; all these exceptions are removed by the rework).
598
635
  - Specs (`spec/**/*_spec.rb`) are not ideal and will be totally reworked (header `NOTE` of `spec/redis_queued_locks_spec.rb`): until then any coding principle may be broken there; code review checks only that the library behavior is covered and that changed expectations are correct (`.claude/skills/rql-code-review`).
@@ -16,7 +16,7 @@ paths:
16
16
  - `AcquireLock` and `LockSeries` are the lock acquisition core, not operation modules of this list: `LockSeries` reuses the `AcquireLock` mixins (`TryToLockSeries` includes `TryToLock`, `LockSeries` extends `DelayExecution` and `YieldExpire`) and never calls `AcquireLock.acquire_lock`.
17
17
  - Known debt (don't copy): `AcquireLock::WithAcqTimeout` calls `LockInfo.lock_info` / `QueueInfo.queue_info` for detailed timeout errors (its TODO asks to make `AcquireLock` independent of them).
18
18
  - Known limitation (kept by the user's decision): `ReleaseLocksOf` (and `FlushZombies`) check the lock owner (`HMGET`) and delete the lock (`DEL`) in two round trips without `WATCH`: a lock re-acquired in between by another acquirer can be deleted.
19
- - Known limitation (kept by the user's decision, documented in README `#lock`): `YieldExpire` releases the write lock (`EXPIRE 0`) and decreases its ttl (Lua) without an owner check: a block (without `timed`) longer than the lock ttl can delete/shorten the lock of another acquirer. Read lock release/decrease is per acquirer (owner-safe).
19
+ - Known limitation (kept by the user's decision, documented in README `#lock`): `YieldExpire` releases the write lock (`EXPIRE 0`) and decreases its ttl (Lua) without an owner check: a block (without `timed`) longer than the lock ttl can delete/shorten the lock of another acquirer. Read lock release/decrease is per acquirer (owner-safe). A block with `auto_extend` is owner-safe (`RELEASE_OWN_LOCK`, `DECREASE_OWN_LOCK_PTTL`: losing a lock is a normal case of this mode).
20
20
  - **Signatures** (see `arguments.md` for the design rationale):
21
21
  - Read-only queries: few positional args `(redis_client, lock_name)`; collection queries use keywords `(redis_client, scan_size:, with_info:)`.
22
22
  - Mutating operations: long positional lists ending with the fixed observability tail
@@ -51,7 +51,7 @@ paths:
51
51
  - the mode is client-wide (`config['lock_index_enabled']` read by `Client`, never a per-call keyword): the hot path gets it as `lock_index_enabled` (`AcquireLock` required keyword → `TryToLock` positional before `lock_index_grace_period`; `ExtendLockTTL`/`ReleaseLock` positional after the lock data); every lock index command is a conditional **tail** of its pipeline/transaction (`return unless lock_index_enabled` at the end of `queue_lock_request`, `if lock_index_enabled` around the last `MULTI` command), so reply positions never depend on the mode (only the reentrant write extension checks `result.size == (lock_index_enabled ? 5 : 4)`);
52
52
  - a command that **creates** a lock key is followed by `ZADD <index> GT <now + ttl + grace> <lock_name>` in the same pipeline/transaction, **after** the key command: the request queue `ZADD NX` in the queueing pipeline (queue ttl), the write lock `HSET` / registry `ZADD` + reader data at the end of the obtaining `MULTI` (lock ttl); the obtaining `MULTI` must index the lock itself: `unlock`/`clear_locks` can drop the name between the queueing and the obtaining (`EXPIRE`/`DEL` of an absent key does not abort the attempt's `WATCH`);
53
53
  - a name is **removed** only together with the deletion of all its indexed keys in one `MULTI` (`ReleaseLock`: `ZREM` in the release transaction; `ReleaseAllLocks`: `DEL` of the batch keys + `ZREM` of the batch names); operations that can leave keys of a name (`ReleaseLocksOf`, `YieldExpire` releases, `FlushZombies`) never remove names;
54
- - a command that **extends** a lock key is followed by `ZADD <index> XX INCR <ms> <lock_name>` in the same transaction (`XX`: names without an entry are not indexed with a wrong score); ttl decreases and releases never touch the index (the bound stays an upper bound);
54
+ - a command that **extends** a lock key is followed by `ZADD <index> XX INCR <ms> <lock_name>` in the same transaction (`XX`: names without an entry are not indexed with a wrong score); the lock keeper sets an absolute lifetime (it does not add time): `ZADD <index> XX GT <now + extension ttl + grace> <lock_name>` inside its scripts, after the owner check; ttl decreases and releases never touch the index (the bound stays an upper bound);
55
55
  - lock request queues get `PEXPIRE NX` + `PEXPIRE GT` with the queue ttl (ms, `(queue_ttl * 1_000).ceil`) on each queueing: every indexed key has a bounded lifetime;
56
56
  - pruning is `ZREMRANGEBYSCORE <index> -inf <lock_index_time - 1>` (each queueing, `flush_zombies`, `clear_locks`, `clear_dead_requests`); keys written without the index (older versions, raw writes) are adopted by `ReindexLocks` (SCAN pass, `PEXPIRE NX` for queues, `PTTL` => `ZADD GT`).
57
57
  - **Lock request priorities**: queue scores are the enqueue time shifted by the priority band (`Resource.calc_initial_acquirer_position(priority)` = `ts - priority * Resource::LOCK_PRIORITY_BAND`, 2**32 s; priority `Resource::MIN_LOCK_PRIORITY`..`MAX_LOCK_PRIORITY`, -100..100, or a priority name of `config['lock_priorities']` resolved to its Integer in `AcquireLock` Step 0.1 and `LockSeries` Step 0.1: code after the resolution never sees Symbols). Never prune a lock queue with one `-inf .. now - ttl` range (it drops alive high-priority requests and keeps dead low-priority ones): prune a band with `Resource.lock_priority_band_floor(p)` .. `Resource.lock_priority_band_dead_score(dead_score, p)` (`TryToLock#pipeline_dead_requests_removal`, `ClearDeadRequests.drop_dead_requests` / `drop_dead_requests_by_priority`); full clears (`-inf .. +inf`) and member-based removals (`ZREM`) are band-independent. Never enumerate the priority range per attempt or per queue (the cost must not depend on it): prune the bands found in the data (decode the band and the liveness of a score with `Resource.lock_request_priority(score)` and `lock_priority_band_dead_score`): the attempt prunes its own band and the bands of the dead blocking requests (`TryToLock#drop_dead_requests_ahead`; a lock series: `TryToLockSeries#drop_series_dead_requests_ahead`, one round trip for all its locks), `ClearDeadRequests` the bands whose first request is dead (all requests of the batch queues are read; `by_priority: true`: a walk over the bands reads only the first request of each band, `ZRANGE <queue> <bound> +inf BYSCORE LIMIT 0 1`, one round trip per band of the batch queue with the most bands + 1, the dead bands are pruned by the next round trip after its reads, `drop_dead_requests_by_priority`; every walk step must make progress: an exclusive bound when the next band edge rounds to the position). Decode priorities with `Resource.lock_request_priority(score)` (info results); the cross-mode `(score, acq_id)` comparison works on shifted scores as is. Infinite positions (manual writes, never written by RQL) are out of all bands: the decoding maps `-inf`/`+inf` to `MAX_LOCK_PRIORITY`/`MIN_LOCK_PRIORITY` (never `Float#floor` of an infinity: `FloatDomainError`); a request at `-inf` is always dead and no band range covers it: it is dropped by its position (`ZREMRANGEBYSCORE <queue> -inf -inf`: `drop_dead_requests_ahead` for a blocking one, `ClearDeadRequests` for the first ones of a queue); a request at `+inf` is never dead.
@@ -63,8 +63,11 @@ paths:
63
63
  - Failure modes are Symbols (`:fail_fast_no_try`, `:fail_fast_after_try`, `:conflict_dead_lock`, `:conflict_lock_upgrade`, ...); exceptions are raised only when `raise_errors` is true, with a message naming the lock key / acquirer id.
64
64
  - `TryToLock` pre-check (retries: `acquire_lock` passes `retry_attempt = tries > 0`, and `fail_fast` attempts): `precheck_lock` reads the lock state with the same pipeline (`pipeline_lock_state`; with the queueing for retries, without it for `fail_fast`) without `WATCH`; it returns the failure result (`lock_obstacle` / `:fail_fast_no_try`) and logs the same events as the failed attempt in the same order (the dead requests dropped by Step 2.2 after the queueing events: `drop_dead_requests_ahead` returns them, `log_dropped_requests` logs them in both paths; a pre-check that does not fail logs them before the attempt), or `nil` to continue the attempt (lock obtainable or a same-process conflict). The pre-check never obtains the lock: mutual exclusion stays with `WATCH`/`MULTI`.
65
65
  - `TryToLock` attempt (both modes): `multi(watch:)` (write: `[lock_key, lock_readers_key]`, read: `[lock_key]`) → one pipelined state read (`HGET acq_id`, `TIME`, own reader score, longest reader: write requests only, the write-only tail of the pipeline) → same-process conflict detection (`sp_conflict_rw_mode` = held `:write`/`:read`) → the lock request queueing in one pipelined round trip (`queue_lock_request`: prune dead requests of the request's priority band in **both** queues (before `ZADD NX`: the old dead position of a requeued request is dropped before its new position is added; the reverse order keeps the old position with `NX` and drops it: the request is missing in the queue for the attempt) → `ZADD NX` into the queue of the requested mode (the position is shifted by the priority band) → queue heads of both queues (`WITHSCORES`) → (the enabled lock index only) request queue `PEXPIRE NX`+`GT` → lock index `ZADD GT` → lock index pruning (5 replies, 9 with the lock index; new commands go to the end, replies after the queue heads are not read); eager queueing (`:wait_for_lock`/`:dead_locking` without `fail_fast`) sends these commands in the state pipeline right after its head, so `lock {}` = 4 round trips; the queueing log events are still emitted in the classic branch in the same order) → Step 2.2 (priorities, `:queued`, also in the pre-check, before the obstacle decision): the dead blocking requests of other bands (the write queue head for writers and the earlier opposite-mode request, decoded from their scores by `dead_request_priority`) are dropped with their bands in both queues and both heads are re-read in one more round trip (`drop_dead_requests_ahead`: one or two bands per round trip, the heads are read from the end of the pipeline, up to `MAX_DEAD_REQUEST_REMOVALS` round trips, `try_lock.dead_request_removed` log per dropped request, written by the caller (`log_dropped_requests`) after the queueing events; no round trip while the blocking requests are alive; a live write queue head stops the removal) (`:queued`: write must be first in its queue; any mode waits for an earlier `(score, acq_id)` request of the opposite mode) → lock state (write held → `:lock_is_still_acquired`; live readers for write / own live read for read → `:read_lock_is_still_acquired`) → MULTI (write: `ZREM` + `HSET` + `PEXPIRE` (+ lock index `ZADD GT`); read: `ZREM` + prune registry + `ZADD expiry` + registry `PEXPIRE NX`+`GT` + reader data `DEL`+`HSET`+`PEXPIRE` (+ lock index `ZADD GT`)). With the enabled lock index the `:extendable_work_through` extension `MULTI` ends with the lock index `ZADD XX INCR` (write: 4 replies, 5 with the lock index: `result.size == (lock_index_enabled ? 5 : 4)`).
66
+ - Interrupted obtaining: `try_to_lock` sets `acq_process[:lock_obtaining_sent]` right before the obtaining `EXEC` is sent (dropped at the start of each attempt and after a failed one); the timeout callback of `with_acq_timeout` (`acq_dequeue`) returns `true` for an already obtained lock (no timeout error) and otherwise releases this lock owner-checked (`DequeueFromLockQueue#release_unconfirmed_lock`) before the dequeue: an acquirement that reports a failure never keeps a lock (the series: `drop_failed_lock_series`).
66
67
  - The try result carries internal `rw_mode` (the **held** lock mode); `acquire_lock` stores it as `acq_process[:held_rw_mode]` and passes it to `yield_expire`, which releases/decreases the held lock. The public `lock` result shape does not include it.
67
68
  - Read lock data (`rql:lock_reader:<name>:<acq_id>`) uses the write-lock field format without `acq_id`/`hst_id` (`ts`, `ini_ttl`, meta, `spc_*`: both ids are derived from the acquirer id, `LockInfo.read_lock_info`/`Locks.read_lock_info` put them first in each reader and still accept older data that contains them) and the read lock TTL; it is a data carrier only (writers never read it). Its key (`read_lock_key`) is built only for read lock requests (`nil` for write requests: they never hold read locks).
69
+ - `timed` budget (`AcquireLock`, `LockSeries`, `YieldExpire#timed_block_budget`): `ttl - ttl_shift` (with `auto_extend`: `max_hold_time_during_auto_extend - ttl_shift`, `nil` = no limit), `ttl_shift` = time from `acq_process[:try_start_time]` (the start of the successful attempt: the ttl starts later: write: `EXEC`, read: `TIME` of the lock state read) + `REDIS_TIMESHIFT_ERROR` (a margin: it always shortens the budget); no budget left (`0.0`) => `yield_with_timeout` does not invoke the block (`Timeout.timeout(0)` means no timeout): `LockTtlTimeBudgetIsSpentError`; a block that exceeds the budget: `TimedBlockExceedsLockTtlError` (`auto_extend`: `TimedBlockExceedsMaxHoldTimeError`), a lost auto extended lock: `TimedBlockLostLockError` (all are `TimedLockTimeoutError` subclasses). With `auto_extend` in an interruptible block (a blocking fiber: `Thread#raise`; a non-blocking fiber whose scheduler has `Fiber::Scheduler#fiber_interrupt`: through it) the budget decides only the invocation: the keeper interrupts the block at the hold limit (movable by `LockLease#hold_for`), no `Timeout`; a non-blocking fiber without such a scheduler keeps the `Timeout` of the budget. `yield_with_timeout` passes the interruption that has come to `forget` (it waits for a pending fiber interruption that has not come: never let the internal error reach the code after the block).
70
+ - Auto extension (overview "Lock auto extension"): `lock_keeper.keep` is called inside the `ensure` scope of the release (`yield_expire`, `lock_series`), `lock_keeper.forget` runs before the release; a block with parameters gets its `RedisQueuedLocks::LockKeeper::LockLease` (built right after `keep`, passed through both yield paths: `yield_expire`/`yield_lock_series` and `yield_with_timeout`), a block without parameters gets nothing; a change of the lock lifetime logic or a new key of a lock is checked against the extension scripts (`LockKeeper::EXTEND_WRITE_LOCK`, `EXTEND_READ_LOCK`); never derive the tick schedule from the reply `PTTL`. An aborted transaction of a reentrant attempt is `:reentrant_lock_is_changed_during_extension`, not `:lock_is_acquired_during_acquire_race`: the held lock can be changed by a tick, `acquire_lock`/`lock_series` repeat the attempt at once (Step 2.1.b, `MAX_REENTRANT_EXTENSION_RETRIES`).
68
71
  - Timing via monotonic `clock_gettime` (microseconds); wall time only for `at:`/`ts` fields.
69
72
  - **LockSeries** (`lock_series.rb`, `lock_series/try_to_lock_series.rb`, `lock_series/release_lock_series.rb`; overview "Lock series"):
70
73
  - The attempt is the single lock attempt for N locks, built from the shared `TryToLock` helpers: lock state and queueing commands (`pipeline_lock_state`, `queue_lock_request`), decisions (`same_process_conflict_status`, `find_opposite_request_ahead`, `lock_obstacle`, `find_dead_requests_ahead`, `pipeline_dead_requests_ahead_removal`), obtaining and reentrant commands (`transact_*`). A change of these helpers applies to both attempts; a change of the single lock attempt flow is checked against `try_to_lock_series`/`precheck_lock_series` (two copies of the flow, not of the commands).
@@ -93,7 +96,7 @@ paths:
93
96
  - every release/cleanup/info/zombie path covers write lock, readers registry, reader data and both queues;
94
97
  - registry/reader-data TTLs: `PEXPIRE NX` + `PEXPIRE GT` pair to keep max TTL (`GT` alone never sets TTL on a key without one);
95
98
  - keep write-only result shapes unchanged; add read keys/fields only when read data exists;
96
- - lock index (the enabled lock index only, `if lock_index_enabled`): every key-creating command is followed by the index `ZADD GT` (the obtaining `MULTI` too), every extension by `ZADD XX INCR`, names are removed only with all their keys in one `MULTI` (see "Lock index" above); the disabled lock index sends no lock index command.
99
+ - lock index (the enabled lock index only, `if lock_index_enabled`): every key-creating command is followed by the index `ZADD GT` (the obtaining `MULTI` too), every extension by `ZADD XX INCR` (the absolute extensions of the lock keeper: `ZADD XX GT`), names are removed only with all their keys in one `MULTI` (see "Lock index" above); the disabled lock index sends no lock index command.
97
100
  13. Values used only for logs (e.g. `HGETALL` of lock data) are fetched only when the log is enabled (`(log_sampled && log_lock_try) ? ... : NO_LOCK_DATA`, a shared frozen hash instead of a new `{}` per attempt): visitor arguments are evaluated before the visitor's guard.
98
101
  14. Keep operation modules independent (see "Independence of operation modules"; the acquisition core, `AcquireLock` and `LockSeries`, is exempt): never call another operation module's function (public or private) or reference its RBS types from an operation module. When similar logic is needed, duplicate it inside the module (same method name and shape as the original copy, with a `NOTE` that it is duplicated on purpose) or move a pure, data-only helper (key names, id parsing, time conversion) to `Resource` / `Utilities`. Helpers used by one module stay `private`. When changing logic that has copies, update every copy in the same change.
99
102
  15. Pipelines/transactions whose replies are read by position (`lock_state[N]`, `result[N]`): document the reply positions next to the commands (`NOTE: (pipeline layout)`). Conditionally sent commands (e.g. `... unless read_mode`) form a tail after all unconditional commands; read their replies only under the same condition (a command appended after a conditional tail gets a mode-dependent position and its reply is read as another command's reply). Insert new commands before the conditional tail and update the positions, the reply reading, the position constants and the layout spec in the same change. `TryToLock` lock state pipeline (`pipeline_lock_state`, shared by the attempt and the pre-check): head `[LOCK_STATE_OBTAINER_REPLY, LOCK_STATE_REDIS_TIME_REPLY, LOCK_STATE_OWN_READ_LOCK_REPLY]`, queueing commands at `LOCK_STATE_QUEUE_REPLIES_AT` (`queue_lock_request` replies, used ones at `QUEUE_HEAD_REPLY`/`OPPOSITE_QUEUE_HEAD_REPLY`), the write-only tail last (`lock_state.last`); read replies only by these constants (both reply readers: `try_to_lock` Step 0.1 and `precheck_lock`); the obstacle decision and its exit logs are shared too (`find_opposite_request_ahead`, `lock_obstacle`, `log_lock_obstacle`, the log-only priority decoding `logged_request_priority`): change them in one place; spec `lock state pipeline layout` records the pipelines of both modes with and without eager queueing and fails on a broken layout or stale position constants.
@@ -50,12 +50,12 @@ This is a deliberate framework-level decision, **not** something to refactor int
50
50
  2. New public option: add it as an explicit keyword to **every** affected `Client` method (`x` and `x!`, e.g. `lock` and `lock!`), with the default taken from `config['...']` (add the `setting` + `validate` first) or a literal for per-call-only flags (`raise_errors: false`, `meta: nil`).
51
51
  3. Forward it explicitly by name through every layer using shorthand (`new_option:`); never forward via `**kwargs`, `...`, or `method(__method__).parameters` tricks.
52
52
  4. Keep defaults only at the public boundary (`Client`); internal functions take required keywords/positionals with no defaults so a missed forward fails loudly.
53
- 5. Internal positional lists: append new params in the established order (subject → domain data → observability tail `logger, instrumenter, instrument, log_sampling_*, log_sample_this, instr_sampling_*, instr_sample_this`) and update every call site and the RBS signature in the same change. Lock key params keep this order: `lock_key, rw_mode, lock_key_queue, read_lock_key_queue, lock_readers_key, read_lock_key, lock_name, acquirer_id, host_id, acquirer_position, priority, ...` (`lock_name` is the lock index member; `acquirer_position` is the priority-shifted queue score, `priority` its band; queueing helpers take `acquirer_position, priority` right after the queue keys; `yield_expire`: `lock_key, lock_readers_key, read_lock_key, rw_mode, acquirer_id, ...`); TTL params: `ttl, queue_ttl, lock_index_enabled, lock_index_grace_period`; compute keys once in `acquire_lock` and pass them down (`read_lock_key` is `nil` for write lock requests). Queueing helpers (`queue_lock_request`, `pipeline_lock_state`) take the lock index params last: `lock_name, queue_ttl, lock_index_enabled, lock_index_grace_period`. Lock-iterating modules take `lock_index_enabled` after their domain data (`scan_size:`/`with_info:` keywords + `lock_index_enabled:`; positional lists: right after the domain data (batch sizes, `dead_ttl`, `by_priority`), before the observability tail; swarm functions: last).
53
+ 5. Internal positional lists: append new params in the established order (subject → domain data → observability tail `logger, instrumenter, instrument, log_sampling_*, log_sample_this, instr_sampling_*, instr_sample_this`) and update every call site and the RBS signature in the same change. Lock key params keep this order: `lock_key, rw_mode, lock_key_queue, read_lock_key_queue, lock_readers_key, read_lock_key, lock_name, acquirer_id, host_id, acquirer_position, priority, ...` (`lock_name` is the lock index member; `acquirer_position` is the priority-shifted queue score, `priority` its band; queueing helpers take `acquirer_position, priority` right after the queue keys; `yield_expire`: `lock_key, lock_readers_key, read_lock_key, rw_mode, lock_name, acquirer_id, ...`, its auto extension tail after `should_decrease`: `lock_keeper, auto_extend, auto_extend_ttl, max_hold_time_during_auto_extend, try_start_time, instrumenter, instrument`); TTL params: `ttl, queue_ttl, lock_index_enabled, lock_index_grace_period`; compute keys once in `acquire_lock` and pass them down (`read_lock_key` is `nil` for write lock requests). Queueing helpers (`queue_lock_request`, `pipeline_lock_state`) take the lock index params last: `lock_name, queue_ttl, lock_index_enabled, lock_index_grace_period`. Lock-iterating modules take `lock_index_enabled` after their domain data (`scan_size:`/`with_info:` keywords + `lock_index_enabled:`; positional lists: right after the domain data (batch sizes, `dead_ttl`, `by_priority`), before the observability tail; swarm functions: last).
54
54
  6. Document each new option with its own `@option`/`@param` YARD line (type, meaning, default source) and add it to the RBS method signature as a named param/keyword.
55
55
  7. Keep hot-path code allocation-light: no per-call wrapper objects, no hash merging, no splats to build args, no `tap`/closures purely for argument plumbing; prefer passing existing locals.
56
56
  8. Silence length cops locally (`# rubocop:disable Metrics/MethodLength`) rather than shortening signatures; `Metrics/ParameterLists` is disabled project-wide on purpose.
57
57
  9. Client-wide modes are not per-call options: `config['lock_index_enabled']` is read inside the `Client` (and `Swarm`) method bodies and forwarded by name to the acquirers (`lock_index_enabled: config['lock_index_enabled']` / positional `config['lock_index_enabled']`), never added as a keyword of `lock`/`locks`/`clear_locks`/...: one call in another mode would break the lock index invariant (all lock acquirements of a client must maintain the index when its operations read it).
58
- 10. `lock`-family options exist in four `Client` methods: `lock`, `lock!`, `lock_series`, `lock_series!` (`AcquireLock.acquire_lock` and `LockSeries.lock_series` have their own keyword lists, with the same validations: duplicated on purpose). A new lock option is added to all of them; `lock_series` keeps one value for the whole series (e.g. `rw_mode`, `priority`). Client-wide registries are read from `config` inside these methods and forwarded as internal keywords, never public keywords (`lock_priorities: config['lock_priorities']`, the priority names: `lock` and `lock_series` pass it, `lock!`/`lock_series!` delegate to them).
58
+ 10. `lock`-family options exist in four `Client` methods: `lock`, `lock!`, `lock_series`, `lock_series!` (`AcquireLock.acquire_lock` and `LockSeries.lock_series` have their own keyword lists, with the same validations: duplicated on purpose). A new lock option is added to all of them; `lock_series` keeps one value for the whole series (e.g. `rw_mode`, `priority`). Client-wide registries are read from `config` inside these methods and forwarded as internal keywords, never public keywords (`lock_priorities: config['lock_priorities']`, the priority names: `lock` and `lock_series` pass it, `lock!`/`lock_series!` delegate to them); the same for the client-wide lock keeper (`lock_keeper:`, the `Client#lock_keeper` object).
59
59
 
60
60
  ## Recommendations (proposed, not yet project policy)
61
61
  1. For new internal functions with many same-typed params (e.g. several Integers/Booleans in a row), consider required keywords instead of positionals to prevent misordering; keep the list flat and explicit.
data/.claude/rules/git.md CHANGED
@@ -28,7 +28,7 @@ Applies to every commit Claude makes in this repository (no `paths:` scope: alwa
28
28
 
29
29
  **When to commit**
30
30
  7. Never commit on your own. When a step with changes reaches completion, ask the user for permission to commit and wait for the answer:
31
- - completion = the feature/functionality required by the prompt is fully implemented (code, RBS, specs, README/CHANGELOG, `.claude/project-overview.md` and rules kept in sync) and checks are green: the touched examples and the full suite (`bundle exec rake rspec:parallel` by default, the serial `bundle exec rake rspec` when the change needs a check in one process: `tests.md#1`), `bundle exec rake rubocop`, `bundle exec rake steep:check` (no `ERROR`/`FATAL` lines); changes without code (docs, `.claude` rules) need no test run;
31
+ - completion = the feature/functionality required by the prompt is fully implemented (code, RBS, specs, README/CHANGELOG, `.claude/project-overview.md` and rules kept in sync) and checks are green: the touched examples and the full suite (`bundle exec rake rspec:parallel` by default, the serial `bundle exec rake rspec` when the change needs a check in one process: `tests.md#1`), `bundle exec rake rubocop`, `bundle exec rake steep:check` (no `ERROR`/`FATAL` lines); changes without code (docs, `.claude` rules) need no test run; a change of the gem docs files only (`README.md`, `CHANGELOG.md`, `CODE_OF_CONDUCT.md`, `LICENSE.txt`, the `paths-ignore` list of `.github/workflows/*.yml`: keep both lists equal) also needs no wait for the GitHub CI after a push or a PR (the workflows skip it);
32
32
  - pre-commit review: once the step is complete, and only then, run the `rql-code-review` skill on the step's changes (scope `uncommitted`) before the question; never during the implementation or for incomplete/red states. Blocker/Major findings in the step's own changes mean the step is not complete yet: fix them, re-run the affected checks and review the fixes; findings that need the user's decision are reported instead of the question (rule 9);
33
33
  - the question contains: the proposed commit subject (following the format rules above), a short recap of what was done in the changes (features/fixes, touched areas, check results), the review verdict with the remaining Minor/Nit findings and the list of files that will be committed;
34
34
  - commit only after an explicit "yes" (or with the subject the user corrects); on "no" leave the changes uncommitted (staging also only on request).
@@ -26,7 +26,7 @@ Related rule files (loaded for narrower paths):
26
26
  - YARD doc block on every class, module, constant, attr and method:
27
27
  `@param name [Type]`, `@option`, `@return [Type]`, blank `#` line, then `@api public|private`, `@since X.Y.Z`, optional `@version X.Y.Z` (methods: the latest behavior/signature change; classes/modules: the latest interface change, see rule 2).
28
28
  - Mixin lines (`include`/`extend`/`prepend`) need no YARD block, only `# @since X.Y.Z` right above each of them: the version that added the mixin to this class/module, not the `@since` of the class/module (`AcquireLock` is `@since 1.0.0`, its `extend RedisQueuedLocks::Utilities` is `@since 1.14.0`).
29
- - Operations are stateless modules with `class << self` functions; dependencies (`redis_client`, logger, instrumenter, sampling options) are passed as explicit args, never read from globals.
29
+ - Operations are stateless modules with `class << self` functions; dependencies (`redis_client`, logger, instrumenter, sampling options) are passed as explicit args, never read from globals. The stateful objects are owned by `Client` and passed down: `Swarm` and `LockKeeper` (the thread and the leases of the lock auto extension; instance state, no module-level state: a client lives in its Ractor).
30
30
  - Operation modules (except the lock acquisition core: `AcquireLock`, `LockSeries`) are independent of each other: no cross-calls and no shared RBS types between them; common logic lives in `Resource`/`Utilities`, similar logic is duplicated on purpose (see `acquirer.md`, "Independence of operation modules").
31
31
  - Public API results are hashes `{ ok: Boolean, result: Symbol|Hash }` (`Client`, `Acquirer::*`, `Swarm` facade actions); `Client` `!` methods raise `RedisQueuedLocks::*Error`. Internal swarm element APIs return bare scalars/primitives (see `swarm.md`).
32
32
  - `Client` methods only fill defaults from `config['...']` and delegate to `Acquirer::*` / `Swarm`.
@@ -51,15 +51,15 @@ Related rule files (loaded for narrower paths):
51
51
  - behavior changes inside the methods, constants, config settings (`setting`/`validate` are not methods of `Config`: its header changed in 1.22.0 only for `prevent_default_priority__unknown_name`) and comments bump only the method tags, never the class/module header;
52
52
  - the header keeps the version of the latest interface change; no `@version` when the interface never changed since `@since` (the headers of the versions >= 1.17.0 are aligned with this rule).
53
53
  3. New operation = new `Acquirer::*` module + thin `Client` method delegating to it (+ `!` variant only if it must raise); details in `acquirer.md`.
54
- 4. Return `{ ok:, result: }` hashes from public API operations (`Client`, `Acquirer::*`, `Swarm` facade actions); raise only in `!` methods or on invalid arguments (`RedisQueuedLocks::ArgumentError`). Internal APIs, and swarm element internals in particular, use bare scalars/primitives (`true`/`false`, String, Symbol, Integer, `nil`, a flat Hash of scalars) without the wrapper.
54
+ 4. Return `{ ok:, result: }` hashes from public API operations (`Client`, `Acquirer::*`, `Swarm` facade actions; the one legacy exception: the flat result of `#flush_zombies`, see `swarm.md`); raise only in `!` methods or on invalid arguments (`RedisQueuedLocks::ArgumentError`). Internal APIs, and swarm element internals in particular, use bare scalars/primitives (`true`/`false`, String, Symbol, Integer, `nil`, a flat Hash of scalars) without the wrapper.
55
55
  5. Never hardcode `rql:` strings; add a `Resource.prepare_*` helper or constant instead.
56
56
  6. Use WATCH/MULTI or a Lua constant for any read-modify-write on lock/queue keys; never do check-then-set in Ruby without a transaction.
57
57
  7. New config option: `setting` with default + `validate` with a type check and the valid range (TTLs, periods, batch/scan sizes are positive Integers: `val.is_a?(Integer) && val > 0`), both in `config.rb`, plus the key's overload line in `sig/redis_queued_locks/config.rbs` (`Config#[]` is typed per key; `spec/redis_queued_locks/config_spec.rb` fails on a missing/extra line); read it in `Client` as `config['key']`. A per-call numeric option (a `Client` keyword with a `config` default) is validated with the same type and range at the start of the operation module (the `Swarm` facade for the swarm actions), before any Redis command: `RedisQueuedLocks::ArgumentError` (`SwarmArgumentError` in `Swarm`) with the option name and the value (`` "`:scan_size` argument should be a positive Integer, got 0." ``).
58
58
  8. Logs and instrumentation events go through visitor modules (see `visitors.md`); event names follow `redis_queued_locks.<snake_case>`.
59
59
  9. Keep thread/Ractor safety: guard shared state with `Utilities::Lock`, never share a `RedisClient` across Ractors.
60
- 10. Follow the rubocop rules of the project (`.rubocop.yml` inheriting the armitage config, `.rubocop.rbs.yml` for RBS): `bundle exec rake rubocop` runs two passes (Ruby sources, then RBS) and both must be clean; read the whole output, not only its tail. Never change `.rubocop.yml` to make an offense pass: rewrite the code (e.g. `yield_self`, not `then`); a config change is a separate decision of the user. Disable rubocop cops only locally with a matching `rubocop:enable`, and only for Metrics/Layout on large methods (the only exception: the line-level `Lint/InheritException` of the base `RedisQueuedLocks::Exception < ::Exception` in `errors.rb`, see rule 15); never `# rubocop:disable all` (it hid real offenses until 1.21.1: an unpaired one in `client.rb` switched the linter off till the end of the file).
60
+ 10. Follow the rubocop rules of the project (`.rubocop.yml` inheriting the armitage config, `.rubocop.rbs.yml` for RBS): `bundle exec rake rubocop` runs two passes (Ruby sources, then RBS) and both must be clean; read the whole output, not only its tail. Never change `.rubocop.yml` to make an offense pass: rewrite the code (e.g. `yield_self`, not `then`); a config change is a separate decision of the user. Disable rubocop cops only locally with a matching `rubocop:enable`, and only for Metrics/Layout on large methods (the only exception for new code: the line-level `Lint/InheritException` of the base `RedisQueuedLocks::Exception < ::Exception` in `errors.rb`, see rule 15; pre-existing ones, kept, never copied: `Lint/DuplicateBranch` in `TryToLock#try_to_lock` Step 7, `Style/RedundantAssignment` in `RedisClientBuilder.build`, `Lint/IneffectiveAccessModifier` of the `def self.` helpers after `private` in `SwarmElement::Isolated`); never `# rubocop:disable all` (it hid real offenses until 1.22.0: an unpaired one in `client.rb` switched the linter off till the end of the file).
61
61
  11. After any change here, update the mirrored `sig/` file (see `type-checking.md`) and add/adjust a spec (see `tests.md`).
62
- 12. Keep `.claude/project-overview.md` and the affected `.claude/rules/*.md` in sync in the same change (keys, options, results, events, algorithm steps, limitations); read the relevant overview sections before implementing and follow their invariants.
62
+ 12. Keep `.claude/project-overview.md` and the affected `.claude/rules/*.md` in sync in the same change (keys, options, results, events, algorithm steps, limitations); read the relevant overview sections before implementing and follow their invariants. User-visible changes (methods, keywords and defaults, config options, results, errors, events, limitations, requirements) update README in the same change: what exactly and where is in `readme.md` (paired with this rule), CHANGELOG in `changelog.md`.
63
63
  13. Read/write awareness: every new or changed operation over locks/queues (release, cleanup, info, zombies, series) must handle the read key family too (see the key families above) and keep the result shape for write-only usage unchanged (add keys/branches only when read data exists).
64
64
  14. Never derive safety from queues or client clocks: mutual exclusion is decided by the lock state checked under WATCH (writers WATCH the write key + readers registry, readers WATCH the write key only), queues and positions only order requests.
65
65
  15. Error hierarchy (`errors.rb`, mirrored in `sig/redis_queued_locks/errors.rbs`):
@@ -73,6 +73,7 @@ Related rule files (loaded for narrower paths):
73
73
  - lock acquirement (`AcquireLock`, `LockSeries`): each meaningful step/outcome is logged and instrumented through the visitors (`visitors.md`): obtained (classic and reentrant), held and released, not obtained (`lock_obtaining_failed`, also before a raised acquirement error); the per-attempt `try_lock.*` steps are logs only (gated by `log_lock_try`), never instrumented (no `notify` per attempt);
74
74
  - lock mutation operations (release, extension, cleanup, reindexing): exactly one log line and one instrumentation event per operation with the time of the whole work of the root operation module called by the public `Client` method (the two-layer pattern of `acquirer.md`: the timer wraps the `fully_*` helper), never of its internal parts; the log line and the event have the same name (`redis_queued_locks.<event>`) and the same data in the same order (the log has no `instrument`), the payload ends with the user's `instrument`; they are written inline in the module (`run_non_critical`, gated by `Logging.should_log?` / `Instrument.should_instrument?`);
75
75
  - every such public `Client` method takes `logger:`, `instrumenter:`, `instrument:` and the log/instrumentation sampling keywords (defaults from `config`) and forwards them by name to the operation module;
76
+ - the lock auto extension (`LockKeeper`): each extension, failed extension, lost lock and reached hold limit is logged and instrumented per lock through its visitors, with the logger/instrumenter and the sampling decision of the lock acquirement;
76
77
  - known debt: the swarm elements and the manual swarm actions (`ProbeHosts`, `FlushZombies`: `#probe_hosts`, `#flush_zombies`) are neither logged nor instrumented yet (the flusher Ractor can not get the user's logger/instrumenter).
77
78
  17. Debug methods of `Resource`: `Resource` may keep methods that the library does not use when they are justified for debugging: they let you check a subtle part of the logic by hand at runtime (in a console), e.g. `lock_key_from_queue` maps a lock request queue of any mode to its lock. Each of them:
78
79
  - has a `# NOTE: (debug)` comment in its YARD block: that it is not used by the library and what it checks (with a console example);
@@ -0,0 +1,40 @@
1
+ ---
2
+ paths:
3
+ - "README.md"
4
+ ---
5
+
6
+ # README rules (`README.md`)
7
+
8
+ Paired with `logic.md#12`: that rule says *when* README changes (in the same change as the code), this file says *what* in README changes. A change of `lib/` that is visible to the user goes through both.
9
+
10
+ ## Observed conventions
11
+ - Layout: title + badges, intro (description, strategies, the "Supports ..." / "Provides ..." feature lines), `## Table of Contents`, `### Requirements` .. `### Configuration`, `### Usage` (one `#### #method - short description` per `Client` method, aliases as `(aka \`...\`)` in the TOC), feature sections (`## Swarm Mode and Zombie Locks`, `## Lock Index`, `## Lock Access Strategies`, `## Lock Request Prioritization`, `## Read/Write Locks`, `## Lock Auto Extending`, ...), `## Logging`, `## Instrumentation`, `## Roadmap`, `## Build and Develop`, `## Contributing`, `## License`, `## Authors`.
12
+ - Each section starts with `<sup>\[[back to top](#table-of-contents)\]</sup>` (a subsection points to its parent section); sections are separated by `---`.
13
+ - Code examples are fenced with a language (`ruby`, `shell`); results are shown as `# =>` comments.
14
+ - Anchors are GitHub slugs: lowercase, punctuation dropped except `-` and `_`, spaces become `-` (`#lock` + ` - obtain a lock` => `#lock---obtain-a-lock`, `Read/Write Locks` => `#readwrite-locks`, `swarmize!` => `#swarmize`).
15
+
16
+ ## Rules
17
+ 1. Sync scope (what changes with the code, `logic.md#12`):
18
+ - a new `Client` method (operation): its `#### #method` section in `### Usage` (signature with every keyword and its default as in `Client`, the result shapes, an example, the `!` variant and aliases) + its TOC line;
19
+ - a new/changed `Client` keyword or default: the signature and the keyword list of every method section that takes it (`#lock`, `#lock!`, `#lock_series`, ...);
20
+ - a new config option (`setting` in `config.rb`): its commented entry in the `### Configuration` block (default, meaning, valid values, the same order and grouping as `config.rb`); defaults always equal the `config.rb` ones (the exception until the swarm docs rework: the `swarm.*` keys, rule 9);
21
+ - new/changed log events and keys, instrumentation events and payload keys: `## Logging` / `### Instrumentation Events` (`visitors.md#14`; events also get their TOC line);
22
+ - new public errors and documented limitations: the method/feature section that raises or has them;
23
+ - a fundamentally new feature (`*Brand New Feature*` of `changelog.md#8`): its own `##` section + TOC lines (with its subsections) + a mention in the intro "Supports ..." / "Provides ..." line with a link to the section;
24
+ - the result shapes and examples of changed operations (read/write data, lock index, priorities: the shapes shown must be the real ones).
25
+ 2. Duplicated texts change together: the intro paragraphs and `### Algorithm` (queue order, strategies), the log lists of `## Logging` and the `config['logger']` / `config['log_lock_try']` comments (`visitors.md#14`); after the swarm docs rework (rule 9): the swarm configuration in `### Configuration` and in the swarm section.
26
+ 3. `## Roadmap`: an item implemented (fully or partly) by the change is removed or narrowed to what is left in the same change.
27
+ 4. `### Requirements`: Ruby / Redis / `redis-client` versions follow the gemspec and the commands the code uses (overview "Stack").
28
+ 5. `## Build and Develop`: rake tasks, the parallel runner (`WORKERS`, databases, log paths), the CI commands and their environment (`RBS_TEST_SKIP`, `type-checking.md#13`) follow the `Rakefile`, `spec/support/` and `.github/workflows/`.
29
+ 6. TOC: every `##` section, every `#### #method` of `### Usage`, every feature subsection and every instrumentation event has a TOC line; the nested lists of sections (swarm) follow the same rule; no link without a heading behind it, except the reserved swarm anchors (the TOC and the list of `## Swarm Mode and Zombie Locks`: `#how-to-swarm`, `#`, `#swarm_status`, `#swarm_info`, `#swarmize!`, `#deswarmize!`, `#probe_hosts`, `#flush_zombies` (text `flush_zobmies`), `#zombies_info`, `#zombie_locks`, `#zombie_hosts`, `#zombie_acquirers`): kept as is by the user's decision until the swarm docs rework (rule 9), never "fixed" or reported; the check of rule 8 lists them.
30
+ 7. Formatting: no trailing whitespace (blank lines inside code blocks included), a back-to-top line in each new section, fenced code with a language, no tabs.
31
+ 8. Before finishing a README change, check the anchors and the whitespace (no output = clean):
32
+ ```shell
33
+ ruby -e 'src=File.read("README.md");c=false;n=Hash.new(0);s={};src.each_line{|l|c=!c if l.start_with?("```");next if c || l !~ /^#+ (.+)$/;g=$1.strip.downcase.gsub(/<[^>]+>/,"").gsub(/[^\p{Word}\- ]/,"").tr(" ","-");s[n[g]>0 ? "#{g}-#{n[g]}" : g]=1;n[g]+=1};src.scan(/\]\(#([^)]*)\)/).flatten.uniq.each{|a|puts "broken anchor: ##{a}" unless s[a]}'
34
+ grep -n '[[:space:]]$' README.md
35
+ ```
36
+ 9. Swarm documentation (pending rework, the user's decision): the `## Swarm Mode and Zombie Locks` section is in progress (the usage preview only), so its gaps are exceptions of the rules above, not findings:
37
+ - the reserved swarm anchors of rule 6 (no headings behind them);
38
+ - the `swarm.*` config keys (`config.rb`) are documented only in the configuration of the swarm usage preview, not in `### Configuration` (rule 1);
39
+ - the swarm methods (`#swarmize!`, `#deswarmize!`, `#swarm_status`, `#swarm_info`, `#probe_hosts`, `#flush_zombies`, `#zombie_*`, `#zombies_info`) have no `#### #method` sections;
40
+ - when the swarm docs are reworked, all these exceptions are removed in the same change: the swarm sections and their TOC lines are written, the `swarm.*` keys go to `### Configuration`, rules 1, 2, 6 and this rule lose their swarm exceptions.
@@ -55,7 +55,7 @@ Command protocol: the same bare-value replies in both bases (see "Internal API:
55
55
  Every request/reply pair is wrapped in `sync.synchronize` so concurrent callers can't interleave on the channel, and each reply belongs to the command just sent. Both bases send every command through one helper, `swarm_loop__send_command(command)`, which returns the reply, or `nil` when the element is dead (or, in Threaded, terminating). Abstract hooks (`spawn_main_loop!`, `spawn_swarm_element!`) raise `NotImplementedError` in the bases.
56
56
 
57
57
  ## Internal API: scalars and primitives
58
- `{ ok:, result: }` is the **public API** contract only: `Client` methods, `Acquirer::*` operations, and the `Swarm` facade's public methods (`swarm!`/`deswarm!`, plus the stateless operations behind `client.probe_hosts` / `client.flush_zombies`). Status reports (`swarm_status`, element `#status`, `Supervisor#status`) are plain nested Hashes with no wrapper.
58
+ `{ ok:, result: }` is the **public API** contract only: `Client` methods, `Acquirer::*` operations, and the `Swarm` facade's public methods (`swarm!`/`deswarm!`, plus the stateless operations behind `client.probe_hosts` / `client.flush_zombies`). The legacy exception (public since 1.9.0, kept as is: a breaking change otherwise): `FlushZombies.flush_zombies` returns the flat `{ ok:, deleted_zombie_hosts:, deleted_zombie_acquirers:, deleted_zombie_locks: }` (RBS `flushedZombies`), without `result:`. Status reports (`swarm_status`, element `#status`, `Supervisor#status`) are plain nested Hashes with no wrapper.
59
59
 
60
60
  Everything inside swarm elements is internal API and uses bare scalars and primitives, with no `{ ok:, result: }` wrapper. That covers control-unit commands and replies, the Isolated handshake, port and queue messages, `swarm_loop__*` helpers, `swarmed__*` predicates and main-loop plumbing.
61
61
  - **Commands**: Symbols (`:status`, `:is_active`, `:start`, `:stop`, `:kill`).
@@ -110,7 +110,7 @@ Public element API (called by `Swarm`/`Supervisor` only):
110
110
  12. Mirror every change in `sig/redis_queued_locks/swarm/**` and keep the existing `# steep:ignore` on nil-narrowed `Thread?`/`Ractor?` calls (Steep doesn't narrow `attr_reader` results).
111
111
  13. Isolated communication goes only through `Ractor::Port`s: create the results port in the main Ractor (`swarm!`) and the command port inside the element Ractor (`.swarm_loop`), and register `Ractor#monitor` on the results port before waiting on it. Every command gets exactly one reply, sent before the Ractor leaves its loop. Treat Symbol replies as death notices. Don't use `Ractor.receive`, `Ractor#send` or the default port, and never share one port between elements. Naming: port variables, attributes and params end in `_port` (`swarm_element_results_port`, `swarm_element_commands_port`). Block (proc) params use short initial-letter names (`r_res_p` for the results port, `r_com_p` for the commands port), like the other abbreviated Ractor block params (`rc`, `z_ttl`).
112
112
  14. Inside an element Ractor, terminate threads with kill + join (`.terminate_thread`) and keep `:kill` terminating every thread of the Ractor. Otherwise its status lags as `running`.
113
- 15. Don't use `{ ok:, result: }` inside swarm elements (see "Internal API: scalars and primitives"). Commands are Symbols. Replies, helper returns and predicates are bare scalars/primitives, or a flat Hash of scalars, with `nil` for "no answer / dead". Keep the wrapper only at the public boundary (`Client`, `Acquirer::*`, `Swarm#swarm!`/`#deswarm!`, `ProbeHosts.probe_hosts`, `FlushZombies.flush_zombies`). Type internal replies in RBS as literal types/unions (`bool`, `String`, `{ alive: bool, state: String }`) rather than `xxxResult` records.
113
+ 15. Don't use `{ ok:, result: }` inside swarm elements (see "Internal API: scalars and primitives"). Commands are Symbols. Replies, helper returns and predicates are bare scalars/primitives, or a flat Hash of scalars, with `nil` for "no answer / dead". Keep the wrapper only at the public boundary (`Client`, `Acquirer::*`, `Swarm#swarm!`/`#deswarm!`, `ProbeHosts.probe_hosts`, `FlushZombies.flush_zombies` (its legacy flat shape, see above)). Type internal replies in RBS as literal types/unions (`bool`, `String`, `{ alive: bool, state: String }`) rather than `xxxResult` records.
114
114
  16. Swarm specs (in `describe 'swarm'`) deal with real timing: set short periods via config, kill elements with `try_kill!`, wait longer than `liveness_probing_period`, and match states loosely (`eq('running').or(eq('blocking'))`, `'sleep'`/`'run'`).
115
115
 
116
116
  ## Known quirks (don't copy; fix only in a dedicated change)