Skip to content

Fleet WS-00G: add Legion::Cache.set_nx#15

Merged
Esity merged 2 commits into
mainfrom
fleet/ws-00g-cache-set-nx
Apr 14, 2026
Merged

Fleet WS-00G: add Legion::Cache.set_nx#15
Esity merged 2 commits into
mainfrom
fleet/ws-00g-cache-set-nx

Conversation

@Esity

@Esity Esity commented Apr 14, 2026

Copy link
Copy Markdown

Summary

  • Adds Legion::Cache.set_nx(key, value, ttl:) — an atomic set-if-not-exists primitive required by the fleet pipeline for distributed race coordination
  • Returns true if the key was written (won the race), false if the key already existed
  • Implemented across all three drivers with consistent semantics

Driver implementations

Driver Mechanism
Redis conn.set(key, serialized, nx: true, ex: ttl) — native Redis NX flag
Memcached conn.add(key, value, ttl) — Dalli's atomic add semantics
Memory (lite mode) Mutex-guarded check-expire-set in a single critical section

The facade (Legion::Cache) routes through memory → local → shared adapter following the same pattern as set_sync.

Test plan

  • Spec: win semantics (key absent → returns true, value stored)
  • Spec: lose semantics (key present → returns false, original unchanged)
  • Spec: expired key treated as absent (Memory driver)
  • Spec: 10-thread concurrency — exactly one thread wins
  • Spec: serialization pass-through (Redis driver)
  • Spec: interface contract in cache_interface_spec.rb
  • 409 examples, 0 failures
  • rubocop: 0 offenses

Adds Legion::Cache.set_nx(key, value, ttl:) — a compare-and-set
primitive that returns true if the key was written (race won) and
false if the key already existed.

- Redis: conn.set(key, serialized, nx: true, ex: ttl)
- Memcached: conn.add(key, value, ttl) — native atomic add semantics
- Memory: mutex-guarded check-and-set with TTL expiry awareness
- Facade (Legion::Cache): routes to the active driver; falls back
  through local/memory tiers following the same pattern as set

Specs cover: win/lose semantics, TTL expiry, concurrency (10 threads),
  serialization pass-through, and the public interface contract.

Also fixes a pre-existing helper_spec JSON key assertion that broke
when Legion::JSON.dump switched to pretty-print output.
@Esity Esity requested a review from a team as a code owner April 14, 2026 00:04
@Esity Esity merged commit 7b0c595 into main Apr 14, 2026
15 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.

1 participant