hermes_state_mutation_guards.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. """Transcript mutation guards evaluated on the receipt's writer connection."""
  2. from hermes_state_common import _ENDED_ROW_SQL, _ended_by_compression
  3. from hermes_state_errors import SessionCompressionInProgressError, SessionTurnLeaseLostError
  4. from hermes_state_runtime import RuntimeStoreError
  5. # What ``require_idle``'s transcript-guard check raises when a live turn lease or a
  6. # compression lock protects a target: the same retryable "busy" verdict as a running
  7. # admission, so mutation surfaces map it to 409 rather than letting it escape as a 500.
  8. MUTATION_GUARD_REFUSALS = (SessionTurnLeaseLostError, SessionCompressionInProgressError)
  9. def busy_refusal(exc):
  10. """The client-facing refusal for one of ``MUTATION_GUARD_REFUSALS``. A held compression lock
  11. is named in ``field``: Stop does not end it, so clients say to wait instead."""
  12. compressing = isinstance(exc, SessionCompressionInProgressError)
  13. return RuntimeStoreError('session_busy', field='compression' if compressing else None)
  14. def require_not_executing(conn, session_ids):
  15. """Refuse while a turn is running (or its outcome is unknown) on any of ``session_ids``.
  16. Queued admissions are allowed: a follower waits on the logical owner and simply runs
  17. against whatever physical target the mutation publishes. Workers have no queued state
  18. (registered/running/unknown are all live), so any non-terminal worker is executing."""
  19. for sid in session_ids:
  20. admissions = conn.execute("SELECT status FROM session_admissions WHERE target_session_id=? AND status IN ('started','unknown')", (sid,)).fetchall()
  21. workers = conn.execute("SELECT status FROM worker_executions WHERE session_id=? AND status IN ('registered','running','unknown')", (sid,)).fetchall()
  22. states = {row[0] for row in [*admissions, *workers]}
  23. if 'unknown' in states:
  24. raise RuntimeStoreError('unknown_execution')
  25. if states:
  26. raise RuntimeStoreError('session_busy')
  27. def _require_transcript_unleased(db, conn, sid):
  28. # A logical owner closed by compression is an ancestor, not a transcript
  29. # target; its live successor (also in session_ids) carries the lease/lock.
  30. if _ended_by_compression(conn.execute(_ENDED_ROW_SQL, (sid,)).fetchone()):
  31. return
  32. db._check_transcript_write_guards(conn, sid, None,
  33. reject_active_turn_lease=True, reject_active_compression_lock=True)
  34. def require_target_advanceable(db, conn, session_ids):
  35. """Fence for writes that publish a new physical target (reset, compress, model):
  36. refuse executing/unknown work and live transcript leases, never a queued follower,
  37. which waits on the logical owner and runs against whatever target is published."""
  38. require_not_executing(conn, session_ids)
  39. for sid in session_ids:
  40. _require_transcript_unleased(db, conn, sid)
  41. def require_idle(db, conn, session_ids):
  42. for sid in session_ids:
  43. admissions = conn.execute("SELECT status FROM session_admissions WHERE target_session_id=? AND status IN ('queued','started','unknown')", (sid,)).fetchall()
  44. workers = conn.execute("SELECT status FROM worker_executions WHERE session_id=? AND status IN ('registered','running','unknown')", (sid,)).fetchall()
  45. states = {row[0] for row in [*admissions, *workers]}
  46. if 'unknown' in states:
  47. raise RuntimeStoreError('unknown_execution')
  48. if states:
  49. raise RuntimeStoreError('session_busy')
  50. _require_transcript_unleased(db, conn, sid)
  51. def _continuation_edges(conn, sid):
  52. """One both-direction compression step from *sid*: its continuation children and its
  53. compression parent. Fork markers are matched against the edge's parent id (the
  54. ``_non_continuation_child_sql`` rule), never by presence: a continuation copies its parent's
  55. ``model_config``, so an inherited ``_branched_from``/``_delegate_from`` naming an older row
  56. does not make it a fork, and a delegate's continuation published by a canonical ``compress``
  57. carries no marker at all."""
  58. from hermes_state_common import _non_continuation_child_sql
  59. edge = _non_continuation_child_sql('child.', 'parent.id')
  60. rows = conn.execute(
  61. 'SELECT child.id FROM sessions parent JOIN sessions child ON child.parent_session_id=parent.id '
  62. "WHERE parent.id=? AND parent.end_reason='compression'\n" + edge
  63. + ' UNION SELECT parent.id FROM sessions child JOIN sessions parent ON parent.id=child.parent_session_id '
  64. "WHERE child.id=? AND parent.end_reason='compression'\n" + edge, (sid, sid)).fetchall()
  65. return [row[0] for row in rows]
  66. def delete_targets(conn, session_id):
  67. from hermes_state_sessions import _collect_delegate_child_ids
  68. import json
  69. from hermes_state_compression import _CHAIN_CAP
  70. from hermes_state_local import POLICY_PREFIX
  71. from hermes_state_local_lineage import validate_local_lineage
  72. from hermes_state_local import local_lineage_owner
  73. targets = {session_id}
  74. # A reset/compression segment of a local conversation is that conversation: the listing
  75. # shows one row for it, so its delete takes the creation id (policy, FIFO) and every segment.
  76. owner = local_lineage_owner(conn, session_id)
  77. targets.add(owner)
  78. saved = conn.execute('SELECT value FROM state_meta WHERE key=?',
  79. (POLICY_PREFIX + owner,)).fetchone()
  80. if saved is not None:
  81. receipt = json.loads(saved[0])
  82. validate_local_lineage(conn, receipt)
  83. targets.update(receipt.get('lineage', [session_id]))
  84. # Canonical admissions bind to the compression root for every producer, not only
  85. # local receipts: every physical continuation of a target goes with it, or the next
  86. # message on the route re-admits the "deleted" conversation through the surviving child.
  87. # The walk also runs BACKWARD to the root (#57543): a sidebar row carries the chain tip's
  88. # id, and a surviving root re-projects as the "deleted" conversation on the next reload.
  89. # Every walked row must belong to its anchor's principal domain: only the requested row was
  90. # authorized, so a parent link into another principal's chain (an imported or forged edge)
  91. # stops the walk instead of deleting their conversation. A delegate subtree is the parent's
  92. # by construction and anchors its own chain (a continuation copies the delegate's route).
  93. # Delegates and continuations close over each other to a fixed point: a compressed
  94. # delegate's continuation (and its queued work) goes with it, or require_idle never sees it
  95. # and the delete orphans it.
  96. from hermes_state_mutation_binding import same_history_owner
  97. anchor = dict.fromkeys(targets, session_id)
  98. frontier = list(targets)
  99. for _ in range(_CHAIN_CAP):
  100. found = {}
  101. for sid in frontier:
  102. for nxt in _continuation_edges(conn, sid):
  103. if nxt not in targets and nxt not in found and same_history_owner(conn, anchor[sid], nxt):
  104. found[nxt] = anchor[sid]
  105. for sid in _collect_delegate_child_ids(conn, frontier):
  106. if sid not in targets:
  107. found.setdefault(sid, sid)
  108. if not found:
  109. break
  110. anchor.update(found)
  111. targets.update(found)
  112. frontier = list(found)
  113. return [session_id, *sorted(targets - {session_id})]