session_worker_child.py 5.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. """Owner-reserved delegated children of a verified worker execution (#141793).
  2. A worker never mints a child. It asks on its OWN fenced receipt stream (epoch, assignment,
  3. generation, sequence), and the owner creates the child's session row and execution, binds it to
  4. the parent's verified process identity and the worker's fresh secret, and enforces the frozen
  5. policy's delegation caps. The child then persists through the ordinary ``worker.persist`` path
  6. under its own claim. Expected refusals (caps, draining) are receipts, not errors: an error would
  7. leave the parent's journal pending and refuse every later write of its turn.
  8. """
  9. import secrets
  10. from functools import partial
  11. from hermes_state_runtime import RuntimeStoreError, apply_worker_receipt
  12. from hermes_state_runtime_workers import CHILD_SEPARATOR, descendant_range
  13. _DEFAULTS = {'max_concurrent_children': 10, 'max_spawn_depth': 1}
  14. def _limit(section, key):
  15. try:
  16. return max(1, int(section.get(key, _DEFAULTS[key])))
  17. except (TypeError, ValueError):
  18. return _DEFAULTS[key]
  19. def delegation_limits(authority, execution_id, session_id):
  20. """``(max_concurrent_children, max_spawn_depth)`` from the root conversation's frozen policy
  21. (the profile's config for a session with no local policy), never from the asking worker."""
  22. from gateway.session_policy import policy_for_source, profile_config
  23. root = execution_id.split(CHILD_SEPARATOR, 1)[0]
  24. if root != execution_id:
  25. with authority.db._read_ctx() as conn:
  26. row = conn.execute('SELECT session_id FROM worker_executions WHERE execution_id=?', (root,)).fetchone()
  27. session_id = row[0] if row else session_id
  28. live = authority.sessions.get(authority.logical_owner(session_id))
  29. policy = policy_for_source(authority.runner, live.source) if live is not None else None
  30. config = policy.config(authority) if policy is not None else profile_config(authority)
  31. section = config.get('delegation') or {}
  32. return _limit(section, 'max_concurrent_children'), _limit(section, 'max_spawn_depth')
  33. def reserve_child_execution(db, conn, session_id, payload, *, epoch, execution_id, identity, principal, limits, refused):
  34. from hermes_state_ids import new_session_id
  35. from hermes_state_keys import admission_fingerprint
  36. from hermes_state_runtime import _secret_digest
  37. from hermes_state_worker_lifecycle import insert_session_row_in_transaction
  38. secret = payload.get('secret') if isinstance(payload, dict) else None
  39. if set(payload) != {'secret'} or not isinstance(secret, str) or not 16 <= len(secret) <= 256:
  40. raise RuntimeStoreError('invalid_params')
  41. max_children, max_depth = limits
  42. prefix = execution_id + CHILD_SEPARATOR
  43. live = conn.execute("SELECT COUNT(*) FROM worker_executions WHERE execution_id>=? AND execution_id<? "
  44. "AND instr(substr(execution_id,?),'/')=0 AND status!='terminal'",
  45. (*descendant_range(execution_id), len(prefix) + 1)).fetchone()[0]
  46. if refused is None and prefix.count(CHILD_SEPARATOR) > max_depth:
  47. refused = 'delegation_depth_exceeded'
  48. if refused is None and live >= max_children:
  49. refused = 'delegation_capacity'
  50. if refused is not None:
  51. return {'refused': refused}
  52. parent = conn.execute('SELECT profile_name FROM sessions WHERE id=?', (session_id,)).fetchone()
  53. child_sid, child_eid = new_session_id(), prefix + secrets.token_hex(8)
  54. insert_session_row_in_transaction(db, conn, child_sid, 'subagent', model_config={'_delegate_from': session_id},
  55. parent_session_id=session_id, profile_name=parent['profile_name'])
  56. scope = dict(identity, session_id=child_sid, execution_id=child_eid, generation=0, secret=secret)
  57. claim = admission_fingerprint(canonical_target=child_sid, payload=scope | {'principal': principal})
  58. conn.execute("INSERT INTO worker_executions(execution_id,session_id,kind,owner_epoch,generation,status,adoption_digest) "
  59. "VALUES(?,?,'child',?,0,'running',?)", (child_eid, child_sid, epoch, _secret_digest(claim)))
  60. return {'child': {'session_id': child_sid, 'execution_id': child_eid, 'generation': 0}}
  61. async def worker_child_request(connection, ref, params):
  62. """worker.persist ``child.reserve``: the parent's full claim and assignment are verified first."""
  63. import asyncio
  64. from gateway.session_worker import _SCOPE, _claim, _verify
  65. if set(params) != _SCOPE | {'epoch', 'sequence', 'operation', 'payload'}:
  66. raise RuntimeStoreError('invalid_params')
  67. claim = _claim(connection, ref, params)
  68. if 'worker:adopt' not in connection.actor.capabilities:
  69. raise RuntimeStoreError('permission_denied')
  70. _verify(connection, ref, params, claim)
  71. authority = connection.authority
  72. def reserve():
  73. refused, limits = None, (0, 0)
  74. try:
  75. authority._require_admission_open()
  76. limits = delegation_limits(authority, params['execution_id'], params['session_id'])
  77. except RuntimeStoreError as exc:
  78. refused = exc.reason
  79. handler = partial(reserve_child_execution, epoch=params['epoch'], execution_id=params['execution_id'],
  80. identity={key: params[key] for key in ('profile_id', 'pid', 'birth')},
  81. principal=connection.actor.subject, limits=limits, refused=refused)
  82. return apply_worker_receipt(authority.db, **{key: params[key] for key in (
  83. 'epoch', 'execution_id', 'session_id', 'generation', 'sequence', 'operation', 'payload')},
  84. handlers={'child.reserve': handler})
  85. return await asyncio.to_thread(reserve)