stream_single_writer.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. """Best-effort accessors for the single-writer stream fence.
  2. The fence lives on ``AIAgent`` (``_claim_stream_writer`` / ``_stream_writer_is_current``) but is
  3. used from other streaming modules. Calling it directly would turn an *additive* safety net into a
  4. fatal AttributeError on a partially-updated checkout, hot-reloaded gateway, duck-typed agent, or
  5. test double (a cron job died this way). The fence may only drop a *provably* superseded stream,
  6. never the sole writer, so when it is unavailable or raises the degradation is "no fence".
  7. """
  8. from __future__ import annotations
  9. import logging
  10. from typing import Any
  11. logger = logging.getLogger(__name__)
  12. def claim_stream_writer(agent: Any) -> int:
  13. """Claim the delta sink for this stream attempt; ``0`` (never fenced) when the agent lacks the fence or the claim raised."""
  14. return _fence_call(agent, "_claim_stream_writer", int, 0, "claim failed; proceeding unfenced")
  15. def stream_writer_is_current(agent: Any, token: int) -> bool:
  16. """True when ``token`` is still the active writer; a falsy token or a fence-less agent cannot prove supersession, so True."""
  17. if not token:
  18. return True
  19. return _fence_call(agent, "_stream_writer_is_current", bool, True, "is_current check failed; treating as current", token)
  20. def _fence_call(agent: Any, name: str, cast, fallback, failure_note: str, *args):
  21. """Call ``agent.<name>(*args)`` when it exists; ``fallback`` when missing or raising (logged at debug)."""
  22. fn = getattr(agent, name, None)
  23. if callable(fn):
  24. try:
  25. return cast(fn(*args))
  26. except Exception:
  27. logger.debug("stream single-writer: %s", failure_note, exc_info=True)
  28. return fallback