Skip to content

fix(cache): synchronize _ensure_eviction_task execution with threading.Lock (#133) - #143

Merged
alialfostovar merged 2 commits into
Baseryn:release/v0.1.0-rc.3from
dwaddle:fix/cache-eviction-thread-safety
Oct 20, 2026
Merged

alialfostovar merged 2 commits into
Baseryn:release/v0.1.0-rc.3from
dwaddle:fix/cache-eviction-thread-safety

Conversation

@dwaddle

@dwaddle dwaddle commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

Summary

This PR addresses #133 by guarding background memory eviction task creation in zcore.cache.base with a threading.Lock double-checked initialization pattern.

Changes

  1. Thread-Safe Eviction Task Scheduling: Added _eviction_lock = threading.Lock() in zcore.cache.base. In _ensure_eviction_task(), the loop check and loop.create_task(_start_eviction_loop(...)) assignment are guarded via with _eviction_lock: with double-checked verification.
  2. Synchronized Shutdown in close_cache(): Wrapped _eviction_task retrieval and clearing inside with _eviction_lock: to prevent concurrent threads from scheduling a new task while shutdown is in flight.
  3. Regression Tests: Added test_ensure_eviction_task_concurrent_thread_safety in tests/test_cache.py exercising concurrent invocation across 20 threads to guarantee exactly one eviction loop task is spawned.

Verification

  • uv run ruff format --check: Passed cleanly.
  • uv run ruff check: Passed cleanly.
  • uv run --all-extras pytest: 516/516 passed.

Closes #133.

@alialfostovar alialfostovar 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.

Hi @dwaddle,

Wow, this is an exceptionally clean implementation of the double-checked locking pattern! The test with threading.Barrier(20) is brilliant and ensures rock-solid thread safety.

I was actually touching this area last night, but your approach and test suite are far superior and more robust.

Approving and merging this into release/v0.1.0-rc.3. Thank you for elevating the quality of ZCore! 🚀

@alialfostovar
alialfostovar changed the base branch from master to release/v0.1.0-rc.3 October 20, 2026 18:02
@alialfostovar
alialfostovar merged commit 055923e into Baseryn:release/v0.1.0-rc.3 Oct 20, 2026
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.

bug: Unsynchronized _ensure_eviction_task execution under multi-threaded event loop initialization

2 participants