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


##########
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:
   Fixed.`await_committed_revision()` no longer includes the owner's action or 
principal in the 409. When a key exists outside the caller's`(action, 
principal)` scope it now raises a generic conflict, keeping only the key the 
caller already supplied:
   
   Python
   `raise ConflictError(f"idempotency key {idempotency_key!r} is already in 
use")`
   
   This is exactly the path you described: the denied action flushes its audit 
revision before raising, so the unique-key collision lands in this fallback. 
Added a regression test that models an anonymous probing 
caller:`test_foreign_scope_key_conflict_does_not_disclose_owner` has a`visitor` 
(no planner role) submit a key already owned by`u-planner` on a 
denied`release-production-order` . It asserts`409` , an empty`details` payload, 
that the response contains the caller's key but not`u-planner` 
or`create-production-order` , and that it fails fast (< 1s) instead of burning 
the polling budget.



##########
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:
   Fixed.`await_committed_revision()` no longer includes the owner's action or 
principal in the 409. When a key exists outside the caller's`(action, 
principal)` scope it now raises a generic conflict, keeping only the key the 
caller already supplied:
   
   Python
   `raise ConflictError(f"idempotency key {idempotency_key!r} is already in 
use")`
   
   This is exactly the path you described: the denied action flushes its audit 
revision before raising, so the unique-key collision lands in this fallback. 
Added a regression test that models an anonymous probing 
caller:`test_foreign_scope_key_conflict_does_not_disclose_owner` has a`visitor` 
(no planner role) submit a key already owned by`u-planner` on a 
denied`release-production-order` . It asserts`409` , an empty`details` payload, 
that the response contains the caller's key but not`u-planner` 
or`create-production-order` , and that it fails fast (< 1s) instead of burning 
the polling budget.



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