ZhYQ1 commented on code in PR #439:
URL: https://github.com/apache/hugegraph-ai/pull/439#discussion_r4657452497
##########
ontogeny/server/ontogeny/action/runtime.py:
##########
@@ -104,6 +105,13 @@ def __init__(
# (PO-000001 twice). The insert guard turns restart-time collisions
# into a 409 instead of duplicate alive rows.
self._id_seq: dict[str, int] = {}
+ # R3: per-key asyncio locks serializing concurrent same-key idempotent
+ # replays on SQLite (which has no advisory lock). Only one caller then
+ # executes the effects and records its revision; the rest replay the
+ # committed revision. The (action, principal, idempotency_key) unique
+ # index stays as the final backstop for writers this lock cannot cover
+ # (multi-process deployments, dialect-specific paths).
+ self._key_locks: dict[tuple[str, str, str], asyncio.Lock] = {}
Review Comment:
Fixed in d043c71. The registry now lives on`ServiceContext`
(`_action_key_locks` ) and is passed into every`ActionRuntime` created
by`_rebuild_services()` , so`publish()` ,`reload()` and domain switching reuse
the same locks. Added`test_key_locks_survive_service_rebuild` : it holds a lock
on the old runtime, rebuilds the services, and asserts the new runtime's guard
for the same key blocks until the old request releases.
##########
ontogeny/server/ontogeny/action/runtime.py:
##########
@@ -168,140 +176,164 @@ async def execute(
if action is None:
raise NotFoundError(f"unknown action {action_name!r}")
- # 1) idempotent replay
+ # R3: SQLite has no advisory lock, so concurrent same-key replays are
+ # serialized per key (action, principal, key) on the event loop before
+ # the replay check runs. Only one caller then executes the effects and
+ # records its revision; the waiters replay the committed revision. The
+ # (action, principal, idempotency_key) unique index stays the final
+ # backstop for writers this per-key lock cannot cover.
+ key_lock: asyncio.Lock | None = None
if idempotency_key:
- existing = (
- await session.execute(
- select(RevisionRow).where(
- RevisionRow.idempotency_key == idempotency_key,
- RevisionRow.action == action_name,
- RevisionRow.principal == str(principal.get("id",
"anonymous")),
+ key = (action_name, str(principal.get("id", "anonymous")),
idempotency_key)
+ key_lock = self._key_locks.setdefault(key, asyncio.Lock())
Review Comment:
Fixed in d043c71:`_key_locks` is now a`weakref.WeakValueDictionary` . The
guard holds the only strong reference while executing, so entries are collected
once no caller holds or waits on a lock.
Added`test_key_locks_are_collected_after_each_guard` (20 distinct keys,
registry empty afterwards); the concurrent HTTP test also asserts the registry
is empty after the requests finish.
##########
ontogeny/server/ontogeny/action/runtime.py:
##########
@@ -168,140 +176,164 @@ async def execute(
if action is None:
raise NotFoundError(f"unknown action {action_name!r}")
- # 1) idempotent replay
+ # R3: SQLite has no advisory lock, so concurrent same-key replays are
+ # serialized per key (action, principal, key) on the event loop before
+ # the replay check runs. Only one caller then executes the effects and
+ # records its revision; the waiters replay the committed revision. The
+ # (action, principal, idempotency_key) unique index stays the final
+ # backstop for writers this per-key lock cannot cover.
+ key_lock: asyncio.Lock | None = None
if idempotency_key:
- existing = (
- await session.execute(
- select(RevisionRow).where(
- RevisionRow.idempotency_key == idempotency_key,
- RevisionRow.action == action_name,
- RevisionRow.principal == str(principal.get("id",
"anonymous")),
+ key = (action_name, str(principal.get("id", "anonymous")),
idempotency_key)
+ key_lock = self._key_locks.setdefault(key, asyncio.Lock())
+ await key_lock.acquire()
+ try:
+ # 1) idempotent replay (only meaningful when a key is supplied;
+ # the key scopes the lookup to (action, principal,
idempotency_key))
+ if idempotency_key:
+ existing = (
+ await session.execute(
+ select(RevisionRow).where(
+ RevisionRow.idempotency_key == idempotency_key,
+ RevisionRow.action == action_name,
+ RevisionRow.principal == str(principal.get("id",
"anonymous")),
+ )
)
+ ).scalar_one_or_none()
+ if existing is not None:
+ if existing.outcome == "executed":
+ return existing
+ raise ConflictError(f"idempotency key {idempotency_key!r}
belongs to a {existing.outcome} revision")
+
+ params = self._bind_parameters(action, parameters)
+
+ async def _record(
+ outcome: str,
+ message: str | None,
+ before=None,
+ after=None,
+ rules_hit=None,
+ decision=None,
+ obj_id: str | None = None,
+ ) -> RevisionRow:
+ rev = RevisionRow(
+ action=action_name,
+ object_type=action.spec.target,
+ object_id=str(obj_id or target_id or ""),
+ principal=str(principal.get("id", "anonymous")),
+ params=_jsonable(params),
+ before=_jsonable(before),
+ after=_jsonable(after),
+ rules_hit=rules_hit,
+ policy_decision=None if decision is None else {"allow":
decision.allow, "reason": decision.reason},
+ outcome=outcome,
+ message=message,
+ idempotency_key=idempotency_key,
)
- ).scalar_one_or_none()
- if existing is not None:
- if existing.outcome == "executed":
- return existing
- raise ConflictError(f"idempotency key {idempotency_key!r}
belongs to a {existing.outcome} revision")
-
- params = self._bind_parameters(action, parameters)
-
- async def _record(
- outcome: str,
- message: str | None,
- before=None,
- after=None,
- rules_hit=None,
- decision=None,
- obj_id: str | None = None,
- ) -> RevisionRow:
- rev = RevisionRow(
- action=action_name,
- object_type=action.spec.target,
- object_id=str(obj_id or target_id or ""),
- principal=str(principal.get("id", "anonymous")),
- params=_jsonable(params),
- before=_jsonable(before),
- after=_jsonable(after),
- rules_hit=rules_hit,
- policy_decision=None if decision is None else {"allow":
decision.allow, "reason": decision.reason},
- outcome=outcome,
- message=message,
- idempotency_key=idempotency_key,
+ session.add(rev)
+ await session.flush()
+ return rev
+
+ # 2) load + rules (evaluated INSIDE the transaction on latest
state)
+ target: dict | None = None
+ if target_id is not None:
+ target = await self.repo.get(session, action.spec.target,
target_id, for_update=True)
+ if target is None:
+ raise NotFoundError(f"{action.spec.target}/{target_id} not
found (or archived)")
+ ctx = _expr.ExprContext(
+ target=target or {}, parameters=params, principal=principal,
now=utcnow(), _seq=self._id_seq
)
- session.add(rev)
- await session.flush()
- return rev
+ rules_hit = []
+ for rule in action.spec.rules:
+ ok = bool(_expr.evaluate(rule.expr, ctx))
+ rules_hit.append({"expr": rule.expr, "ok": ok})
+ if not ok:
+ rev = await _record(
+ "rejected_rule", rule.message or "rule rejected",
before=target, rules_hit=rules_hit
+ )
+ # Rules run before any data write, so the session holds
nothing but
+ # this audit row: commit it here and the rejection is
recorded no
+ # matter which shell (REST/MCP/CLI/eval) invoked the
action.
+ await session.commit()
+ raise RuleRejectedError(
+ rule.message or f"rule rejected: {rule.expr}",
+ details={"revision_id": rev.id, "rule": rule.expr},
+ )
- # 2) load + rules (evaluated INSIDE the transaction on latest state)
- target: dict | None = None
- if target_id is not None:
- target = await self.repo.get(session, action.spec.target,
target_id, for_update=True)
- if target is None:
- raise NotFoundError(f"{action.spec.target}/{target_id} not
found (or archived)")
- ctx = _expr.ExprContext(
- target=target or {}, parameters=params, principal=principal,
now=utcnow(), _seq=self._id_seq
- )
- rules_hit = []
- for rule in action.spec.rules:
- ok = bool(_expr.evaluate(rule.expr, ctx))
- rules_hit.append({"expr": rule.expr, "ok": ok})
- if not ok:
+ # 3) policy at the last meter
+ decision = self.policy.decide(principal, action_name, target)
+ if not decision.allow:
rev = await _record(
- "rejected_rule", rule.message or "rule rejected",
before=target, rules_hit=rules_hit
- )
- # Rules run before any data write, so the session holds
nothing but
- # this audit row: commit it here and the rejection is recorded
no
- # matter which shell (REST/MCP/CLI/eval) invoked the action.
- await session.commit()
- raise RuleRejectedError(
- rule.message or f"rule rejected: {rule.expr}",
- details={"revision_id": rev.id, "rule": rule.expr},
+ "denied_policy", decision.reason, before=target,
rules_hit=rules_hit, decision=decision
)
+ await session.commit() # same reasoning as the rule-rejection
path
+ from ..errors import PolicyDeniedError
- # 3) policy at the last meter
- decision = self.policy.decide(principal, action_name, target)
- if not decision.allow:
- rev = await _record("denied_policy", decision.reason,
before=target, rules_hit=rules_hit, decision=decision)
- await session.commit() # same reasoning as the rule-rejection path
- from ..errors import PolicyDeniedError
-
- raise PolicyDeniedError(
- f"policy denied {action_name!r}: {decision.reason}",
- details={"revision_id": rev.id},
- )
-
- # 4) effect plan (declarative, or sandbox-provided for function-backed)
- effects: list[Any] = list(action.spec.effects)
- if action.spec.execution is not None:
- if self.function_runner is None:
- raise OOError("function-backed action requires a configured
function runner")
- plan = await self.function_runner(session,
action.spec.execution.entry, params, ctx)
- effects = [self._materialize_plan_entry(entry) for entry in plan]
-
- before = dict(target) if target else None
- after: dict | None = None
- created_id: str | None = None
- linked_pairs: list[tuple[str, str]] = [] # (object_type, id) changed
via modify-linked
- ts = utcnow()
+ raise PolicyDeniedError(
+ f"policy denied {action_name!r}: {decision.reason}",
+ details={"revision_id": rev.id},
+ )
- for eff in effects:
- if getattr(eff, "when", None) is not None and not
bool(_expr.evaluate(eff.when, ctx)):
- continue
- outcome = await self._apply_effect(
- session, action, eff, ctx, target_id, expected_revision if
after is None and before else None, ts
- )
- if outcome is not None:
- after, created_id = outcome[0], outcome[1] or created_id
- linked_pairs.extend(outcome[2] or [])
-
- # 5) audit revision + outbox (same transaction)
- effective_id = created_id or target_id
- if after is None:
- after = await self.repo.get(session, action.spec.target,
effective_id)
- rev = await _record(
- "executed", None, before=before, after=after, rules_hit=rules_hit,
decision=decision, obj_id=effective_id
- )
- for op, oid, payload in self._outbox_events(
- action,
- effects,
- before,
- after,
- effective_id,
- ctx,
- linked_pairs,
- ):
- session.add(
- OutboxRow(
- # linked-object events carry their own type in the payload
- object_type=payload.get("object_type", action.spec.target),
- object_id=oid or "",
- op=op,
- payload=_jsonable(payload),
- revision_id=rev.id,
+ # 4) effect plan (declarative, or sandbox-provided for
function-backed)
+ effects: list[Any] = list(action.spec.effects)
+ if action.spec.execution is not None:
+ if self.function_runner is None:
+ raise OOError("function-backed action requires a
configured function runner")
+ plan = await self.function_runner(session,
action.spec.execution.entry, params, ctx)
+ effects = [self._materialize_plan_entry(entry) for entry in
plan]
+
+ before = dict(target) if target else None
+ after: dict | None = None
+ created_id: str | None = None
+ linked_pairs: list[tuple[str, str]] = [] # (object_type, id)
changed via modify-linked
+ ts = utcnow()
+
+ for eff in effects:
+ if getattr(eff, "when", None) is not None and not
bool(_expr.evaluate(eff.when, ctx)):
+ continue
+ outcome = await self._apply_effect(
+ session, action, eff, ctx, target_id, expected_revision if
after is None and before else None, ts
)
+ if outcome is not None:
+ after, created_id = outcome[0], outcome[1] or created_id
+ linked_pairs.extend(outcome[2] or [])
+
+ # 5) audit revision + outbox (same transaction)
+ effective_id = created_id or target_id
+ if after is None:
+ after = await self.repo.get(session, action.spec.target,
effective_id)
+ rev = await _record(
+ "executed",
+ None,
+ before=before,
+ after=after,
+ rules_hit=rules_hit,
+ decision=decision,
+ obj_id=effective_id,
)
- return rev
+ for op, oid, payload in self._outbox_events(
+ action,
+ effects,
+ before,
+ after,
+ effective_id,
+ ctx,
+ linked_pairs,
+ ):
+ session.add(
+ OutboxRow(
+ # linked-object events carry their own type in the
payload
+ object_type=payload.get("object_type",
action.spec.target),
+ object_id=oid or "",
+ op=op,
+ payload=_jsonable(payload),
+ revision_id=rev.id,
+ )
+ )
+ return rev
+ finally:
+ if key_lock is not None:
+ key_lock.release()
Review Comment:
Fixed in d043c71.`execute()` no longer acquires or releases any lock; the
route now holds`ActionRuntime.idempotency_guard()` across`execute()` and the
session, so the lock is released only after commit or rollback (the session
closes first). Tests now use a file-backed DSN with a warm
pool:`TestSqliteIdempotencyConcurrency` runs 8 concurrent same-key creates
and`test_concurrent_same_key_action_execute` runs 4 concurrent same-key HTTP
requests, both asserting a single revision row and identical revision ids. With
a widened execute-to-commit window the old behavior reproduces`UNIQUE
constraint failed: ontogeny_revision.idempotency_key` ; the guard version
returns the same revision to all callers.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]