session_retry_admission.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. """Messaging ``/retry`` under a session authority: the transcript rewrite commits in the re-sent
  2. turn's own admission transaction (#139257 step 2, MSG-11).
  3. ``/retry`` drops the last exchange and re-sends its user text. Rewriting first and admitting
  4. afterwards loses the turn whenever admission refuses (a drain or retirement that begins after the
  5. pre-check, a full FIFO). Here the handler only PLANS the rewrite: it reads the transcript, pins the
  6. active row ids it read, and binds the plan to the re-send. ``admit_native`` takes the binding and
  7. runs the rewrite as a write guard after its own admission gate and queue cap, in the same
  8. ``BEGIN IMMEDIATE`` that inserts the row. A refusal rolls both back; a transcript that changed since
  9. the read refuses both (``RetryRewriteRefused``).
  10. """
  11. from __future__ import annotations
  12. import sqlite3
  13. from contextvars import ContextVar
  14. from dataclasses import dataclass, field
  15. from typing import Any, Callable, Optional
  16. from hermes_state_runtime import RuntimeStoreError
  17. _bound: ContextVar[Optional[RetryRewrite]] = ContextVar('retry_rewrite', default=None)
  18. class RetryRewriteRefused(RuntimeError):
  19. """The planned rewrite no longer applies (the transcript changed since the read, a turn lease is
  20. live, the session closed): the re-send was refused with it and nothing was written."""
  21. @dataclass
  22. class RetryRewrite:
  23. """One ``/retry`` rewrite, applied at most once inside the re-send's admission write."""
  24. db: Any
  25. session_id: str
  26. source: Any # the re-send's own SessionSource object: only that admission takes the binding
  27. write: Callable[[Any], None] # (conn) -> None, inside the admission transaction
  28. on_commit: Callable[[], None] # on the loop, once the admission that applied it committed
  29. applied: bool = False
  30. taken: bool = field(default=False, repr=False)
  31. def guard(self, conn):
  32. self.applied = False # the writer may retry the whole transaction
  33. try:
  34. self.write(conn)
  35. except (RuntimeStoreError, sqlite3.OperationalError):
  36. raise # gate refusals and writer contention keep their own handling
  37. except Exception as exc:
  38. raise RetryRewriteRefused(str(exc)) from exc
  39. self.applied = True
  40. def bind(rewrite: RetryRewrite):
  41. return _bound.set(rewrite)
  42. def unbind(token) -> None:
  43. _bound.reset(token)
  44. def take(event, db) -> Optional[RetryRewrite]:
  45. """The bound rewrite for this native admission, once, and only for the re-send itself (the same
  46. source object on the same store). A drain task inheriting the context never takes it."""
  47. rewrite = _bound.get()
  48. if (rewrite is None or rewrite.taken or getattr(event, 'source', None) is not rewrite.source
  49. or rewrite.db is not db):
  50. return None
  51. rewrite.taken = True
  52. return rewrite
  53. def compose(rewrite: Optional[RetryRewrite], authorize):
  54. """``authorize`` (the admission gate) first, then the rewrite, in one write transaction."""
  55. if rewrite is None:
  56. return authorize
  57. def guard(conn):
  58. authorize(conn)
  59. rewrite.guard(conn)
  60. return guard