bitflicker64 commented on code in PR #439:
URL: https://github.com/apache/hugegraph-ai/pull/439#discussion_r4654370174


##########
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:
   Important: `_key_locks` gains one entry per distinct `(action, principal, 
idempotency_key)` and never drops it, so a long-running server leaks about 290 
bytes per keyed request. Drop the entry once no caller holds or waits on it, 
for example by making `_key_locks` a `weakref.WeakValueDictionary`.



##########
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:
   Important: the lock is released when `execute()` returns, before the route's 
`await s.commit()`, so the next waiter's replay lookup runs on another pooled 
connection, misses the uncommitted revision and raises the same `UNIQUE 
constraint failed: ontogeny_revision.idempotency_key`. Hold the lock until the 
revision commits, for example with a per-key guard the route holds across 
`execute()` and `commit()`.
   
   The new tests pass only because `sqlite+aiosqlite:///:memory:` shares one 
`StaticPool` connection; on a file DSN with a warm pool, 4 concurrent same-key 
creates still fail once per round.



-- 
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]

Reply via email to