redis_queued_locks 1.23.1 → 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 -4
  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 +25 -10
  17. data/CLAUDE.md +7 -5
  18. data/README.md +381 -13
  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 +243 -35
  24. data/lib/redis_queued_locks/acquirer/acquire_lock.rb +93 -3
  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 +150 -14
  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 +11 -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 +6 -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
@@ -7,7 +7,7 @@ paths:
7
7
  # Test rules (`spec/`)
8
8
 
9
9
  ## Observed conventions
10
- - All behavior specs live in one integration file, `spec/redis_queued_locks_spec.rb` (~5.6k lines), under `RSpec.describe RedisQueuedLocks`; the only other spec is the Redis-free `spec/redis_queued_locks/config_spec.rb` (the typed `Config#[]` overload table of `config.rbs` == the `setting` registry); groups: `describe 'Lock Series'`, `describe 'swarm'`, `describe 'read/write locks'`, plus top-level `specify` blocks (all of them in the shared examples), and `describe 'lock index'` (outside the shared examples, see below). The file header says it will be reworked; rspec-retry (5 retries) masks flakiness meanwhile.
10
+ - All behavior specs live in one integration file, `spec/redis_queued_locks_spec.rb` (~10.5k lines), under `RSpec.describe RedisQueuedLocks`; the only other spec is the Redis-free `spec/redis_queued_locks/config_spec.rb` (the typed `Config#[]` overload table of `config.rbs` == the `setting` registry); groups: `describe 'Lock Series'`, `describe 'swarm'`, `describe 'lock request priorities'`, `describe 'read/write locks'`, `describe 'lock auto extension'`, plus top-level `specify` blocks (all of them in the shared examples), and `describe 'lock index'` (outside the shared examples, see below). The file header says it will be reworked; rspec-retry (5 retries) masks flakiness meanwhile.
11
11
  - Known flaky examples (timing-dependent: they pass in isolation, rspec-retry usually hides them; check them with `RSPEC_RETRY_RETRY_COUNT=1` before blaming a change):
12
12
  - `all in + notifications`: `sleep(1)` before the lock/queue info checks; it was order-dependent (wrong `locks_info.size` in full runs, e.g. `--seed 6170`, `--seed 28462`): `detailed lock acquirement timeout error` left an unbounded waiter thread that obtained its lock in the next example (now bounded and joined); check new failures without retries before blaming a change;
13
13
  - `:queued access strategy` and `:queued access strategy (manually defined)` (the same scenario): the 4th attempt of `trd2` (~9 s, `retry_delay: 3_000`) races the expiration of the `trd1` lock (obtained at ~7 s with ttl 2 s), and the default `try_to_lock_timeout` (10 s) leaves no later attempt;
@@ -26,12 +26,13 @@ paths:
26
26
  - Coverage: SimpleCov line + branch, HTML only; `minimum_coverage 100` is a TODO.
27
27
  - Both lock lookup modes (`config['lock_index_enabled']`): the behavior examples are `RSpec.shared_examples 'redis_queued_locks'` (the `redis` pool and the FLUSHDB hooks are `RSpec.shared_context 'redis_queued_locks redis'`), included by `RSpec.describe RedisQueuedLocks` twice: `context 'with the disabled lock index (keyspace SCAN)', lock_index_enabled: false` and `context 'with the enabled lock index (lock index ZSCAN)', lock_index_enabled: true`; the `around` hook of `spec_helper` switches the default of `config['lock_index_enabled']` for the example by this metadata (`RedisQueuedLocks::Config.setting`, the library default is restored after the example), so `RedisQueuedLocks::Client.new(redis)` inside the shared examples gets the mode of the context (explicit config values win). One `bundle exec rake rspec` runs the shared examples in both modes (~2x time).
28
28
  - Mode-dependent expectations inside the shared examples branch on `client.config['lock_index_enabled']` (e.g. `lock state pipeline layout`: 5 queueing commands, 9 with the lock index; `lock-iterating operations: one pass (keyspace or lock index) with small batches`: `#keys` lists other `rql:lock*` keys only with the keyspace lookup); keys written directly with raw commands (`ZADD` queues, `HSET` locks) are found by the keyspace SCAN and are indexed with `client.reindex_locks if client.config['lock_index_enabled']` before lock-iterating assertions.
29
+ - Lock auto extension: `describe 'lock auto extension'` (in the shared examples, both lookup modes), `lock auto extension: ...` examples of `describe 'lock index'`. Blocks are longer than the short ttls of the locks; survival is checked from another client or thread (the keeper lives in the process of the example); wait for keeper events by polling (`wait_until`), a block can end before the tick of the keeper. The lease of the block (`describe 'the lease of the block of code (LockLease)'`): blocks with a parameter; rbs/test wraps the blocks of the checked methods (the arity is lost: a lambda without parameters gets the lease under `RBS_RUNTIME_TEST`); `hold_for` at the old limit is too late by design (the lock ends there), so a race with the tick is forced by stubs (`LockKeeper#stop_hold`, `Lease#hold_limit_reached?`). `fork` examples call `exit!` in the child: SimpleCov does not see these lines. Fiber scheduler examples (`timed` blocks of non-blocking fibers) run in `Sync` blocks of `async` (a dev gem, required by `spec_helper`); a scheduler without `fiber_interrupt` is emulated by undefining it on the singleton class of the reactor (`Fiber.scheduler`); `Fiber.new(blocking: false)` without a scheduler is the fallback case; an interruption sent at the end of the block is forced by a `Thread.pass` loop (it gives the GVL, not the control to the scheduler: the fiber does not suspend).
29
30
  - Lock index specifics live in `describe 'lock index'` (outside the shared examples: run once, every client enables the lock index explicitly with `config['lock_index_enabled'] = true`; `let(:index_score_ahead)` = index score minus the current client ms, `let(:upper_bound)` = `be_between(lifetime + grace - 1_000, lifetime + grace)`); `the lock obtaining transaction indexes the lock` drops the index entry right before the obtaining `MULTI` with a middleware (keep it when touching the obtaining transaction); `the disabled lock index (default): no lock index commands, keyspace lookups` records all commands of the default mode (no `rql:index:locks` argument, no `ZSCAN`, queues without TTL); `enabling the lock index: ...` covers the migration (`#reindex_locks` after enabling).
30
31
 
31
32
  ## Claude rules
32
33
  The suite is pending a total rework (overview "Conventions"): these rules guide new examples, but their violations in `*_spec.rb` are not code review findings until the rework; the review checks only that the changed library behavior is covered and that changed expectations are correct (`.claude/skills/rql-code-review`, §3).
33
34
 
34
- 1. Run specs with a local Redis available. Run the suite in parallel processes by default: `bundle exec rake rspec:parallel` (~1 min instead of ~6 of the serial `bundle exec rake rspec`; the RBS runtime checks: the same environment with `rake rspec:parallel` (locally; the CI `typecheck-runtime` job stays serial: parallel workers under the RBS hooks starve the timing-sensitive examples on its 2-core runner); `WORKERS=<n>` flushes db `0..2n-1`, see the `RQL_SPEC_DB_OFFSET` note in `spec_helper.rb`; failures are listed with their rerun command, worker logs in `tmp/rspec_parallel/`). Use the serial run only when something has to be checked in one process: an order-dependent failure or a whole-suite `--seed` (each parallel worker has its own seed and order), state leaking between examples (threads, Redis keys of a finished example), changes of the parallel infrastructure (`spec_helper.rb`, `spec/support/parallel_runner.rb`: check both runs), the serial duration itself. Targeted runs of a few examples (development, the flakiness checks of rule 10) use `bundle exec rspec spec/redis_queued_locks_spec.rb:<line>` / `-e '<group>'` directly. Examples must stay independent of other processes: no server-wide Redis commands (`FLUSHALL`, `CONFIG SET`, `SWAPDB`, `SELECT`), Redis clients only through `RedisClient.config` (the database offset of the parallel workers is applied there).
35
+ 1. Run specs with a local Redis available. Run the suite in parallel processes by default: `bundle exec rake rspec:parallel` (~1 min instead of ~6 of the serial `bundle exec rake rspec`; the RBS runtime checks: the same environment with `rake rspec:parallel`, locally and in the CI `typecheck-runtime` job; `WORKERS=<n>` flushes db `0..2n-1`, see the `RQL_SPEC_DB_OFFSET` note in `spec_helper.rb`; failures are listed with their rerun command, worker logs in `tmp/rspec_parallel/`). Use the serial run only when something has to be checked in one process: an order-dependent failure or a whole-suite `--seed` (each parallel worker has its own seed and order), state leaking between examples (threads, Redis keys of a finished example), changes of the parallel infrastructure (`spec_helper.rb`, `spec/support/parallel_runner.rb`: check both runs), the serial duration itself. Targeted runs of a few examples (development, the flakiness checks of rule 10) use `bundle exec rspec spec/redis_queued_locks_spec.rb:<line>` / `-e '<group>'` directly. Examples must stay independent of other processes: no server-wide Redis commands (`FLUSHALL`, `CONFIG SET`, `SWAPDB`, `SELECT`), Redis clients only through `RedisClient.config` (the database offset of the parallel workers is applied there).
35
36
  2. Add new examples to `spec/redis_queued_locks_spec.rb` with `specify '<feature>'`, inside an existing `describe` when one fits; don't create new spec files unless asked (the suite is pending a rework); Redis-free consistency checks (e.g. the `config_spec.rb` table sync) are the exception: one small file per subject under `spec/redis_queued_locks/`.
36
37
  3. Use only `expect` syntax; no `should`, no monkey-patched DSL, no `focus` left behind.
37
38
  4. Use the shared `redis` pool and rely on the global `before`/`after` FLUSHDB; never use a different DB or flush in the middle of an example without reason.
@@ -26,7 +26,7 @@ paths:
26
26
  - `pipelined`/`call` return `untyped`: annotate destructured pipeline results with a tuple (`# @type var lock_state: [String?, Array[String], Float?, Array[[String, Float]]]`);
27
27
  - splatting a `Set` (`call(*set)`) is rejected (`Ruby::ArgumentTypeMismatch`: splat arguments must be arrays), and no honest inline annotation fixes it; at runtime Ruby converts a splatted `Set` with `Set#to_a` on every call.
28
28
  - Steep 2 narrows on `==` with literals (`x == :sym` makes `x` the literal type `:sym`) and rejects `# @type var` annotations that widen a narrowed variable; RBS 4's `Kernel#Array` has a `(nil) -> []` overload that `untyped` arguments resolve to, so `Array(rconn.call(...)).first` needs a `#: T` assertion.
29
- - Runtime checking: CI runs specs with `RUBYOPT='-rbundler/setup -rrbs/test/setup' RBS_TEST_TARGET='RedisQueuedLocks::*'` (the blocking `typecheck-runtime` job, command in the workflow and README; the job stays serial (`bundle exec rspec`): parallel workers under the RBS hooks starve the timing-sensitive examples on the 2-core runner, locally the same environment works with `rake rspec:parallel`; `bundler/setup` goes first so `rbs`/`prism` come from `Gemfile.lock`, not from newer system gems), so signatures must match real runtime values, not just Steep's view. Not hooked (rbs/test hooks read `RBS.logger` and die with `Ractor::IsolationError` inside the flusher Ractor): the Ractor-side classes via `RBS_TEST_SKIP` (`Swarm::FlushZombies`, `Swarm::SwarmElement::Isolated`, `Swarm::RedisClientBuilder`) and the shared helpers they call via `%a{rbs:test:skip}` in RBS (`Resource.prepare_*`, `lock_key_family`, `lock_index_time`, `lock_name_from_readers`, `host_identifier_from_acquirer`, `calc_zombie_score`, `Utilities.thread_state`); `VoidNotifier.notify` and the samplers' `sampling_happened?` are skipped because `Instrument.valid_interface?` / `valid_sampler?` introspect their `#parameters`. `RBS_TEST_SKIP` entries need the absolute form (`::RedisQueuedLocks::...`): rbs/test compares them with absolute type names without normalizing them. Specs that pass type-invalid values on purpose skip those expectations under `RBS_RUNTIME_TEST` (`spec_helper.rb`); value-invalid cases of the right type (`:reed`) stay.
29
+ - Runtime checking: CI runs specs with `RUBYOPT='-rbundler/setup -rrbs/test/setup' RBS_TEST_TARGET='RedisQueuedLocks::*'` (the blocking `typecheck-runtime` job, command in the workflow and README; parallel processes (`rake rspec:parallel`) as in tests: the job was serial until the checks got cheaper (`Config#config_state` skip, 10 sampling rounds), the RBS hooks starved the timing-sensitive examples on the 2-core runner; `RUBY_TCP_NO_FAST_FALLBACK=1` in the job env (NOTE in the workflow); `bundler/setup` goes first so `rbs`/`prism` come from `Gemfile.lock`, not from newer system gems), so signatures must match real runtime values, not just Steep's view. Not hooked (rbs/test hooks read `RBS.logger` and die with `Ractor::IsolationError` inside the flusher Ractor): the Ractor-side classes via `RBS_TEST_SKIP` (`Swarm::FlushZombies`, `Swarm::SwarmElement::Isolated`, `Swarm::RedisClientBuilder`) and the shared helpers they call via `%a{rbs:test:skip}` in RBS (`Resource.prepare_*`, `lock_key_family`, `lock_index_time`, `lock_name_from_readers`, `host_identifier_from_acquirer`, `calc_zombie_score`, `Utilities.thread_state`); `VoidNotifier.notify` and the samplers' `sampling_happened?` are skipped because `Instrument.valid_interface?` / `valid_sampler?` introspect their `#parameters`. `Config#config_state` is skipped for speed: it runs twice per `config['...']` and rbs/test walks every key of its `Hash[String, untyped]` on each call (64 % of the check time of a `lock`: ~17 ms → ~7 ms per `lock` under the checks); the values stay checked per key by the `Config#[]` overloads. `RBS_TEST_SKIP` entries need the absolute form (`::RedisQueuedLocks::...`): rbs/test compares them with absolute type names without normalizing them. Specs that pass type-invalid values on purpose skip those expectations under `RBS_RUNTIME_TEST` (`spec_helper.rb`); value-invalid cases of the right type (`:reed`) stay.
30
30
 
31
31
  ## Claude rules
32
32
  1. Every change to a `lib/` file's public or private API (new method, param, return shape, constant, ivar) must be reflected in the mirrored `.rbs` file in the same change.
@@ -36,13 +36,14 @@ paths:
36
36
  5. Prefer fixing types or adding `# @type var` / `#: T` annotations over `# steep:ignore`; add `# steep:ignore` only where Steep reports a diagnostic. Strict mode fails the build on `Ruby::RedundantIgnoreComment`, so never add a speculative ignore and remove ones that become redundant. Never shape runtime code around Steep limitations (conversions, copies or allocations made only to satisfy Steep): annotate it, or use a targeted `# steep:ignore` with a `NOTE: (steep)` comment when no honest annotation exists. Keep a conversion only when it is cheaper at runtime and say so in its comment (e.g. a `Set` splatted in a loop: build the array once instead of a `Set#to_a` per call).
37
37
  6. Don't loosen `Steep::Diagnostic::Ruby.strict` or add `ignore` entries to the `Steepfile`.
38
38
  7. New third-party gem used in `lib/`: add it to `rbs_collection.yaml` (and `sig/manifest.yml` for stdlib) or write a minimal stub in `sig/vendor/`.
39
- 8. Verify with `bundle exec rbs collection install && bundle exec rake steep:check`; for signature/runtime mismatches run the specs under RBS runtime testing (the environment of `.github/workflows/typecheck-runtime.yml`; in parallel processes by default: the same environment with `bundle exec rake rspec:parallel` instead of `bundle exec rspec`, `tests.md#1`).
39
+ 8. Verify with `bundle exec rbs collection install && bundle exec rake steep:check`; for signature/runtime mismatches run the specs under RBS runtime testing (the command of `.github/workflows/typecheck-runtime.yml`: parallel processes; the same environment with `bundle exec rspec` instead of `bundle exec rake rspec:parallel` for the one-process checks of `tests.md#1`).
40
40
  9. Keep RBS file and directory names identical to their `lib/` counterparts (`acquirer.rbs`, `acquire_lock/yield_expire/`).
41
41
  10. After `steep:check`, also grep its output for `ERROR`/`FATAL` lines: an internal Steep crash skips the file but still reports "No type error detected".
42
42
  11. Bump the pinned `gem_rbs_collection` revision only deliberately, in its own change: set the new commit in `rbs_collection.yaml`, run `bundle exec rbs collection update`, commit both files together and keep Steep green.
43
43
  12. New `setting` in `config.rb` = new overload line `| ("<key>") -> <value type>` in `Config#[]` (`config.rbs`), in the `setting` order; the value type is the validator's type (`Integer`, `Integer?` for nullable keys, `bool`, shared aliases such as `RQL::loggerObj`, `RQL::conflictStrategy`).
44
44
  13. Keep the runtime type-check job green: run its command before proposing a commit that touches `sig/` or method signatures; a new method executed inside the flusher Ractor gets `%a{rbs:test:skip}` (with the `(rbs test)` NOTE) or its class goes to `RBS_TEST_SKIP` in the workflow and README; a new spec that passes a type-invalid value wraps that expectation in `unless RBS_RUNTIME_TEST`.
45
45
  14. `bundle exec rbs collection install` may rewrite `rbs_collection.lock.yaml` with environment-specific entries; restore it (`git checkout -- rbs_collection.lock.yaml`) unless the change is intended.
46
+ 15. A runtime check costs time on every hooked call: a hot internal method whose signature proves nothing at runtime (an `untyped` payload read many times per operation, like `Config#config_state`) may get `%a{rbs:test:skip}` with a `(rbs test)` NOTE; methods whose types carry real checks (`Config#[]`, the public API) stay hooked.
46
47
 
47
48
  ## Recommendations (proposed, not yet project policy)
48
49
  1. Type `Config#[]=` per key like `Config#[]` (an overload table of key literal => value type) so Steep checks assignments in user code too.
@@ -19,11 +19,12 @@ The project calls these modules "visitors", but they are not GoF Visitor (no `ac
19
19
  |---|---|---|
20
20
  | `AcquireLock::LogVisitor` | `acquire_lock/log_visitor.rb` | 7: `start_lock_obtaining`, `start_try_to_lock_cycle`, `dead_score_reached__reset_acquirer_position`, `extendable_reentrant_lock_obtained`, `reentrant_lock_obtained`, `lock_obtained`, `lock_obtaining_failed` |
21
21
  | `AcquireLock::InstrVisitor` | `acquire_lock/instr_visitor.rb` | 6: `extendable_reentrant_lock_obtained`, `reentrant_lock_obtained`, `lock_obtained`, `lock_obtaining_failed`, `reentrant_lock_hold_completes`, `lock_hold_and_release` |
22
- | `AcquireLock::TryToLock::LogVisitor` | `acquire_lock/try_to_lock/log_visitor.rb` | 19 step-level events (`start`, `rconn_fetched`, `acq_added_to_queue`, `dead_request_removed`, `exit__no_first`, `exit__read_lock_still_obtained`, `obtain__free_to_acquire`, ...); every lock event logs `rw_mode` |
22
+ | `AcquireLock::TryToLock::LogVisitor` | `acquire_lock/try_to_lock/log_visitor.rb` | 20 step-level events (`start`, `rconn_fetched`, `acq_added_to_queue`, `dead_request_removed`, `exit__no_first`, `exit__read_lock_still_obtained`, `exit__reentrant_lock_is_changed`, `obtain__free_to_acquire`, ...); every lock event logs `rw_mode` |
23
23
  | `AcquireLock::YieldExpire::LogVisitor` | `acquire_lock/yield_expire/log_visitor.rb` | `expire_lock`, `decrease_lock` |
24
24
  | `AcquireLock::DequeueFromLockQueue::LogVisitor` | `acquire_lock/dequeue_from_lock_queue/log_visitor.rb` | `dequeue_from_lock_queue` |
25
25
  | `LockSeries::LogVisitor` | `lock_series/log_visitor.rb` | 11: `start_lock_series_obtaining`, `start_try_to_lock_series_cycle`, `dead_score_reached__reset_series_position`, `lock_series_intermediate_lock_obtained`, `lock_series_lock_obtained`, `lock_series_lock_obtaining_failed`, `lock_series_obtained`, `lock_series_obtaining_failed`, `dequeue_from_lock_series_queues`, `expire_lock_series`, `decrease_lock_series`; `rw_mode` (the mode of the series) and `priority` in all of them |
26
26
  | `LockSeries::InstrVisitor` | `lock_series/instr_visitor.rb` | 6: `lock_series_intermediate_lock_obtained`, `lock_series_lock_obtained`, `lock_series_lock_obtaining_failed`, `lock_series_obtained`, `lock_series_hold_and_release`, `lock_series_obtaining_failed`; `rw_mode` and `priority` in all of them |
27
+ | `LockKeeper::LogVisitor`, `LockKeeper::InstrVisitor` | `lock_keeper/log_visitor.rb`, `lock_keeper/instr_visitor.rb` | 5 per visitor, one per lock: from the keeper thread `lock_auto_extended`, `lock_auto_extension_failed`, `auto_extended_lock_lost`, `lock_hold_limit_reached`; from the thread that calls `LockLease#hold_for` `lock_hold_limit_extended` (and `auto_extended_lock_lost` of a lock it finds lost); `rw_mode` (the held mode) right after `lock_key`, no `priority`; the sampling decision of the acquirement and the user `instrument` live in the lease |
27
28
 
28
29
  `TryToLockSeries` writes the try-lock logs of each lock through `TryToLock::LogVisitor` (the `LogVisitor` constant there: `TryToLock` is included; the per-lock loops are gated by `log_sampled && log_lock_try`): no own try-lock events.
29
30
 
@@ -32,7 +33,7 @@ Not covered by visitors (lock mutation operations, `logic.md#16`): `ReleaseLock`
32
33
  ## Observed conventions
33
34
  - **Placement**: a visitor sits in a subdirectory named after the component it reports on (`<component>/log_visitor.rb`, `<component>/instr_visitor.rb`) and is loaded by that component with `require_relative` at the top of the module body.
34
35
  - **Shape**: `module <Component>::LogVisitor` / `::InstrVisitor`, `# @api private`, all methods inside `class << self`, full YARD block per method; return `void`.
35
- - **Method name = event name**: snake_case; double underscore separates phase and detail (`exit__queue_ttl_reached`, `reentrant_lock__work_through`). The LogVisitor and InstrVisitor use the same method name for the same event.
36
+ - **Method name = event name**: snake_case; double underscore separates phase and detail (`exit__queue_ttl_reached`, `reentrant_lock__work_through`). The LogVisitor and InstrVisitor use the same method name for the same event. The one legacy exception (a public log name, never renamed): `DequeueFromLockQueue::LogVisitor.dequeue_from_lock_queue` writes `[redis_queued_locks.fail_fast_or_limits_reached_or_deadlock__dequeue]`.
36
37
  - **Parameter order**: `(port, sampled_flag, [extra gate], lock_key, ...event data..., [instrument])`:
37
38
  - LogVisitor: `(logger, log_sampled, ...)`; `TryToLock::LogVisitor` adds `log_lock_try` as the third arg (fine-grained step logs are opt-in through `config['log_lock_try']`). Lock lifecycle events (AcquireLock, TryToLock, YieldExpire, DequeueFromLockQueue, LockSeries) take `rw_mode` right after `access_strategy`, before event-specific data, and log it as `rw_mode => '<mode>'` right after `acs_strat`; the lock acquirement logs of `AcquireLock::LogVisitor` (all of them), `LockSeries::LogVisitor` (the priority of the series) and `TryToLock::LogVisitor.acq_added_to_queue` take `priority` right after `rw_mode` and log `priority => N` right after it (the release logs of `YieldExpire` and `DequeueFromLockQueue` don't); try-lock logs that name another request log its decoded priority right after its acquirer (`first_priority_in_queue` after `first_acq_id_in_queue`, `ahead_priority` after `ahead_acq_id`, `dead_priority` after `dead_acq_id`; `Integer?` params decoded at the call site only when `log_sampled && log_lock_try`, by one helper: `TryToLock#logged_request_priority`, see rule 12).
38
39
  - InstrVisitor: `(instrumenter, instr_sampled, lock_key, rw_mode, ttl, acq_id, hst_id, ts, acq_time, [hold_time], instrument)`; the payload carries `rw_mode:` (requested mode); the user's `instrument` value is always last. All lock acquirement events (`lock_obtained`, `lock_hold_and_release`, `lock_obtaining_failed`, the reentrant ones: the requested priority, they never queue; the lock series ones: the priority of the series) take `priority` (the lock request priority: always the Integer, a priority name is resolved before) right after `rw_mode` (payload `priority:` after `rw_mode:`).
@@ -129,7 +129,9 @@ Still in scope (the exemption covers how specs are written, not whether the libr
129
129
 
130
130
  ### A. Lock safety and Redis correctness
131
131
  - Mutual exclusion only from the lock state checked under `WATCH`/`MULTI` (`logic.md#6`, `#14`); Lua only for the
132
- existing write TTL extension/decrease, no new Lua in the RW acquisition path unless the user asked. No
132
+ write TTL extension/decrease, the owner-checked release/decrease (`RELEASE_OWN_LOCK`, `DECREASE_OWN_LOCK_PTTL`: a lease,
133
+ an interrupted obtaining) and the lock keeper scripts (write and read extensions of a held lock), no new Lua in
134
+ the RW acquisition path unless the user asked. No
133
135
  check-then-set in Ruby without a transaction; queues, client clocks, the lock index and the pre-check never
134
136
  decide mutual exclusion (the pre-check never obtains the lock).
135
137
  - Asymmetric WATCH (`acquirer.md#12`): writers watch `[lock_key, lock_readers_key]`, readers `[lock_key]` only.
@@ -227,7 +229,8 @@ Still in scope (the exemption covers how specs are written, not whether the libr
227
229
  except `ReindexLocks`.
228
230
  - Superset invariant: every key-creating command is followed by `ZADD <index> GT <now + lifetime + grace> <name>`
229
231
  in the same pipeline/transaction, after the key command; the obtaining `MULTI` indexes the lock itself; every
230
- extension is followed by `ZADD XX INCR`; scores never decrease; names are removed only in the same `MULTI`
232
+ extension is followed by `ZADD XX INCR` (the absolute extensions of `LockKeeper`: `ZADD XX GT` in their scripts);
233
+ scores never decrease; names are removed only in the same `MULTI`
231
234
  that deletes all their keys (`ReleaseLocksOf`, `YieldExpire` releases and `FlushZombies` never remove names).
232
235
  - Lock index commands are conditional tails: reply positions never depend on the mode.
233
236
  - A new key family: distinct prefix `rql:lock_<kind>:<name>` (never a suffix of the name), bounded TTL in the
@@ -389,7 +392,7 @@ Still in scope (the exemption covers how specs are written, not whether the libr
389
392
  - Unused `Resource` methods marked `# NOTE: (debug)` (manual runtime checks, `logic.md#17`); report a debug method
390
393
  only when it is wrong for a key family it can get.
391
394
  - Known limitations kept by the user: `YieldExpire` write release (`EXPIRE 0`) and ttl decrease without an owner
392
- check; `HMGET`→`DEL` without `WATCH` in `ReleaseLocksOf`/`FlushZombies`; `unlock` dropping the data of a reader
395
+ check (without `auto_extend`: a block with a lease must check the owner); `HMGET`→`DEL` without `WATCH` in `ReleaseLocksOf`/`FlushZombies`; `unlock` dropping the data of a reader
393
396
  re-acquired between its two round trips; `zombie_acquirers` vs `flush_zombies` acquirer sets.
394
397
  - Known debt: `WithAcqTimeout` → `LockInfo`/`QueueInfo`; rspec-retry, disabled coverage minimum;
395
398
  `sleep(0.1)` readiness waits and missing logging in the swarm;
@@ -0,0 +1,171 @@
1
+ ---
2
+ name: rql-project-full-review
3
+ description: Full audit of the whole redis_queued_locks repository (not a diff) - every instruction (CLAUDE.md, .claude/project-overview.md, .claude/rules/*.md, the skills) against the code (lib/, sig/, spec coverage, CI, Rakefile, gemspec) and against each other, plus a hunt for defects in the code itself. Reports "everything matches" or "matches, but these things should be updated/corrected" with a list, separating intentional decisions (never proposed for change) and intentionally deferred items (their own section). Use only when the user asks for a full/project-wide review or audit (полное ревью проекта, аудит, проверь соответствие инструкций и кода); a diff/branch/PR review is rql-code-review.
4
+ argument-hint: "[<areas...>: lib | sig | swarm | acquirer | keeper | docs | rules | ci] [--with-specs] [--no-checks]"
5
+ ---
6
+
7
+ # redis_queued_locks full project review
8
+
9
+ Audit the repository as it is at `HEAD` (+ uncommitted changes, named as such): do the instructions describe the
10
+ code truthfully, does the code follow the instructions, do the instructions agree with each other, and what is
11
+ broken or fragile regardless of the instructions. Diff-based reviews are `rql-code-review`; this skill reuses its
12
+ checklist (§4) and its "Do not report" list (§5) as the single source of the project invariants and settled
13
+ decisions: read `.claude/skills/rql-code-review/SKILL.md` first.
14
+
15
+ - Read-only: never edit, stage or commit. After the report offer to fix the selected items (one change per topic,
16
+ each going through the usual completion checks and the pre-commit review of `git.md#7`).
17
+ - Inline, in this session (no subagents unless the user asks for them).
18
+ - Arguments narrow the audit to areas (the default is all of §3). `--with-specs` also runs the suite
19
+ (`bundle exec rake rspec:parallel`: needs a local Redis, flushes db `0..2n-1`); `--no-checks` skips rubocop/steep.
20
+ - The report language follows the Claude Code `language` setting exactly as in `rql-code-review` §7 (templates
21
+ `templates/report.<code>.md` of this skill, English when no template matches).
22
+
23
+ ## 1. Classification: what is a finding
24
+
25
+ Every candidate is put into exactly one class before it goes into the report.
26
+
27
+ 1. **Intentional decision** (never proposed for change, not a finding): the trade-off is documented as chosen:
28
+ - `rql-code-review` §5 (settled design, priorities design, known limitations kept by the user, `NOTE: (debug)`
29
+ methods, spec exemption of §3 there);
30
+ - wording in the overview/rules/README/code: "on purpose", "kept by the user's decision", "settled", "design
31
+ decision", "rejected", "duplicated on purpose", "intentional", a design `NOTE` next to the code;
32
+ - CLAUDE.md "Rules" (long explicit argument lists, operation-module independence over DRY, etc.);
33
+ - decisions recorded outside the repository (the user's auto-memory of this project, when loaded): the gemspec
34
+ packages `git ls-files` (incl. `.claude/`); `rql-code-review` runs inline (no forked/subagent variant);
35
+ `@raise` YARD tags are not required.
36
+ - The report lists them only as a short "accounted for" line (count + the topics), so the user sees they were
37
+ recognized; an intentional decision whose documentation contradicts the code is still a finding (sync class).
38
+ 2. **Intentionally deferred** (section "Намеренно отложенное" / "Intentionally deferred"; reported, not proposed as
39
+ a fix now): the item is documented as a future fix:
40
+ - "Known debt" / "Temporary debt" (CLAUDE.md, overview "Conventions", `acquirer.md`, `logic.md#16`), `swarm.md`
41
+ "Known quirks", `tests.md` (coverage minimum, rspec-retry, the spec rework);
42
+ - the "Recommendations (proposed, not yet project policy)" sections of the rule files;
43
+ - `TODO` comments in `lib/`, `sig/`, `Rakefile`, workflows (`git grep -n "TODO" -- lib sig Rakefile .github`);
44
+ - README `## Roadmap`: don't copy it; mention a Roadmap item only when the audit found its gap in the code;
45
+ - deferred work from the auto-memory, when loaded (e.g. the inline argument checks: no `check_*` helpers until a
46
+ refactoring; the postponed RW optimization plan; open review findings): verify each against the current code,
47
+ drop the ones that are done (and say so in "Stale instructions" when a repo file still calls them open).
48
+ - Each entry: what, where it is documented, the current state in the code (still present / partly fixed / already
49
+ fixed: then the documentation is stale, a sync finding), the risk if it stays.
50
+ 3. **Finding** (sections by kind, §5): anything else that is wrong, contradictory, stale or fragile. An undocumented
51
+ deviation is a finding even when it looks deliberate: the fix is either the code or the documentation of the
52
+ decision (say which is more plausible; when unsure, ask the user in the report rather than guess).
53
+
54
+ Doubtful cases: a deviation that matches the spirit of a documented decision but not its letter is a finding of the
55
+ "instructions should say it" kind (Minor), never a code change proposal.
56
+
57
+ ## 2. Inventory (read before judging)
58
+
59
+ 1. `git rev-parse --short HEAD`, `git status --porcelain` (uncommitted changes are audited too and marked as such),
60
+ `RedisQueuedLocks::VERSION` (`lib/redis_queued_locks/version.rb`), the CHANGELOG `[Unreleased]` head.
61
+ 2. Instructions: `CLAUDE.md`, `.claude/project-overview.md`, every `.claude/rules/*.md`, every
62
+ `.claude/skills/*/SKILL.md` and templates.
63
+ 3. User docs: `README.md` (TOC, method sections, config block, `## Logging`, `### Instrumentation Events`,
64
+ Requirements, Roadmap, Build and Develop), `CHANGELOG.md`.
65
+ 4. Tooling: `redis_queued_locks.gemspec`, `Gemfile`, `Rakefile`, `spec/support/parallel_runner.rb`, `.rubocop.yml`,
66
+ `.rubocop.rbs.yml`, `Steepfile`, `rbs_collection.yaml`, `.github/workflows/*.yml`.
67
+ 5. Code: `lib/**` (dependency order: `resource.rb`, `config.rb`, `errors.rb`, `utilities.rb`, `acquirer/acquire_lock/*`,
68
+ `acquirer/lock_series/*`, other `acquirer/*`, `lock_keeper*`, `client.rb`, `swarm*`, `logging/`, `instrument/`, then the rest of `lib/`: `config/`, `utilities/`,
69
+ `data.rb`, `debugger*`, `stats/`),
70
+ `sig/**`, `spec/spec_helper.rb`; specs only for coverage (`rql-code-review` §3).
71
+ 6. Build the two ledgers of §1 (intentional, deferred) from these files before looking for findings.
72
+
73
+ Big areas are read in full, not sampled: an audit claim "X holds everywhere" needs the grep that proves it (§4).
74
+
75
+ ## 3. Areas and checks
76
+
77
+ ### A. Instructions ↔ code (does the code follow every rule?)
78
+ - Walk every numbered "Claude rule" of every rule file and every CLAUDE.md "Rules" bullet; for each, check the whole
79
+ codebase (not a diff): the `rql-code-review` §4 A–J checklist applied repository-wide. Record per rule file:
80
+ `ok` or the findings.
81
+ - Repository-wide greps (each one with its expected result):
82
+ - `'rql:`/`"rql:` literals outside `resource.rb`; `'KEYS'`, `.scan(`/`.zscan(` outside the known lookups;
83
+ - `git grep -n LOCK_INDEX_KEY -- lib`: every use behind `lock_index_enabled` (except `ReindexLocks`, `Resource`);
84
+ - cross-module calls `git grep -n "RedisQueuedLocks::Acquirer::" -- lib/redis_queued_locks/acquirer` (only the
85
+ known `WithAcqTimeout` debt and the `LockSeries` uses of the `AcquireLock` mixins);
86
+ - `Struct`/`Data.define`/`OpenStruct`/`**opts`/`options = {}`/`(...)` in `lib/`;
87
+ - `ZREMRANGEBYSCORE` on request queues: per band only (`rql-code-review` §4 C);
88
+ - `.nil?`, `# rubocop:disable all`, missing `# frozen_string_literal: true`
89
+ (`git grep -L "frozen_string_literal: true" -- '*.rb'`);
90
+ - every `lib/**/*.rb` has its `sig/**/*.rbs` mirror and back (`comm` of both file lists, path-mapped);
91
+ - every `Client` public method: `Acquirer::*` module, RBS, README section, spec (`describe`/`it` grep), `!` variant
92
+ where the rules require one, the lock-family options in all four lock methods (`arguments.md#10`);
93
+ - every `setting` in `config.rb`: `validate`, its `Config#[]` overload line in `config.rbs`, the README config
94
+ block, the overview "Configuration" table;
95
+ - every visitor method: the same name in the Log and Instr visitors; every event/log key in README `## Logging` /
96
+ `### Instrumentation Events` and the overview "Instrumentation events";
97
+ - every error class in `errors.rb`: under the right base, in the overview "Errors", raised somewhere (or
98
+ documented as public API kept for compatibility);
99
+ - YARD: `@api`/`@since`/`@version` on every class/module/method; no `@since`/`@version` newer than the unreleased
100
+ version or older than the code that introduced it where git history proves it (`git log -S`).
101
+ - Duplicated logic copies (`rql-code-review` §2 list): every copy pair compared side by side; a diverged copy is a
102
+ Major finding (behavioral divergence) or Minor (cosmetic).
103
+
104
+ ### B. Instructions ↔ instructions (contradictions and dead references)
105
+ - Each fact stated in several places (CLAUDE.md, overview, rule files, `rql-code-review` checklist, README,
106
+ CHANGELOG) says the same: option names and defaults, round-trip counts, key layout, event names, result shapes,
107
+ the paths-ignore list (`git.md#7` ↔ CLAUDE.md ↔ every `.github/workflows/*.yml`), worker/database counts, commands.
108
+ - References resolve: `<file>.md#N` points to a rule N that exists and is about that topic; overview "<section>"
109
+ names exist; `.claude/skills/...` paths, file paths and method/constant names mentioned in the docs exist
110
+ (`git grep -n` each identifier in backticks that looks like code; report the ones absent from `lib/`, `sig/`,
111
+ `spec/`).
112
+ - Renamed or removed things still mentioned (e.g. old option names in any file, `git log --format=%s -30` for recent
113
+ renames and their leftovers).
114
+ - Duplicate or conflicting rules (the same rule in two files with different wording, a rule that forbids what
115
+ another requires); the "Known debt" lists are consistent across CLAUDE.md, overview and rule files.
116
+
117
+ ### C. User docs ↔ code
118
+ - README: every public method, keyword and default, config key and default, result shape, event and payload key,
119
+ error, limitation and requirement matches the code; TOC entries and anchors resolve; `readme.md` rules followed.
120
+ - CHANGELOG: `[Unreleased]` covers the user-visible changes since the last release tag
121
+ (`git describe --tags --abbrev=0`, `git log <tag>..HEAD --format=%s`); entries follow `changelog.md`; the gem
122
+ version in `version.rb` and the latest released section agree.
123
+ - gemspec: Ruby requirement and runtime deps (`redis-client` only) match CLAUDE.md, README Requirements and the CI
124
+ Ruby version.
125
+
126
+ ### D. Defects in the code (the hunt)
127
+ Independent of the instructions, look for real bugs with a concrete scenario: race windows (name the interleaving
128
+ and why `WATCH` does not catch it), reply positions vs the commands of a pipeline/transaction, `nil`/missing key
129
+ handling, `PTTL` sentinels, unit mix-ups, infinite scores, error paths (`ensure`, `rescue` scope, swallowed errors
130
+ outside the documented `rescue nil` of observability), thread/fiber/Ractor safety (shared mutable state, the
131
+ keeper's mutex and interrupts), resource leaks (connections, threads), RBS that does not match runtime values, dead
132
+ code. Concentrate on the lock safety core first (`acquire_lock/*`, `lock_series/*`, `lock_keeper*`, releases), then
133
+ the operations, then the swarm. Every candidate goes through §1 (a documented limitation is not a defect).
134
+
135
+ ### E. Tooling and CI
136
+ - Rake tasks, the parallel runner and the workflows do what the overview "Rake tasks"/"CI" and `tests.md` say;
137
+ workflows use the same Ruby/Redis versions as documented; `.rubocop.yml` has no global loosening that contradicts
138
+ "never tune `.rubocop.yml` to pass" (a pre-existing exclusion documented as intended is fine).
139
+ - Checks (unless `--no-checks`): `bundle exec rake rubocop`; `bundle exec rbs collection install && bundle exec rake
140
+ steep:check` (grep for `ERROR`/`FATAL`; restore a rewritten `rbs_collection.lock.yaml` with
141
+ `git checkout -- rbs_collection.lock.yaml`); with `--with-specs`: `bundle exec rake rspec:parallel` (a failure is
142
+ reported with its output; the known flaky examples of `tests.md` are named as such).
143
+
144
+ ## 4. Verify every finding
145
+
146
+ - Confirm it in the files (quote the line or the grep), never by memory or a pattern alone; `CONFIRMED` (traced) or
147
+ `PLAUSIBLE` (name the assumption). Concurrency, layout, mode and priority claims follow `rql-code-review` §6.
148
+ - Re-check each finding against both ledgers of §1 right before writing the report; drop or reclassify.
149
+ - Severity as in `rql-code-review` §7 (Blocker, Major, Minor, Nit); for docs: a wrong statement about safety, the
150
+ public API or a result shape is Major, a stale reference/typo/wording issue is Minor or Nit.
151
+ - Keep the report proportional: group repeated instances of one issue into one finding with all locations (or the
152
+ first five + count).
153
+
154
+ ## 5. Report
155
+
156
+ Fill `templates/report.<code>.md`. The verdict is exactly one of:
157
+ - **Всё соответствует** / **Everything matches**: no findings of any severity (deferred items may exist);
158
+ - **Соответствует, но есть что обновить/скорректировать** / **Matches, with things to update**: only Major and lower
159
+ findings;
160
+ - **Есть серьёзные несоответствия** / **Serious mismatches**: at least one Blocker (or a Major that breaks lock safety
161
+ or the public API).
162
+
163
+ Sections (empty ones are omitted, except "Intentionally deferred", which is always present when its ledger is not
164
+ empty): code defects; instructions ↔ code; contradictions between instructions; user docs ↔ code; stale instructions
165
+ and dead references; tooling and CI; optional suggestions (from the rule files' recommendations applied to existing
166
+ code: only when cheap and clearly useful, never as violations); intentionally deferred; accounted-for intentional
167
+ decisions (one line); checks; coverage of the audit (areas audited, greps run, what was not audited and why).
168
+
169
+ Each finding: location(s), the problem in one sentence, the source (rule/section/README anchor) it contradicts,
170
+ `CONFIRMED`/`PLAUSIBLE`, the proposed correction and where it belongs (code / instruction / README / CHANGELOG).
171
+ After the report, offer to fix (in the session language), grouped into suggested commits (`git.md` subjects).
@@ -0,0 +1,41 @@
1
+ ## Full project review: <areas> (HEAD <sha>, v<VERSION>[, + uncommitted changes])
2
+ **Verdict:** <Everything matches | Matches, with things to update | Serious mismatches> — <one sentence why>
3
+
4
+ ### Code defects
5
+ 1. `<path>:<line>` — <the defect in one sentence>. [<Blocker | Major | Minor | Nit>] [CONFIRMED | PLAUSIBLE: <assumption>]
6
+ Scenario: <state / interleaving → wrong result>.
7
+ Source: <`acquirer.md#16` | overview "Lock index" | general defect>.
8
+ Fix: <what to do> → <code | instruction | README | CHANGELOG>.
9
+
10
+ ### Instructions ↔ code
11
+ <findings in the same format; each rule file without findings: `<file>.md`: ok>
12
+
13
+ ### Contradictions between instructions
14
+ <findings in the same format: both places and their wording>
15
+
16
+ ### User docs (README, CHANGELOG) ↔ code
17
+ <findings in the same format>
18
+
19
+ ### Stale instructions and dead references
20
+ <findings in the same format>
21
+
22
+ ### Tooling and CI
23
+ <findings in the same format>
24
+
25
+ ### Suggestions (optional)
26
+ - <a rule-file recommendation applied to existing code: what, where, why>
27
+
28
+ ### Intentionally deferred
29
+ - <what> — documented in: <source>; state in the code: <present | partly fixed | already fixed → the docs are stale>; risk if kept: <...>.
30
+
31
+ ### Accounted-for intentional decisions
32
+ <N decisions not proposed for change: <topics, comma-separated>>
33
+
34
+ ### Checks
35
+ - rubocop: <result | skipped (--no-checks)>
36
+ - steep: <result | skipped (--no-checks)>
37
+ - rspec: <not run (no --with-specs) | result>
38
+
39
+ ### Audit coverage
40
+ - Audited: <areas, rule files, key greps>
41
+ - Not audited: <what and why>
@@ -0,0 +1,41 @@
1
+ ## Полное ревью проекта: <области> (HEAD <sha>, v<VERSION>[, + незакоммиченные изменения])
2
+ **Вердикт:** <Всё соответствует | Соответствует, но есть что обновить/скорректировать | Есть серьёзные несоответствия> — <одна фраза почему>
3
+
4
+ ### Дефекты кода
5
+ 1. `<path>:<line>` — <дефект одним предложением>. [<Блокер | Важное | Мелкое | Придирка>] [CONFIRMED | PLAUSIBLE: <допущение>]
6
+ Сценарий: <состояние / интерливинг → неверный результат>.
7
+ Источник: <`acquirer.md#16` | overview "Lock index" | общий дефект>.
8
+ Исправление: <что сделать> → <код | инструкция | README | CHANGELOG>.
9
+
10
+ ### Инструкции ↔ код
11
+ <находки в том же формате; по каждому файлу правил без находок: `<file>.md`: ок>
12
+
13
+ ### Противоречия между инструкциями
14
+ <находки в том же формате: оба места и их формулировки>
15
+
16
+ ### Документация (README, CHANGELOG) ↔ код
17
+ <находки в том же формате>
18
+
19
+ ### Устаревшее и битые ссылки
20
+ <находки в том же формате>
21
+
22
+ ### Инструменты и CI
23
+ <находки в том же формате>
24
+
25
+ ### Предложения (необязательно)
26
+ - <рекомендация из правил, применённая к существующему коду: что, где, зачем>
27
+
28
+ ### Намеренно отложенное
29
+ - <что> — где задокументировано: <источник>; состояние в коде: <есть | частично исправлено | уже исправлено → документация устарела>; риск, если оставить: <...>.
30
+
31
+ ### Учтённые намеренные решения
32
+ <N решений не предлагаются к изменению: <темы через запятую>>
33
+
34
+ ### Проверки
35
+ - rubocop: <результат | пропущен (--no-checks)>
36
+ - steep: <результат | пропущен (--no-checks)>
37
+ - rspec: <не запускался (нет --with-specs) | результат>
38
+
39
+ ### Охват ревью
40
+ - Проверено: <области, файлы правил, ключевые grep'ы>
41
+ - Не проверено: <что и почему>
data/CHANGELOG.md CHANGED
@@ -1,16 +1,38 @@
1
1
  ## [Unreleased]
2
2
 
3
- ## [1.23.1] = 2026-11-01
3
+ ## [1.24.0] - 2026-11-09
4
+ ### Added
5
+ - *Brand New Feature*: **Lock Auto Extending**: a block of code keeps its lock alive while it is running, and the crash of the process releases the lock by the TTL (see README "Lock Auto Extending"):
6
+ - `auto_extend:`, `auto_extend_ttl:` and `max_hold_time_during_auto_extend:` options of `#lock`/`#lock!`/`#lock_series`/`#lock_series!`;
7
+ - `config['is_auto_extended_by_default']`, `config['default_auto_extend_ttl']` and `config['default_max_hold_time_during_auto_extend']` (**!IMPORTANT**: set `max_hold_time_during_auto_extend` deliberately for your logic: `nil` or a period longer than your longest block of code; the default 1 hour is only a fallback);
8
+ - `RedisQueuedLocks::LockKeeper::LockLease`: a block of code with a parameter gets its lease: `#hold_for` moves the hold limit while the block makes progress, `#lost?`, `#hold_time_left`;
9
+ - `timed: true` with `auto_extend: true`: the block of code is limited by `max_hold_time_during_auto_extend` (or the moved limit) and is interrupted when the lock is lost: `TimedBlockExceedsMaxHoldTimeError`, `TimedBlockLostLockError` (fiber scheduler tasks too: through `Fiber::Scheduler#fiber_interrupt`, e.g. `async` >= 2.25);
10
+ - `config['lock_keeper.*']`: the tuning of the lock keeper thread (idle timeout, wake-ups, retries, batching, schedule slots, fiber interruption wait);
11
+ - instrumentation events and logs: `lock_auto_extended`, `lock_auto_extension_failed`, `auto_extended_lock_lost`, `lock_hold_limit_reached`, `lock_hold_limit_extended`; `try_lock.exit__reentrant_lock_is_changed` log;
12
+ ### Removed
13
+ - `RedisQueuedLocks::Utilities::RUBY_OVER_4` and `RedisQueuedLocks::Utilities.ruby_over_4?`: always `true` (Ruby >= 4.0 is required);
14
+ ### Fixed
15
+ - `#lock`/`#lock!`: a lock obtained right at the acquirement `timeout` was kept till its ttl while the acquirement failed
16
+ with `:timeout_reached` (`LockAcquirementTimeoutError`);
17
+
18
+ ## [1.23.1] - 2026-11-01
4
19
  ### Added
5
20
  - `timed: true` of `#lock`/`#lock_series`: separate errors of the failures, both are `TimedLockTimeoutError` subclasses: `LockTtlTimeBudgetIsSpentError` (the block was not invoked: no time left) and `TimedBlockExceedsLockTtlError` (the block exceeded the lock TTL);
6
21
  ### Fixed
7
22
  - `timed: true` of `#lock`/`#lock_series`: in some cases the time budget of the block could have been a little bit longer than the lock lifetime (2ms);
8
23
 
9
24
  ## [1.23.0] - 2026-11-01
25
+ ### Added
26
+ - `#lock_series` instrumentation events and logs: `lock_series_obtaining_failed` of the series and the events of each lock of the series:
27
+ `lock_series_intermediate_lock_obtained`, `lock_series_lock_obtained`, `lock_series_lock_obtaining_failed`;
28
+ - `reentrant_lock_keys` key of the `lock_series_obtained` and `lock_series_hold_and_release` events and logs;
29
+ - the logs of the series acquirement: `start_try_to_lock_series_cycle`, `dead_score_reached__reset_series_position`,
30
+ `dequeue_from_lock_series_queues`, `decrease_lock_series`;
31
+ - RBS signatures of `#lock_series`/`#lock_series!`;
10
32
  ### Changed
11
33
  - [**Breaking**] `#lock_series`/`#lock_series!` are no longer a proof of concept. The final feature design:
12
- - all locks are obtained atomically with the same;
13
- TTL, nothing is held while the series waits, any order of the lock names is deadlock-free (see README "lock_series"):
34
+ - all locks are obtained atomically with the same TTL, nothing is held while the series waits, any order of the lock
35
+ names is deadlock-free (see README "lock_series");
14
36
  - each lock gets exactly `ttl:` (it was `position * (ttl + retry_delay + retry_jitter)`);
15
37
  - `timeout:`, `retry_count:` and `queue_ttl:` limit the whole series (they limited each lock of the series);
16
38
  - a series without a block returns `{ ok: true, result: { lock_series:, rql_lock_series:, acq_id:, hst_id:, ts:, ttl: } }` (it returned `nil`);
@@ -21,13 +43,6 @@
21
43
  - an empty series raises `RedisQueuedLocks::ArgumentError`, duplicated lock names are one lock;
22
44
  - upgrade all processes that share these locks: older versions obtain a series lock by lock;
23
45
  - [**Breaking**] `read_write_mode:` option of `#lock`/`#lock!`/`#lock_series`/`#lock_series!`/`#extend_lock_ttl` is renamed to `rw_mode:`;
24
- ### Added
25
- - `#lock_series` instrumentation events and logs: `lock_series_obtaining_failed` of the series and the events of each lock of the series:
26
- `lock_series_intermediate_lock_obtained`, `lock_series_lock_obtained`, `lock_series_lock_obtaining_failed`;
27
- - `reentrant_lock_keys` key of the `lock_series_obtained` and `lock_series_hold_and_release` events and logs;
28
- - the logs of the series acquirement: `start_try_to_lock_series_cycle`, `dead_score_reached__reset_series_position`,
29
- `dequeue_from_lock_series_queues`, `decrease_lock_series`;
30
- - RBS signatures of `#lock_series`/`#lock_series!`;
31
46
 
32
47
  ## [1.22.0] - 2026-10-27
33
48
  ### Added
data/CLAUDE.md CHANGED
@@ -7,17 +7,19 @@ Full details (config keys, key layout, events, errors, stack, CI): `.claude/proj
7
7
  - Tests (need a running local Redis): `bundle exec rake rspec:parallel` by default (~1 min; `WORKERS=<n>`, default: Redis `databases` / 2 up to the CPU count; each worker flushes its own pair of databases: db 0..2n-1 in total); the serial `bundle exec rake rspec` (~6 min) only when something must be checked in one process (order-dependent failures, a whole-suite `--seed`, leaks between examples, changes of the parallel runner: `tests.md#1`)
8
8
  - Lint: `bundle exec rake rubocop` (two passes, Ruby then RBS: both must be clean; never tune `.rubocop.yml` to pass, fix the code)
9
9
  - Static types: `bundle exec rbs collection install && bundle exec rake steep:check`
10
+ - Reviews: `rql-code-review` (a diff: branch, PR, uncommitted; also the pre-commit review), `rql-project-full-review` (on request only: the whole repository, instructions ↔ code ↔ each other + a defect hunt; intentional decisions are not findings, deferred items get their own section)
10
11
 
11
12
  ## Architecture
12
13
  - `client.rb`: public API facade; fills defaults from `config[...]`, delegates to `Acquirer::*`.
13
14
  - `acquirer/*.rb`: one stateless module per operation (`class << self`), returns `{ ok:, result: }`; `!` client methods raise.
14
15
  - `acquirer/acquire_lock.rb`: composed via `extend` mixins in `acquire_lock/` (try_to_lock, with_acq_timeout, delay_execution, dequeue_from_lock_queue, yield_expire) + `LogVisitor`/`InstrVisitor` event hooks.
15
- - Locking: `ZADD NX` into the request queue, then WATCH/MULTI; Lua only for write TTL extension/decrease.
16
+ - Locking: `ZADD NX` into the request queue, then WATCH/MULTI; Lua only for write TTL extension/decrease, the owner-checked release/decrease (a lease, an interrupted obtaining) and the lock keeper extensions (not the acquirement).
16
17
  - Lock request priorities (`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; `config['default_lock_priority']`): queue score = enqueue time - priority * 2**32 (`Resource.calc_initial_acquirer_position`), strict priority + FIFO inside a priority; dead requests are pruned per priority band (never one `-inf..now-ttl` range): the own band on each queueing, the bands of the dead requests that block the attempt (the write queue head, the earlier opposite-mode request) in one more round trip (`TryToLock#drop_dead_requests_ahead`, band and liveness decoded from the score); the attempt cost never depends on the priority range; every lock acquirement log/event carries the Integer `priority`. Component map: overview "Lock request prioritization in the architecture"; details: overview "Lock request priorities".
17
18
  - Read/Write locks (`rw_mode: :write|:read`): write lock `rql:lock:<name>` + queue `rql:lock_queue:<name>`; readers registry `rql:lock_readers:<name>` (ZSET acq_id => Redis-time expiry), read queue `rql:lock_read_queue:<name>`, per-reader data `rql:lock_reader:<name>:<acq_id>`. Readers WATCH the write key only, writers WATCH the write key + registry; queues give ordering only. Component map: overview "Read/Write locks in the architecture"; details: overview "Read/Write locks".
18
19
  - Lock lookup modes: `config['lock_index_enabled']` (client-wide, `false` by default) is read by `Client`/`Swarm` and passed to every lock-iterating module (swarm, `locks`, `queues`, `keys`, `clear_*`) and to the hot path; each module keeps the keyspace lookup (one `SCAN` pass, the pre-index code) and the lock index lookup (one `ZSCAN` pass) side by side with the shared processing in one copy.
19
20
  - Lock index `rql:index:locks` (enabled mode only; ZSET lock name => upper bound of the lifetime of all lock keys, client ms + ttl + `lock_index_grace_period`): every key-creating command is followed by `ZADD GT` (queueing pipeline, obtaining `MULTI`), every extension by `ZADD XX INCR`, names are removed only with all their keys (`unlock`, `clear_locks`), queues have TTL, expired names are pruned on queueing; lock index commands are conditional tails of their pipelines/transactions (none in the disabled mode); `reindex_locks` (one keyspace `SCAN`, both modes) adopts keys without entries after enabling. Details: overview "Lock index".
20
21
  - Lock series (`acquirer/lock_series.rb`, `lock_series/`): all locks obtained by one WATCH/MULTI attempt with one `ttl` (all or nothing, nothing held while waiting), one queue position in all queues of the series (deadlock-free for any order of names), limits of the whole series; details: overview "Lock series".
22
+ - Lock auto extension (`lock_keeper.rb`, `lock_keeper/`, `auto_extend:`, `auto_extend_ttl:`, `max_hold_time_during_auto_extend:`): one lazy thread per `Client` with its own connection (`redis_client.config.new_client`) renews the locks of running blocks: one `Lease` per block, one pipeline per tick, Lua with an owner check ("live N ms from now", never a sum, never revives a lost lock); the hold limit stops the renewal; a block with parameters gets its `LockLease` (`lock_keeper/lock_lease.rb`: `hold_for` moves the hold limit and extends the locks at once, `lost?`, `hold_time_left`; a `timed` block is interrupted at the limit by the keeper, no `Timeout`: `Thread#raise` in a blocking fiber, `Fiber::Scheduler#fiber_interrupt` in a non-blocking one; a scheduler without the hook keeps the `Timeout`); a block with a lease releases its lock with an owner check; the acquirement is the same (`TryToLock` only repeats a reentrant attempt aborted by a tick). Details: overview "Lock auto extension".
21
23
  - Strategies: `access_strategy` `:queued`|`:random`; `conflict_strategy` `:wait_for_lock`|`:work_through`|`:extendable_work_through`|`:dead_locking`.
22
24
  - `resource.rb`: all key names and acquirer/host IDs. `config.rb`: `setting`/`validate` DSL, read as `config['a.b']`.
23
25
  - `swarm/`: zombie-lock cleanup. `Supervisor` thread revives `ProbeHosts` (`SwarmElement::Threaded`) and `FlushZombies` (`SwarmElement::Isolated`, Ractor talking via `Ractor::Port`s); each element runs a main-loop thread with its own Redis connection.
@@ -25,7 +27,7 @@ Full details (config keys, key layout, events, errors, stack, CI): `.claude/proj
25
27
  - `sig/`: RBS mirror of `lib/`. `spec/redis_queued_locks_spec.rb`: single integration spec (+ Redis-free `spec/redis_queued_locks/config_spec.rb`).
26
28
 
27
29
  ## Rules
28
- Detailed, path-scoped rules in `.claude/rules/`: `logic.md` (lib, general), `acquirer.md` (acquirer modules, Redis access), `visitors.md` (log/instrumentation visitors), `arguments.md` (long keyword lists), `swarm.md` (swarm supervisor/elements, Ractor/Thread rules), `tests.md` (spec), `type-checking.md` (sig/Steep), `changelog.md` (CHANGELOG entries), `git.md` (commit messages and commit flow, always loaded).
30
+ Detailed, path-scoped rules in `.claude/rules/`: `logic.md` (lib, general), `acquirer.md` (acquirer modules, Redis access), `visitors.md` (log/instrumentation visitors), `arguments.md` (long keyword lists), `swarm.md` (swarm supervisor/elements, Ractor/Thread rules), `tests.md` (spec), `type-checking.md` (sig/Steep), `changelog.md` (CHANGELOG entries), `readme.md` (README sync, paired with `logic.md#12`), `git.md` (commit messages and commit flow, always loaded).
29
31
  - Long explicit keyword/parameter lists are intentional (minimal allocations, signature-as-DSL): never introduce parameter objects, option structs or `**opts`; add new options as explicit keywords to every `Client` variant and forward them by name.
30
32
  - Update the matching `sig/*.rbs` for every `lib/` change; keep Steep green.
31
33
  - Keep `# frozen_string_literal: true` and YARD `@api`/`@since`/`@version` tags (`# @since` right above each `include`/`extend`/`prepend` line; class/module `@version` changes only with the interface: signatures, added/removed methods, `extend`/`include`/`prepend`, the superclass; `logic.md#2`).
@@ -34,8 +36,8 @@ Detailed, path-scoped rules in `.claude/rules/`: `logic.md` (lib, general), `acq
34
36
  - Operation modules behind `Client` methods (all `Acquirer::*` except the lock acquisition core: `AcquireLock` and `LockSeries`, which reuses the `AcquireLock` mixins) are independent: they never call each other or reference each other's RBS types, share logic only via `Resource`/`Utilities`, and duplicate similar logic on purpose (independence over DRY; e.g. `Locks` duplicates the `LockInfo` formatting). Details: `acquirer.md`.
35
37
  - New option: `setting` (+ `validate`) in `config.rb` + its `Config#[]` overload line in `sig/redis_queued_locks/config.rbs` (typed per key).
36
38
  - Dev gems go in `Gemfile`, not the gemspec.
37
- - Commits (`git.md`): subject only `[<scope>] <summary>` (several features: 1-2 words each, comma-separated), no body; when a step is complete (requirement fully implemented, specs/rubocop/steep green), and only then, run the `rql-code-review` skill on the uncommitted changes, then ask before committing, with the proposed subject, a recap of the changes and the review verdict; an explicit "commit" request needs no extra question and no review (a commit authorized in advance for a task still gets the review); never on `master`, never push.
38
- - Before implementing, read the relevant sections of `.claude/project-overview.md` (key layout, lock flow, "Read/Write locks", events) and keep their invariants. In the same change, update the overview and the affected `.claude/rules/*.md` for every new/changed key, option, result shape, event, algorithm step or limitation (and README/CHANGELOG `[Unreleased]` for user-visible behavior; CHANGELOG entries are compact: only the subject-level change in 1-2 lines, no implementation details; a fundamentally new feature or globally new support is a separate `*Brand New Feature*` entry, `changelog.md`). New or changed log keys / instrumentation payload keys (visitors or inline `notify`) also go to README `## Logging` / `### Instrumentation Events` (see `visitors.md`).
39
+ - Commits (`git.md`): subject only `[<scope>] <summary>` (several features: 1-2 words each, comma-separated), no body; when a step is complete (requirement fully implemented, specs/rubocop/steep green), and only then, run the `rql-code-review` skill on the uncommitted changes, then ask before committing, with the proposed subject, a recap of the changes and the review verdict; an explicit "commit" request needs no extra question and no review (a commit authorized in advance for a task still gets the review); never on `master`, never push. A change of the gem docs files only (`README.md`, `CHANGELOG.md`, `CODE_OF_CONDUCT.md`, `LICENSE.txt`: the `paths-ignore` of the workflows) needs no local test run before the commit and no wait for the GitHub CI after the push (CI skips such pushes).
40
+ - Before implementing, read the relevant sections of `.claude/project-overview.md` (key layout, lock flow, "Read/Write locks", events) and keep their invariants. In the same change, update the overview and the affected `.claude/rules/*.md` for every new/changed key, option, result shape, event, algorithm step or limitation (and README/CHANGELOG `[Unreleased]` for user-visible behavior; CHANGELOG entries are compact: only the subject-level change in 1-2 lines, no implementation details; a fundamentally new feature or globally new support is a separate `*Brand New Feature*` entry, `changelog.md`). New or changed log keys / instrumentation payload keys (visitors or inline `notify`) also go to README `## Logging` / `### Instrumentation Events` (see `visitors.md`). What else changes in README (method sections, config block, TOC, intro, Roadmap, Requirements, Build and Develop, anchors, whitespace): `readme.md`, paired with `logic.md#12`.
39
41
  - Observability (`logic.md#16`): logic that creates/changes/deletes keys is logged and instrumented: the lock acquirement per meaningful outcome (visitors), each mutation operation with one log line + one event of the whole root operation called by `Client` (inline, `instrument` last in the payload); lock info queries are neither; the swarm elements are known debt.
40
42
  - Lock-touching code is read/write-aware and index-aware: any operation over locks, queues, zombies or lock info must cover the read family (`rql:lock_readers:*`, `rql:lock_read_queue:*`, `rql:lock_reader:*`) next to `rql:lock:*`/`rql:lock_queue:*`, and any new key-creating/extending command must keep the lock index a superset of the existing locks (enabled mode); a new lock-iterating operation implements both lookups (keyspace and lock index, `lock_index_enabled`). Mutual exclusion comes only from WATCH/MULTI on lock state (no Lua in the RW acquisition path unless asked); queues never guarantee safety.
41
- - Known debt: rspec-retry, disabled coverage minimum.
43
+ - Known debt: rspec-retry, disabled coverage minimum, the swarm README docs (pending rework: its exceptions live in `readme.md#9` and are removed with it).