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


##########
ontogeny/server/ontogeny/action/runtime.py:
##########
@@ -153,6 +166,95 @@ async def validate(
             "policy": {"allow": decision.allow, "reason": decision.reason},
         }
 
+    @asynccontextmanager
+    async def idempotency_guard(
+        self,
+        action_name: str,
+        principal: dict,
+        idempotency_key: str | None,
+    ) -> AsyncIterator[None]:
+        """Serialize a keyed execution through its session commit or rollback.
+
+        The caller owns the transaction, so this guard must wrap both execute()
+        and the session lifecycle; releasing inside execute() would let a 
waiter
+        replay-check before the first caller's revision becomes visible.
+        """
+        if not idempotency_key:
+            yield
+            return
+        key = (action_name, str(principal.get("id", "anonymous")), 
idempotency_key)
+        lock = self._key_locks.get(key)
+        if lock is None:
+            lock = asyncio.Lock()
+            self._key_locks[key] = lock
+        async with lock:
+            yield
+
+    async def _find_revision(
+        self,
+        session,
+        action_name: str,
+        principal: dict,
+        idempotency_key: str | None,
+    ) -> RevisionRow | None:
+        if not idempotency_key:
+            return None
+        return (
+            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()
+
+    async def _find_revision_by_key(self, session, idempotency_key: str) -> 
RevisionRow | None:
+        """Look the key up without its scope: the unique index is key-only."""
+        return (
+            await 
session.execute(select(RevisionRow).where(RevisionRow.idempotency_key == 
idempotency_key))
+        ).scalar_one_or_none()
+
+    async def await_committed_revision(
+        self,
+        session,
+        action_name: str,
+        principal: dict,
+        idempotency_key: str | None,
+        *,
+        attempts: int = 20,
+        delay: float = 0.05,
+    ) -> RevisionRow | None:
+        """Resolve a unique-index conflict on a keyed execution.
+
+        A lock only serializes one process. When another worker wins the race,
+        the loser rolls back and waits briefly for the winner's committed
+        revision to become visible, then returns it instead of surfacing a 500.
+
+        The unique index covers the key alone while the replay lookup is scoped
+        to (action, principal, key). A key owned by another scope would 
therefore
+        never be found by the scoped lookup, so polling it can only hold the
+        connection and the key lock until the caller turns the miss into a
+        misleading 500: detect that case up front and report the conflict.
+        """
+        if not idempotency_key:
+            return None
+        for attempt in range(attempts):
+            rev = await self._find_revision(session, action_name, principal, 
idempotency_key)
+            if rev is not None:
+                if rev.outcome == "executed":
+                    return rev
+                raise ConflictError(f"idempotency key {idempotency_key!r} 
belongs to a {rev.outcome} revision")
+            owner = await self._find_revision_by_key(session, idempotency_key)
+            if owner is not None:
+                raise ConflictError(

Review Comment:
   **⚠️ Avoid disclosing the key owner**
   
   An anonymous caller can submit a guessed key belonging to another principal. 
A denied action attempts to flush its audit revision before raising the policy 
denial; the unique-key failure reaches this fallback and the 409 reveals the 
other principal and action. Please return a generic conflict without the 
foreign owner details. This path follows from source inspection and was not 
reproduced over HTTP.



##########
ontogeny/server/ontogeny/api/routes_objects.py:
##########
@@ -203,18 +204,49 @@ async def execute_action(
         started = time.perf_counter()
         from ..errors import PolicyDeniedError, RuleRejectedError
 
-        async with sc.sessionmaker() as s:
+        # Keep same-key executions serialized until the revision is committed;
+        # exiting the session first also rolls back failures before unlocking.
+        async with (
+            sc.runtime.idempotency_guard(action_name, principal, 
body.idempotency_key),

Review Comment:
   **⚠️ Serialize function execution across workers**
   
   This guard is process-local, so two workers can miss the same key and both 
enter a function-backed action before either inserts its revision. The function 
sandbox can call the external LLM; rolling back the losing transaction cannot 
undo that request or its cost, even if the response is replayed. Please reserve 
or serialize the key across workers before executing the function, or 
explicitly narrow the idempotency guarantee. This interleaving was verified 
from source, not reproduced across processes.



##########
ontogeny/server/ontogeny/api/routes_objects.py:
##########
@@ -203,18 +204,49 @@ async def execute_action(
         started = time.perf_counter()
         from ..errors import PolicyDeniedError, RuleRejectedError
 
-        async with sc.sessionmaker() as s:
+        # Keep same-key executions serialized until the revision is committed;
+        # exiting the session first also rolls back failures before unlocking.
+        async with (
+            sc.runtime.idempotency_guard(action_name, principal, 
body.idempotency_key),
+            sc.sessionmaker() as s,
+        ):
             try:
-                rev = await sc.runtime.execute(
-                    s,
-                    action_name,
-                    principal,
-                    body.parameters,
-                    body.target_id,
-                    expected_revision=body.expected_revision,
-                    idempotency_key=body.idempotency_key,
-                )
-                await s.commit()
+                try:
+                    rev = await sc.runtime.execute(
+                        s,
+                        action_name,
+                        principal,
+                        body.parameters,
+                        body.target_id,
+                        expected_revision=body.expected_revision,
+                        idempotency_key=body.idempotency_key,
+                    )
+                    await s.commit()
+                except IntegrityError:
+                    # The per-key lock only serializes one process. When 
another
+                    # worker wins the same key, roll back and resolve the 
winner's
+                    # committed revision instead of surfacing a 500.
+                    if not body.idempotency_key:
+                        raise
+                    await s.rollback()
+                    rev = await sc.runtime.await_committed_revision(s, 
action_name, principal, body.idempotency_key)
+                    if rev is None:
+                        raise
+                except ConflictError:

Review Comment:
   **⚠️ Recheck after a concurrent archive**
   
   Two workers can both miss the replay lookup; if the first commits an archive 
before the second loads its target, `execute()` raises `NotFoundError` because 
the current row is gone. The fallback handles integrity and conflict errors 
only, so the retry returns 404 instead of the committed revision. The shipped 
`retract-inspection` action uses `archive-object`. Please cover this 
interleaving and recheck the key after rollback on this path. This is 
source-derived, not a multi-process reproduction.



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