Skip to content

refactor(redis): every SingleFlightLock renew and release is one Lua script (#4028) - #4251

Merged
vybe merged 1 commit into
devfrom
AndriiPasternak31/issue-4028
Nov 5, 2026
Merged

vybe merged 1 commit into
devfrom
AndriiPasternak31/issue-4028

Conversation

@AndriiPasternak31

@AndriiPasternak31 AndriiPasternak31 commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Closes #4028

What changes

SingleFlightLock.refresh_if_owned and release_if_owned were GET-then-EXPIRE and GET-then-DELETE. If a holder's lease lapsed between the two commands and a successor won SET NX in that gap, the second command extended or deleted the successor's lease, and two holders ran at once. Now both methods are one Lua script each: the token compare and the mutation happen inside Redis.

  • One method per action. The atomic bodies (added as _atomic siblings in trinity-enterprise#695) take the plain names. The non-atomic bodies and the _atomic names are gone. Every caller is now atomic without a call-site change, except the three that used _atomic (system_service, memory_service), which are renamed.
  • The fleet restart keeps its re-take, atomically and opt-in. refresh_if_owned(retake_lapsed=True) runs one script that renews our token, or re-takes an absent key with SET NX (REACQUIRED), or reports another token (LOST). Only fleet_ops_service passes it, so its bug: fleet-restart lock — lease refresh isn't ownership-checked, and acquisition sits outside the try/finally (#1912 review follow-up) #1919 behaviour (finish a half-done run after an unclaimed lapse, lease_reacquired audited) is unchanged. By default a lapsed lease is LOST and never re-taken, which is what system apply relies on. With the re-take, LOST means another token holds the key, so last_current and the foreign/absent log word are removed and stopped_early="lease_lost_foreign" stays accurate.
  • One home for the scripts. LEASE_REFRESH_LUA, LEASE_REFRESH_OR_RETAKE_LUA and LEASE_RELEASE_LUA live in redis_breaker_util, in KEYS[1] form. The canary leader lease drops its private copies and uses them. They are registered on the injected client at each call, with no process-wide cache: building a Script is a local sha1, and redis-py reloads it on NOSCRIPT.
  • Replies are parsed strictly. Anything other than the script's ASCII integers is DEGRADED, never OWNED, and never raised ('²' and b'\xff' included). A client that never executed the script (for example a MagicMock, where int(MagicMock()) is 1) used to read as a held lease.
  • The KEYS/SCAN guard is narrowed, not weakened. test_helper_has_no_KEYS_or_scan refused the substring KEYS anywhere in the file, and that is why the earlier atomic scripts passed the key through ARGV. It now refuses the scan command as an attribute call (.keys(, .scan (, .scan_iter(), as a string literal in any case (execute_command('keys'), redis.pcall('SCAN'), getattr(client, 'keys')), and as the bare words SCAN / KEYS, while allowing a script's KEYS[n]. A parametrised test proves 14 spellings are refused, including 7 that the old substring guard also missed. Dispatch built from string pieces is beyond any text guard.

Tests

fakeredis here has no Lua, so with these methods on scripts, 11 test files would have stopped checking anything without any error. fakeredis turns a script call into a swallowed unknown command 'evalsha', a MagicMock reads as owned, and hand-written fakes released nothing. tests/unit/_ent695_lua.py is now the one executing emulator:

  • LeaseRedis runs client commands and scripts over one store, and its race hook fires only inside client-side commands, never inside a script.
  • SET NX EX is supported, values are compared as bytes the way Redis compares them, an if tests Lua truth (0 is true), a chained comparison is refused, and a non-positive TTL deletes the key (EXPIRE) or errors (SET EX), as Redis does.
  • with_lua(client) gives a fakeredis client an executing register_script.

Every lock client in the caller tests now runs the real script text.

  • New race tests: a successor that wins inside a client-side GET is neither renewed nor deleted, for the default refresh, the re-take refresh and the release. They are red on the old methods: "the stale holder re-armed the successor's lease" (TTL 60, expected 17) and "the stale holder deleted the successor's lease".
  • Mutations of the production code, each red: compare inverted (refresh / re-take / release), compare dropped (release), args swapped (refresh), NX dropped from the re-take, a coercing reply parse, the default refresh re-taking, release not gated on held, and the fleet restart not passing retake_lapsed. 10/10 red.
  • Checked against a real Redis (7.4 with the backend ACL from docker-compose.yml, and 6.2): own / absent / foreign key × str and bytes clients give the expected OWNED / LOST / REACQUIRED, a release leaves a foreign key alone, and a release after SCRIPT FLUSH still deletes our key (NOSCRIPT reload). The emulator matches Redis on all three production scripts.
  • The canary heartbeat is pinned to never re-take a lapsed lease (it is red with the heartbeat switched to the re-take script), and the memory retain lease now has a test that releases a won lease. Its call site swallows errors, so a wrong method name there was invisible before.
  • Two fleet-restart tests modelled command gaps that no longer exist ("absent at GET, loses SETNX" and "EXPIRE returns 0"). They are replaced by the cases that can happen at the script boundary: a successor inside the lapse is never overwritten, and an unreadable reply fails open.

Validation: the 33 test files that touch the lock, its callers, the canary or the apply engine: 1238 passed under pytest-randomly with seeds 2026, 4028 and 91731. No local full suite; CI runs it.

Mutation: 10/10 production mutations red (listed under Tests). Two further tests are red on the code without their fix: odd replies ('²', b'\xff', fullwidth digit) and the canary heartbeat switched to the re-take script.

Unverified: not run against a live Trinity stack. Real-Redis behaviour of the three scripts was checked on throwaway Redis 7.4 and 6.2 servers outside the stack. tests/unit/test_ent1022_retrieval_memory.py (the other memory-lease test) can't import locally because numpy is missing from the local venv; CI has it.

Not in this PR

Upgrade note

Every SingleFlightLock renew and release now needs Redis scripting. The bundled compose files already grant +@scripting. An operator running an external Redis whose ACL lacks it was served by the old GET and DELETE; now a release silently leaves the key until its TTL, and ops:fleet_restart answers 409 for up to 2100s after a run. Grant +@scripting before upgrading.

Journey Impact: none: internal lock primitive; no user journey changes

…script (#4028)

refresh_if_owned / release_if_owned were GET-then-EXPIRE and GET-then-DELETE:
a holder whose lease lapsed between the two commands extended or deleted the
successor's lease, and two holders ran at once. The atomic bodies added for
the apply lock now carry the plain names; the non-atomic ones are gone.

- refresh_if_owned(retake_lapsed=True) renews, or re-takes an absent key with
  SET NX, in one script. Only the fleet restart passes it, keeping its #1919
  re-take; by default a lapsed lease is LOST, as system apply relies on.
- One home for the lease scripts (LEASE_*_LUA, KEYS[1] form); the canary
  leader lease uses them and is pinned to never re-take. Registered on the
  client per call, no process-wide cache.
- A reply that is not one of the script's ASCII integers is DEGRADED, never
  OWNED, and never raised.
- The KEYS/SCAN guard refuses the scan command as an attribute call, as a
  string literal in any case, and as the bare words, and admits a script's
  KEYS[n]; 14 spellings are pinned.
- tests/unit/_ent695_lua.py is the one executing emulator (race hooks on
  client commands only, SET NX EX, byte compare, Lua truth, non-positive TTLs,
  with_lua for fakeredis); every lock client in the caller tests runs the real
  script text, and the memory retain lease gets a release test.
@vybe

vybe commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

merge-train (2026-11-04): validated READY at cd0777624. I added an upgrade note to this PR's description, since a custom Redis ACL without +@scripting loses lock release with this change. No code was pushed to this branch.

Notes that ride with it and do not block:

  • Deleting release_if_owned stays green at agent_service/ephemeral.py:206, git_service/token_scrub.py:371 and subscription_headroom_service.py:485. These tests are outside this diff, so the gap looks older than this PR. It was not re-run on dev.
  • Changing system_service.py:4233 to retake_lapsed=True stays green. The impact is small, because ApplyLeaseKeeper stops on any non-OWNED result.
  • A failed release is silent. One log line would make the missing-ACL case diagnosable. That is the author's call.

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

merge-train: batch validated on train/20261105-0424 (#4266), all gates green.

@vybe
vybe merged commit b891c5d into dev Nov 5, 2026
28 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants